@pickaxeproject/react 6.18.0 → 6.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/chatMessages.js +1 -1
- package/dist/cjs/components/Pickaxe/Chat/History/Message.js +1 -1
- package/dist/cjs/components/Pickaxe/Chat/History/index.js +1 -1
- package/dist/cjs/components/Pickaxe/Chat/Input.js +1 -1
- package/dist/cjs/components/Pickaxe/Form/History/Response.js +1 -1
- package/dist/cjs/components/Pickaxe/common/PickaxeMarkdown/Components/Action/index.js +1 -1
- package/dist/cjs/components/Pickaxe/common/PickaxeMarkdown/index.js +1 -1
- package/dist/cjs/components/Pickaxe/common/PickaxeMessageParts/ActionToolCaptionPart/index.js +1 -1
- package/dist/cjs/components/Pickaxe/common/PickaxeMessageParts/ReasoningCaptionPart/index.js +1 -1
- package/dist/cjs/components/Pickaxe/common/PickaxeMessageParts/index.js +1 -1
- package/dist/cjs/hooks/pickaxe/useTextToSpeech.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/chatMessages.d.ts +1 -1
- package/dist/cjs/src/components/Pickaxe/common/PickaxeMarkdown/hooks/usePickaxeMarkdownContext.d.ts +1 -0
- package/dist/cjs/src/components/Pickaxe/common/PickaxeMarkdown/index.d.ts +3 -1
- package/dist/cjs/src/components/Pickaxe/common/PickaxeMessageParts/ActionToolCaptionPart/index.d.ts +2 -1
- package/dist/cjs/src/components/Pickaxe/common/PickaxeMessageParts/ReasoningCaptionPart/index.d.ts +2 -1
- package/dist/cjs/src/components/Pickaxe/common/PickaxeMessageParts/index.d.ts +2 -1
- package/dist/esm/common/chatMessages.js +1 -1
- package/dist/esm/components/Pickaxe/Chat/History/Message.js +1 -1
- package/dist/esm/components/Pickaxe/Chat/History/index.js +1 -1
- package/dist/esm/components/Pickaxe/Chat/Input.js +1 -1
- package/dist/esm/components/Pickaxe/Form/History/Response.js +1 -1
- package/dist/esm/components/Pickaxe/common/PickaxeMarkdown/Components/Action/index.js +1 -1
- package/dist/esm/components/Pickaxe/common/PickaxeMarkdown/index.js +1 -1
- package/dist/esm/components/Pickaxe/common/PickaxeMessageParts/ActionToolCaptionPart/index.js +1 -1
- package/dist/esm/components/Pickaxe/common/PickaxeMessageParts/ReasoningCaptionPart/index.js +1 -1
- package/dist/esm/components/Pickaxe/common/PickaxeMessageParts/index.js +1 -1
- package/dist/esm/hooks/pickaxe/useTextToSpeech.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/chatMessages.d.ts +1 -1
- package/dist/esm/src/components/Pickaxe/common/PickaxeMarkdown/hooks/usePickaxeMarkdownContext.d.ts +1 -0
- package/dist/esm/src/components/Pickaxe/common/PickaxeMarkdown/index.d.ts +3 -1
- package/dist/esm/src/components/Pickaxe/common/PickaxeMessageParts/ActionToolCaptionPart/index.d.ts +2 -1
- package/dist/esm/src/components/Pickaxe/common/PickaxeMessageParts/ReasoningCaptionPart/index.d.ts +2 -1
- package/dist/esm/src/components/Pickaxe/common/PickaxeMessageParts/index.d.ts +2 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
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{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as d,useMemo as c,useImperativeHandle as u}from"react";import{usePickaxeContext as m}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as p}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as g}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as f}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as v}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as h}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as j}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as I}from"../../../hooks/core/useHover.js";import{useMediaQuery as w}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as O,allowedImageMimeTypes as k,additionalAllowedFileExtensions as N}from"../../../common/documents.js";import{createParser as S}from"eventsource-parser";import C from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/message-clock.svg.js";import U from"../../Icons/stop.svg.js";import P from"../../Icons/trash.svg.js";import A from"../../Icons/pencil.svg.js";import D from"../Addons/Document/List.js";import L from"../../Core/Textarea.js";import R from"../../Core/ErrorAlert.js";import M from"../../Core/Menu/index.js";import $ from"../../Core/Menu/Button.js";import B from"../../Core/Menu/List.js";import X from"../../../common/error.js";import{getUnpersistedMemoryMessages as K}from"../../../common/chatMessages.js";import{pickaxeApi2 as F}from"../../../common/api/pickaxe.js";import{getValidationFailure as V}from"../../../common/validation.js";import G from"../../../common/cn.js";import{buildUpgradeUrl as H,openAuthenticatedPricingUrl as W,initializeEmbedUserId as q}from"../../../common/utils.js";import{getPickaxeConfigMetadata as J}from"../../../common/pickaxeConfig.js";import{readAgentPrefill as z}from"../../../common/agentPrefill.js";import{fireDeploymentSessionInitializedWebhook as Q,fireDeploymentFirstMessageSubmittedWebhook as Y}from"../../../common/deploymentWebhooks.js";import{useStudio as Z}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as ee}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as te}from"../common/PickaxeCommon.js";const ne=(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},se=e=>"string"==typeof e&&e.trim().length>0,oe=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,ie=e=>e.map((e=>Object.assign({},e))),re=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),ae=(e,t)=>{if(e&&"object"==typeof e)return e[t]},le=(e,t)=>{const n=ae(e,t);return se(n)?n:null},de=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},ce=({studioUser:e,deploymentId:t,portalId:n})=>{var s,o;const i=Array.isArray(ae(e,"uses"))?ae(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>se(e)?{type:"deployment",id:e}:se(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}},ue=i((({resubmitPrompt:i,onFocus:ae,onBlur:ue,onInputHeightChange:me,initSmitheryAuthData:pe},ge)=>{var fe,ve,he,be,ye,xe,je,Ie,we,Oe,ke,Ne,Se,Ce,Ee,_e,Te;const{origin:Ue,pickaxeId:Pe,sessionId:Ae,sender:De,senderType:Le,portalId:Re,deploymentId:Me,deploymentType:$e,pickaxe:Be,styles:Xe,colors:Ke,translations:Fe,locale:Ve,forceMobile:Ge,isNewChat:He,isRtl:We,isEmbed:qe,isShowFeedbackMessage:Je,accessGroup:ze,setIsNewChat:Qe,setIsShowIceBreaker:Ye,setValidationStatus:Ze,setValidationUpgradeGroups:et,setValidationUpgradeUrl:tt,setAccessGroup:nt,onUpgrade:st,onGenerateComplete:ot}=m(),{token:it,isLoggedOut:rt,isSent:at,isPricingAuth:lt}=b(),{messages:dt,isGenerating:ct,setMessages:ut,setStatus:mt,setLimitData:pt,setError:gt}=p(),{documents:ft,isUploading:vt,documentError:ht,onFileUpload:bt,setDocuments:yt,setDocumentError:xt}=y(),{studio:jt}=Z(),[It]=w("(max-width: 480px)"),{scrollStartSession:wt,scrollEndSession:Ot,scrollToBottom:kt}=x({auto:!0,smooth:!(Ge||It)}),{artifacts:Nt,currentPopupType:St,setArtifacts:Ct,setCurrentArtifact:Et}=j(),{height:_t}=h(),Tt=v(),[Ut,Pt]=r((()=>z([Me,Pe]).chatInput)),[At,Dt]=r(!1),[Lt,Rt]=r(!1),[Mt,$t]=r(!1),[Bt,Xt]=r([]),[Kt,Ft]=r(!1),[Vt,Gt]=r(null),[Ht,Wt]=r(null),[qt,Jt]=r(null),[zt,Qt]=r(null),[Yt,Zt]=r(!1),[en,tn]=r(!1),[nn,sn]=r(0),on=a(null),rn=a(""),an=a(null),ln=a(null),dn=a(null),cn=a([]),un=a(null),mn=a(null),pn=a(null),gn=a(null),fn=a(new Set),vn=a(null),hn=Math.max(.4*_t,100),{speechTranscript:bn,isSpeechListening:yn,isSpeechProcessing:xn,isSpeechSupported:jn,onStartListening:In,onStopListening:wn}=ee(),On=I(),{isHover:kn}=On,Nn=e(On,["isHover"]),Sn=I(),{isHover:Cn}=Sn,En=e(Sn,["isHover"]),_n=I(),{isHover:Tn}=_n,Un=e(_n,["isHover"]),Pn=f(),An=g(),Dn="undefined"!=typeof window?window.location.hostname:"",Ln="undefined"!=typeof window?window.location.href:"",Rn="undefined"!=typeof window&&window.self!==window.top,Mn=Dn.includes("pickaxe.co")&&!Ln.includes("https://studio.pickaxe.co/_embed")&&!Rn,$n=null!==(ve=null===(fe=null==Be?void 0:Be.documentuploadtype)||void 0===fe?void 0:fe.startsWith("enduserupload"))&&void 0!==ve&&ve,Bn=jn&&(null==Be?void 0:Be.enablevoicetotext),Xn=yn&&!Ut.trim(),Kn=se(Me),Fn="chat-input"===$e&&He&&!at,Vn="chat-input"===$e&<&&rt&&at,Gn=l((e=>{const t=V(e);return!!t&&(gt(""),pt(null),Ze(t.status),nt(t.accessGroup),et(t.upgradeGroups),tt(t.upgradeUrl),!0)}),[gt,pt,Ze,et,tt,nt]),Hn=null!==(he=null==Be?void 0:Be.placeholdertext)&&void 0!==he?he:We?"بماذا تريد أن تتحدث؟":(null==Fe?void 0:Fe["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Wn=At||Lt,qn=l((()=>t(void 0,void 0,void 0,(function*(){Zt(!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==Be?void 0:Be.studioid},it?{studioSessionToken:it}:De?{sender:De}:{sender:q()}))},(!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}})),Mn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(Jt(t.studioUser),Qt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{Zt(!0)}}))),[Mn,null==Be?void 0:Be.studioid,De,it]);d((()=>{qn()}),[qn]);const Jn=Number(null!==(be=null==ze?void 0:ze.limit)&&void 0!==be?be:0),zn="string"==typeof(null==ze?void 0:ze.limitInterval)?ze.limitInterval:null,Qn=!!(null==jt?void 0:jt.data.usage)&&jt.data.usage.isCredits,Yn=c((()=>{var e,t,n,s,o;return null!==(o=null!==(s=null!==(n=null!==(t=null!==(e=null!=Re?Re:le(qt,"portalId"))&&void 0!==e?e:le(qt,"portalid"))&&void 0!==t?t:le(ze,"portalId"))&&void 0!==n?n:le(ze,"portalid"))&&void 0!==s?s:le(Be,"portalId"))&&void 0!==o?o:le(Be,"portalid")}),[ze,Re,Be,qt]),Zn=c((()=>ce({studioUser:qt,deploymentId:Me,portalId:Yn})),[Me,Yn,qt]);d((()=>{Kn&&He&&Ae&&fn.current.add(Ae)}),[He,Ae,Kn]);const es=l((()=>{var e,t,n;return{studioId:null==Be?void 0:Be.studioid,userEmail:le(qt,"email"),userId:null!==(e=le(qt,"userId"))&&void 0!==e?e:le(qt,"userid"),sessionId:Ae,deploymentId:Me,deploymentType:$e,portalId:Yn,accessGroupId:null!==(t=null==ze?void 0:ze.accessGroupId)&&void 0!==t?t:null,pickaxeId:Pe,sender:De,senderType:Le,origin:Ue,metadata:null!==(n=J(Me))&&void 0!==n?n:null}}),[null==ze?void 0:ze.accessGroupId,Me,$e,Ue,null==Be?void 0:Be.studioid,Pe,Yn,De,Le,Ae,qt]),ts=l((()=>!!(Kn&&Yt&&Ae)&&(!!fn.current.has(Ae)&&(Q(es()),fn.current.delete(Ae),!0))),[es,Yt,Ae,Kn]);d((()=>{if(!Yt||!Ae)return;ts();const e=vn.current;(null==e?void 0:e.sessionId)===Ae&&(Y(Object.assign(Object.assign(Object.assign({},e),es()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),vn.current=null)}),[ts,es,Yt,Ae]);const ns={currentUses:de(null==qt?void 0:qt.currentUses),extraUses:de(null==qt?void 0:qt.extraUses)},ss=Zn.scope?{currentUses:null!==(xe=de(null===(ye=Zn.record)||void 0===ye?void 0:ye.currentUses))&&void 0!==xe?xe:0,extraUses:null!==(Ie=de(null===(je=Zn.record)||void 0===je?void 0:je.extraUses))&&void 0!==Ie?Ie:0}:{currentUses:0,extraUses:0},os=le(qt,"type"),is="guest"===os||!os&&rt?ss:ns;d((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(Qn&&(null===(t=null==jt?void 0:jt.data)||void 0===t?void 0:t.workspaceId))try{const t=yield F.get(`/cost_per_run?workspaceId=${jt.data.workspaceId}`,{withCredentials:!1});e&&sn(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&sn(0)}else e&&sn(0)})),()=>{e=!1}}),[Qn,null===(we=null==jt?void 0:jt.data)||void 0===we?void 0:we.workspaceId]);const rs=(({currentUses:e,extraUses:t,limit:n,limitInterval:s})=>{const o=Number(null!=e?e:0),i=Number(null!=t?t:0);return n===te||i===te?te:"one_time"===s?Math.max(0,i-o):Math.max(0,n-o)+i})({currentUses:is.currentUses,extraUses:is.extraUses,limit:Jn,limitInterval:zn}),as=rs===te?te:Math.max(0,Math.ceil(rs)),ls=(({extraUses:e,limit:t,limitInterval:n})=>{const s=Number(null!=e?e:0);return t===te||s===te?te:"one_time"===n?Math.max(0,s):Math.max(0,t)+Math.max(0,s)})({extraUses:is.extraUses,limit:Jn,limitInterval:zn}),ds=ls===te?te:Math.ceil(.05*ls),cs=Qn?Math.ceil(5*nn):5,us=ds===te?te:Math.max(ds,cs),ms=c((()=>!!qt&&(!en&&(as!==te&&as<=us))),[en,us,as,qt]),ps=Boolean(null==ze?void 0:ze.hideUpgradeOptions),gs=Boolean(!ps&&((null===(Oe=null==ze?void 0:ze.upgrade)||void 0===Oe?void 0:Oe.isBuyMoreUses)||(null===(ke=null==ze?void 0:ze.upgrade)||void 0===ke?void 0:ke.isLinkToCustomURL)||(null===(Ne=null==ze?void 0:ze.upgrade)||void 0===Ne?void 0:Ne.isUpgradeToAnotherGroup)&&(null===(Se=ze.upgrade.accessGroupIds)||void 0===Se?void 0:Se.length))),fs=!ps&&(null===(Ce=null==ze?void 0:ze.upgrade)||void 0===Ce?void 0:Ce.isLinkToCustomURL)&&"string"==typeof ze.upgrade.limitLink&&ze.upgrade.limitLink.trim().length>0?ze.upgrade.limitLink.trim():null,vs=fs&&"string"==typeof(null===(Ee=null==ze?void 0:ze.upgrade)||void 0===Ee?void 0:Ee.limitCTA)&&ze.upgrade.limitCTA.trim().length>0?ze.upgrade.limitCTA:(null==Fe?void 0:Fe["pricing.upgrade"])||(null==Fe?void 0:Fe.upgrade)||"Upgrade",hs=c((()=>{var e,t,n;return!!He&&(!!Be&&(!Tt.isLoading&&(!((null!==(t=null===(e=Tt.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=Be.icebreakers)||void 0===n?void 0:n.length)&&(!Je&&!Fn)))))}),[Be,He,Je,Fn,Tt.data,Tt.isLoading]),bs=c((()=>{if(vt||Mt)return!1;const e=$n&&ft.length>0&&ft.every((e=>"finished"===e.status));return!(!Ut.trim()&&!e)&&ft.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[$n,vt,Mt,Ut,ft]);u(ge,(()=>({onSubmit:ws}))),d((()=>{Ye(hs)}),[hs]),d((()=>{var e;if(i){const t=Array.from(dt),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;ws(n,!0)}}),[i]),d((()=>{if(!pn.current||!me)return;const e=new ResizeObserver((e=>{for(const t of e)me(t.contentRect.height)}));return e.observe(pn.current),()=>{e.disconnect()}}),[me]),d((()=>{if(!yn)return;const e=rn.current?`${rn.current} `:"";Pt(`${e}${bn}`)}),[bn,yn]),d((()=>{if(!un.current)return;(()=>{if(!un.current)return;let e=un.current.scrollHeight>52;Ut.includes("\n")||ft.length?e=!0:Ut.trim()||(e=!1),Dt(e)})()}),[Ut,ft]),d((()=>{const e=un.current,t=mn.current;if(!e||!t||At||Ut.includes("\n"))return void Rt(!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=Ut||Hn,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;Rt(i>l)}),[Ut,At,Hn]);const ys=e=>t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:ln.current))return!1;const t=ie(cn.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})},Mn&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),xs=e=>{dn.current=e,gn.current&&(gn.current.abort(),gn.current=null),an.current&&(an.current.cancel().catch((()=>{})),an.current=null)},js=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}))},Mn&&{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})),Is=()=>{const e=ln.current;e&&!Mt&&!vt&&Ut.trim()&&(Xt((t=>{var n,s;return[...t,{id:oe(),message:Ut,predecessorSubmissionId:null!==(s=null===(n=t[t.length-1])||void 0===n?void 0:n.id)&&void 0!==s?s:e}]})),Pt(""))},ws=(e,n=!1,s=!1,o)=>t(void 0,void 0,void 0,(function*(){var t,i,r,a,l,d;let c=null;try{if(ct&&!s||vt)return;const u=ft.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),m=u.map((e=>e.documentId)).filter(Boolean),p=u.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),g=null!=e?e:Ut,f=null!==(i=null===(t=null==Be?void 0:Be.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==i&&i&&m.length>0;if(!g&&!f)return;gt(""),xt(""),pt(null),Pt(""),Qe(!1),mt("fetching"),wt(),kt();const v=null!==(a=null===(r=Tt.data)||void 0===r?void 0:r.messages)&&void 0!==a?a:[],h=K(dt,v),b=n?h.slice(0,h.length-1):h,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:g,isVisible:!0}],documentIds:f?m:[]}],j];ut(I),kt(),f&&yt([]);const w=J(Me),O=null!=o?o:oe();c=O,ln.current=O,dn.current=null,cn.current=[];const k=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({origin:Ue,pickaxeId:Pe,sessionId:Ae,submissionId:O,senderType:Le,value:g},f&&{documentIds:m}),De&&{sender:De}),it&&{studioSessionToken:it}),!it&&!De&&{sender:q()}),Yn&&{portalId:Yn}),Me&&{deploymentId:Me}),w&&{metadata:w}),f&&p.length>0?{uploadedModelImages:p}:{})),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()})},Mn&&{credentials:"include"})),N=yield k.json();if(!N.success){if(N.limitData){const e=new Error(N.error||N.message||(null==Fe?void 0:Fe["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=N.limitData,e}if(Gn(N))return;throw new Error(N.error||N.message||(null==Fe?void 0:Fe["failed-to-start-generation"])||"Failed to start generation")}const C=null!==(l=N.submissionId)&&void 0!==l?l:O;c=C,ln.current=C;const E=()=>dn.current===C;if(E())return;Kn&&He&&Ae&&fn.current.add(Ae);const _=Object.assign(Object.assign({},es()),{message:g,documentIds:f?m:[],uploadedModelImages:f?p:[],hasUploadedDocuments:f,isHidden:n,metadata:null!=w?w:null});Yt?(ts(),Y(_)):vn.current=_,mt("streaming"),gn.current=new AbortController;const T=[];let U=[...null!=Nt?Nt:[]],P=0,A=!1,D="";for(;!A;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${C}?index=${P}`,{signal:null===(d=gn.current)||void 0===d?void 0:d.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();an.current=t;const n=new TextDecoder,s=S({onEvent:e=>{var t,n;if(E())A=!0;else if(e.event&&"ping"!==e.event&&P++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return pt(t.limitData),gt(""),void(A=!0);const n=t.error||t.message||(null==Fe?void 0:Fe["something-went-wrong"])||"Something went wrong.";return Gn(t)||gt(n),void(A=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("data-error"===s.type&&pe){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 A=!0,pe({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 A=!0,pe({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 A=!0,pe({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 A=!0,pe({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,T[T.length-1].content=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,T[T.length-1].content=D;else if("reasoning-end"===s.type)D="";else if(s.type.startsWith("data-")){const e=s;T.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}cn.current=ie(T);const o=ie(T);ut((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);U=U.filter((e=>!(e.id===t.id&&e.version===t.version))),U.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ct([...U]),St.startsWith("inline")||Et({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);U=U.filter((e=>!(e.id===t.id&&e.version===t.version))),U.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),Ct(U),St.startsWith("inline")||Et({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);U=U.filter((e=>!(e.id===t.id&&e.version===t.version))),U.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),Ct(U),St.startsWith("inline")||Et({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");U=U.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),Ct(U)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);Ct(U.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 pt(t.limitData),gt(""),void(A=!0);const n=t.error||t.message||(null==Fe?void 0:Fe["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Gn(t))return void(A=!0);gt(n)}else"stop"===e.event&&(A=!0)}else A=!0}});for(;;){if(E()){A=!0,t.cancel().catch((()=>{}));break}const{value:e,done:o}=yield t.read();if(E()){A=!0,t.cancel().catch((()=>{}));break}if(o)break;s.feed(n.decode(e))}A||E()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||re(e)||E())return void(A=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==ot||ot(Ae)}catch(e){if(re(e))return;if(e.limitData)pt(e.limitData),gt("");else{let t=X(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==Fe?void 0:Fe["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Gn(t)||gt(t)}}finally{const e=!c||ln.current===c;kt(),e&&(mt("idle"),Ot(),an.current=null),c&&e&&(ln.current=null,cn.current=[]),yield qn()}}));return d((()=>{if(ct||Mt||Kt||0===Bt.length)return;const e=Bt[0];Ft(!0),Gt(e.id),t(void 0,void 0,void 0,(function*(){try{if(!(yield js(e.predecessorSubmissionId)))return void gt((null==Fe?void 0:Fe["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");Xt((t=>t.filter((t=>t.id!==e.id)))),yield ws(e.message,!1,!0,e.id)}finally{Ft(!1),Gt(null)}}))}),[ct,Kt,Mt,Bt]),Vn?null:n("div",Object.assign({className:G("flex w-full flex-shrink-0 flex-col items-center",!Fn&&"px-4 pb-8"),dir:We?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[Bt.length>0&&n("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:Ke.text+"18",backgroundColor:null!==(_e=An.backgroundColor)&&void 0!==_e?_e:Ke.text+"08",color:Ke.text,borderTopLeftRadius:Math.max(Xe.cornerRadius-4,12),borderTopRightRadius:Math.max(Xe.cornerRadius-4,12)}},{children:Bt.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<Bt.length-1?{borderBottom:`1px solid ${Ke.text}12`}:void 0},{children:[n(T,{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})),Ht===e.id||Vt===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"}),Ht===e.id?(null==Fe?void 0:Fe.steering)||"Steering...":(null==Fe?void 0:Fe.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:Mt||!ct,onClick:()=>{(e=>{t(void 0,void 0,void 0,(function*(){const t=ln.current;if(!t||Mt)return;const n=Bt.findIndex((t=>t.id===e.id));if(-1===n)return;$t(!0),Wt(e.id),gt(""),xs(t);let s=!1;try{if(!(yield ys(t)))throw new Error((null==Fe?void 0:Fe["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield js(t)))throw new Error((null==Fe?void 0:Fe["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");mt("idle"),Xt((t=>t.filter((t=>t.id!==e.id)))),s=!0,$t(!1),Wt(null),yield ws(e.message,!1,!0,e.id)}catch(t){mt("idle"),s&&Xt((t=>{if(t.some((t=>t.id===e.id)))return t;const s=[...t];return s.splice(n,0,e),s})),gt(X(t))}finally{$t(!1),Wt(null)}}))})(e)},"aria-label":`${(null==Fe?void 0:Fe["steer-with"])||"Steer with"}: ${e.message}`},{children:[n("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==Fe?void 0:Fe.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:Mt,onClick:()=>{return t=e.id,void Xt((e=>ne(e,t)));var t},"aria-label":`${(null==Fe?void 0:Fe["remove-queued-message"])||"Remove queued message"}: ${e.message}`},{children:n(P,{className:"h-4 w-4","aria-hidden":"true"})})),s(M,Object.assign({id:`queued-message-menu-${e.id}`,className:"shrink-0"},{children:[n($,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:Mt,role:"button",tabIndex:Mt?-1:0,"aria-haspopup":"menu","aria-label":(null==Fe?void 0:Fe["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(B,Object.assign({role:"menu",align:We?"bottom-start":"bottom-end",positionStrategy:qe?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(r=An.backgroundColor)&&void 0!==r?r:Ke.primary,color:Ke.text,borderRadius:"12px"},border:`1px solid ${Ke.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=>{Xt((t=>ne(t,e.id))),Pt(e.message),requestAnimationFrame((()=>{const t=un.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(e)},{children:[n(A,{className:"h-4 w-4 shrink-0"}),(null==Fe?void 0:Fe["edit-message"])||"Edit message"]}))}))]}))]})]}),e.id)}))})),s("div",Object.assign({ref:pn,className:G("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Xe.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},An),{maxHeight:`${hn}px`,overflowY:"auto"})},{children:[ms&&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:An.backgroundColor?`${An.backgroundColor}E6`:void 0,borderColor:Ke.text+"20",color:Ke.text,borderTopRightRadius:Xe.cornerRadius+"px",borderTopLeftRadius:Xe.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:s("span",{children:[as.toLocaleString()," ",Qn?(null==Fe?void 0:Fe.credits)||"Credits":(null==Fe?void 0:Fe.uses)||"Uses"," ",(null==Fe?void 0:Fe.remaining)||"remaining"]})})),s("div",Object.assign({className:"flex items-center gap-3"},{children:[gs&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Ke.accent,color:Ke.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),fs)return void window.open(fs,"_blank","noopener,noreferrer");if(st)return void st();const t=H({baseUrl:zt,accessGroupId:null==ze?void 0:ze.accessGroupId});t&&W({deploymentId:Me,pricingUrl:t,studioId:null==Be?void 0:Be.studioid,studioSessionToken:it})}},{children:vs})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>tn(!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"})}))}))]}))]})),!ct&&ft.length>0&&n(D,{className:"p-4 pb-0",isDisabled:ct}),s("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Xn&&s("div",Object.assign({className:G("pointer-events-none absolute top-1/2 z-10 flex -translate-y-1/2 select-none items-center gap-x-2",We?"right-4":"left-4")},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(Te=Ke.accent)&&void 0!==Te?Te:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Ke.text+"90"}},{children:(null==Fe?void 0:Fe.listening)||"Listening..."}))]})),n(L,Object.assign({ref:un,className:G(Pn.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Ut.trim()&&!Ut.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",We?"text-right":"text-left",Wn&&"mb-12"),value:Ut,placeholder:Xn?"":Hn,onChange:e=>{Pt(e)},onKeyDown:e=>{Ge||It||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),vt||Mt||(ct?Is():ws())))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!$n)return;e.preventDefault(),Qe(!1),yield bt(t)}}))},ae&&{onFocus:ae},ue&&{onBlur:ue},{dir:We?"rtl":"ltr"})),n("div",Object.assign({ref:mn,className:G("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",Wn?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Wn&&An.backgroundColor&&{backgroundColor:An.backgroundColor}),{borderTopRightRadius:Xe.cornerRadius+"px",borderBottomRightRadius:Xe.cornerRadius+"px"})},{children:ct?s(o,{children:[n("button",Object.assign({"aria-label":(null==Fe?void 0:Fe["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=ln.current;e&&(xs(e),ys(e)),mt("idle")},style:{backgroundColor:Ke.accent+"10",color:Ke.accent}},{children:n(U,{className:"h-4 w-4 shrink-0"})})),n("button",Object.assign({"aria-label":(null==Fe?void 0:Fe["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:Mt||vt||!Ut.trim(),onClick:Is,style:{backgroundColor:Ut.trim()?Ke.accent:Ke.accent+"10",color:Ut.trim()?Ke.accentText:Ke.accent+"80"}},{children:n(E,{className:G("h-6 w-6 shrink-0",We&&"scale-x-[-1] transform")})}))]}):yn?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:wn,style:{backgroundColor:Ke.accent,color:Ke.accentText}},{children:n(U,{className:"h-4 w-4 shrink-0"})})):s(o,{children:[$n&&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:Cn?Ke.accent+"10":void 0,color:Cn?Ke.accent:Ke.accent+"80"},disabled:vt||ct,onClick:()=>{var e;return null===(e=on.current)||void 0===e?void 0:e.click()}},En,{children:[n("input",{id:"file-upload",ref:on,type:"file",accept:[...O,...k,...N].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){Qe(!1),yield bt(Array.from(e.target.files||[])),e.target.value=""}))}),n(C,{className:"h-6 w-6 shrink-0"})]})),Bn&&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:yn?Ke.accent:Tn?Ke.accent+"10":void 0,color:yn?Ke.accentText:Tn?Ke.accent:Ke.accent+"80"},disabled:vt||ct||xn,onClick:()=>{yn?wn():(rn.current=Ut,In(Ve||"en-US"))}},Un,{children:n(_,{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:kn||bs?Ke.accent:Ke.accent+"10",color:kn||bs?Ke.accentText:Ke.accent+"80"},disabled:!bs,onClick:()=>ws()},Nn,{children:n(E,{className:G("h-6 w-6 shrink-0",We&&"scale-x-[-1] transform")})}))]})}))]}))]})),ht&&n(R,{error:ht,className:"mt-3"})]}))}))}));ue.displayName="Input";export{ue 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{forwardRef as i,useState as r,useRef as a,useCallback as l,useEffect as d,useMemo as c,useImperativeHandle as u}from"react";import{usePickaxeContext as m}from"../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as p}from"../../../hooks/pickaxe/useResponseContext.js";import{useStyleInput as g}from"../../../hooks/studio/useStyleInput.js";import{useStyleFontSize as f}from"../../../hooks/studio/useStyleFontSize.js";import{useConversation as v}from"../../../hooks/pickaxe/useConversation.js";import{useDimensionContext as h}from"../../../hooks/pickaxe/useDimensionContext.js";import{useAuthContext as b}from"../Addons/Auth/hooks/useAuthContext.js";import{useDocument as y}from"../Addons/Document/hooks/useDocument.js";import{useScroll as x}from"../Addons/Scroll/hooks/useScroll.js";import{useArtifactContext as j}from"../Addons/Artifact/hooks/useArtifactContext.js";import{useHover as I}from"../../../hooks/core/useHover.js";import{useMediaQuery as w}from"../../../hooks/core/useMediaQuery.js";import{allowedFileMimeTypes as O,allowedImageMimeTypes as k,additionalAllowedFileExtensions as N}from"../../../common/documents.js";import{createParser as S}from"eventsource-parser";import C from"../../Icons/attach-vertical.svg.js";import E from"../../Icons/arrow-right.svg.js";import _ from"../../Icons/microphone.svg.js";import T from"../../Icons/message-clock.svg.js";import U from"../../Icons/stop.svg.js";import P from"../../Icons/trash.svg.js";import A from"../../Icons/pencil.svg.js";import D from"../Addons/Document/List.js";import L from"../../Core/Textarea.js";import R from"../../Core/ErrorAlert.js";import M from"../../Core/Menu/index.js";import $ from"../../Core/Menu/Button.js";import B from"../../Core/Menu/List.js";import X from"../../../common/error.js";import{pickaxeApi2 as K}from"../../../common/api/pickaxe.js";import{getValidationFailure as F}from"../../../common/validation.js";import V from"../../../common/cn.js";import{buildUpgradeUrl as G,openAuthenticatedPricingUrl as H,initializeEmbedUserId as W}from"../../../common/utils.js";import{getPickaxeConfigMetadata as q}from"../../../common/pickaxeConfig.js";import{readAgentPrefill as J}from"../../../common/agentPrefill.js";import{fireDeploymentSessionInitializedWebhook as z,fireDeploymentFirstMessageSubmittedWebhook as Q}from"../../../common/deploymentWebhooks.js";import{useStudio as Y}from"../../../hooks/studio/useStudio.js";import{useSpeechToText as Z}from"../../../hooks/pickaxe/useSpeechToText.js";import{STUDIO_INFINITY_VALUE as ee}from"../common/PickaxeCommon.js";const te=(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},ne=e=>"string"==typeof e&&e.trim().length>0,se=()=>"undefined"!=typeof crypto&&"randomUUID"in crypto?crypto.randomUUID():`submission-${Date.now()}-${Math.random().toString(36).slice(2)}`,oe=e=>e.map((e=>Object.assign({},e))),ie=e=>e instanceof Error&&("AbortError"===e.name||"BodyStreamBuffer was aborted"===e.message),re=(e,t)=>{if(e&&"object"==typeof e)return e[t]},ae=(e,t)=>{const n=re(e,t);return ne(n)?n:null},le=e=>{const t=Number(e);return Number.isFinite(t)?t:void 0},de=({studioUser:e,deploymentId:t,portalId:n})=>{var s,o;const i=Array.isArray(re(e,"uses"))?re(e,"uses"):[],r=(({deploymentId:e,portalId:t})=>ne(e)?{type:"deployment",id:e}:ne(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}},ce=i((({resubmitPrompt:i,onFocus:re,onBlur:ce,onInputHeightChange:ue,initSmitheryAuthData:me},pe)=>{var ge,fe,ve,he,be,ye,xe,je,Ie,we,Oe,ke,Ne,Se,Ce,Ee,_e;const{origin:Te,pickaxeId:Ue,sessionId:Pe,sender:Ae,senderType:De,portalId:Le,deploymentId:Re,deploymentType:Me,pickaxe:$e,styles:Be,colors:Xe,translations:Ke,locale:Fe,forceMobile:Ve,isNewChat:Ge,isRtl:He,isEmbed:We,isShowFeedbackMessage:qe,accessGroup:Je,setIsNewChat:ze,setIsShowIceBreaker:Qe,setValidationStatus:Ye,setValidationUpgradeGroups:Ze,setValidationUpgradeUrl:et,setAccessGroup:tt,onUpgrade:nt,onGenerateComplete:st}=m(),{token:ot,isLoggedOut:it,isSent:rt,isPricingAuth:at}=b(),{messages:lt,isGenerating:dt,setMessages:ct,setStatus:ut,setLimitData:mt,setError:pt}=p(),{documents:gt,isUploading:ft,documentError:vt,onFileUpload:ht,setDocuments:bt,setDocumentError:yt}=y(),{studio:xt}=Y(),[jt]=w("(max-width: 480px)"),{scrollStartSession:It,scrollEndSession:wt,scrollToBottom:Ot}=x({auto:!0,smooth:!(Ve||jt)}),{artifacts:kt,currentPopupType:Nt,setArtifacts:St,setCurrentArtifact:Ct}=j(),{height:Et}=h(),_t=v(),[Tt,Ut]=r((()=>J([Re,Ue]).chatInput)),[Pt,At]=r(!1),[Dt,Lt]=r(!1),[Rt,Mt]=r(!1),[$t,Bt]=r([]),[Xt,Kt]=r(!1),[Ft,Vt]=r(null),[Gt,Ht]=r(null),[Wt,qt]=r(null),[Jt,zt]=r(null),[Qt,Yt]=r(!1),[Zt,en]=r(!1),[tn,nn]=r(0),sn=a(null),on=a(""),rn=a(null),an=a(null),ln=a(null),dn=a([]),cn=a(null),un=a(null),mn=a(null),pn=a(null),gn=a(new Set),fn=a(null),vn=Math.max(.4*Et,100),{speechTranscript:hn,isSpeechListening:bn,isSpeechProcessing:yn,isSpeechSupported:xn,onStartListening:jn,onStopListening:In}=Z(),wn=I(),{isHover:On}=wn,kn=e(wn,["isHover"]),Nn=I(),{isHover:Sn}=Nn,Cn=e(Nn,["isHover"]),En=I(),{isHover:_n}=En,Tn=e(En,["isHover"]),Un=f(),Pn=g(),An="undefined"!=typeof window?window.location.hostname:"",Dn="undefined"!=typeof window?window.location.href:"",Ln="undefined"!=typeof window&&window.self!==window.top,Rn=An.includes("pickaxe.co")&&!Dn.includes("https://studio.pickaxe.co/_embed")&&!Ln,Mn=null!==(fe=null===(ge=null==$e?void 0:$e.documentuploadtype)||void 0===ge?void 0:ge.startsWith("enduserupload"))&&void 0!==fe&&fe,$n=xn&&(null==$e?void 0:$e.enablevoicetotext),Bn=bn&&!Tt.trim(),Xn=ne(Re),Kn="chat-input"===Me&&Ge&&!rt,Fn="chat-input"===Me&&at&&it&&rt,Vn=l((e=>{const t=F(e);return!!t&&(pt(""),mt(null),Ye(t.status),tt(t.accessGroup),Ze(t.upgradeGroups),et(t.upgradeUrl),!0)}),[pt,mt,Ye,Ze,et,tt]),Gn=null!==(ve=null==$e?void 0:$e.placeholdertext)&&void 0!==ve?ve:He?"بماذا تريد أن تتحدث؟":(null==Ke?void 0:Ke["what-do-you-want-to-talk-about"])||"What do you want to talk about?",Hn=Pt||Dt,Wn=l((()=>t(void 0,void 0,void 0,(function*(){Yt(!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==$e?void 0:$e.studioid},ot?{studioSessionToken:ot}:Ae?{sender:Ae}:{sender:W()}))},(!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}})),Rn&&{credentials:"include"})),t=yield e.json();(null==t?void 0:t.studioUser)&&(qt(t.studioUser),zt(t.url))}catch(e){console.error("Failed to fetch studio user:",e)}finally{Yt(!0)}}))),[Rn,null==$e?void 0:$e.studioid,Ae,ot]);d((()=>{Wn()}),[Wn]);const qn=Number(null!==(he=null==Je?void 0:Je.limit)&&void 0!==he?he:0),Jn="string"==typeof(null==Je?void 0:Je.limitInterval)?Je.limitInterval:null,zn=!!(null==xt?void 0:xt.data.usage)&&xt.data.usage.isCredits,Qn=c((()=>{var e,t,n,s,o;return null!==(o=null!==(s=null!==(n=null!==(t=null!==(e=null!=Le?Le:ae(Wt,"portalId"))&&void 0!==e?e:ae(Wt,"portalid"))&&void 0!==t?t:ae(Je,"portalId"))&&void 0!==n?n:ae(Je,"portalid"))&&void 0!==s?s:ae($e,"portalId"))&&void 0!==o?o:ae($e,"portalid")}),[Je,Le,$e,Wt]),Yn=c((()=>de({studioUser:Wt,deploymentId:Re,portalId:Qn})),[Re,Qn,Wt]);d((()=>{Xn&&Ge&&Pe&&gn.current.add(Pe)}),[Ge,Pe,Xn]);const Zn=l((()=>{var e,t,n;return{studioId:null==$e?void 0:$e.studioid,userEmail:ae(Wt,"email"),userId:null!==(e=ae(Wt,"userId"))&&void 0!==e?e:ae(Wt,"userid"),sessionId:Pe,deploymentId:Re,deploymentType:Me,portalId:Qn,accessGroupId:null!==(t=null==Je?void 0:Je.accessGroupId)&&void 0!==t?t:null,pickaxeId:Ue,sender:Ae,senderType:De,origin:Te,metadata:null!==(n=q(Re))&&void 0!==n?n:null}}),[null==Je?void 0:Je.accessGroupId,Re,Me,Te,null==$e?void 0:$e.studioid,Ue,Qn,Ae,De,Pe,Wt]),es=l((()=>!!(Xn&&Qt&&Pe)&&(!!gn.current.has(Pe)&&(z(Zn()),gn.current.delete(Pe),!0))),[Zn,Qt,Pe,Xn]);d((()=>{if(!Qt||!Pe)return;es();const e=fn.current;(null==e?void 0:e.sessionId)===Pe&&(Q(Object.assign(Object.assign(Object.assign({},e),Zn()),{message:e.message,documentIds:e.documentIds,uploadedModelImages:e.uploadedModelImages,hasUploadedDocuments:e.hasUploadedDocuments,isHidden:e.isHidden})),fn.current=null)}),[es,Zn,Qt,Pe]);const ts={currentUses:le(null==Wt?void 0:Wt.currentUses),extraUses:le(null==Wt?void 0:Wt.extraUses)},ns=Yn.scope?{currentUses:null!==(ye=le(null===(be=Yn.record)||void 0===be?void 0:be.currentUses))&&void 0!==ye?ye:0,extraUses:null!==(je=le(null===(xe=Yn.record)||void 0===xe?void 0:xe.extraUses))&&void 0!==je?je:0}:{currentUses:0,extraUses:0},ss=ae(Wt,"type"),os="guest"===ss||!ss&&it?ns:ts;d((()=>{let e=!0;return t(void 0,void 0,void 0,(function*(){var t;if(zn&&(null===(t=null==xt?void 0:xt.data)||void 0===t?void 0:t.workspaceId))try{const t=yield K.get(`/cost_per_run?workspaceId=${xt.data.workspaceId}`,{withCredentials:!1});e&&nn(1e4*(Number(t.data.costPerRun)||0))}catch(t){console.error("Failed to fetch average cost per run:",t),e&&nn(0)}else e&&nn(0)})),()=>{e=!1}}),[zn,null===(Ie=null==xt?void 0:xt.data)||void 0===Ie?void 0:Ie.workspaceId]);const is=(({currentUses:e,extraUses:t,limit:n,limitInterval:s})=>{const o=Number(null!=e?e:0),i=Number(null!=t?t:0);return n===ee||i===ee?ee:"one_time"===s?Math.max(0,i-o):Math.max(0,n-o)+i})({currentUses:os.currentUses,extraUses:os.extraUses,limit:qn,limitInterval:Jn}),rs=is===ee?ee:Math.max(0,Math.ceil(is)),as=(({extraUses:e,limit:t,limitInterval:n})=>{const s=Number(null!=e?e:0);return t===ee||s===ee?ee:"one_time"===n?Math.max(0,s):Math.max(0,t)+Math.max(0,s)})({extraUses:os.extraUses,limit:qn,limitInterval:Jn}),ls=as===ee?ee:Math.ceil(.05*as),ds=zn?Math.ceil(5*tn):5,cs=ls===ee?ee:Math.max(ls,ds),us=c((()=>!!Wt&&(!Zt&&(rs!==ee&&rs<=cs))),[Zt,cs,rs,Wt]),ms=Boolean(null==Je?void 0:Je.hideUpgradeOptions),ps=Boolean(!ms&&((null===(we=null==Je?void 0:Je.upgrade)||void 0===we?void 0:we.isBuyMoreUses)||(null===(Oe=null==Je?void 0:Je.upgrade)||void 0===Oe?void 0:Oe.isLinkToCustomURL)||(null===(ke=null==Je?void 0:Je.upgrade)||void 0===ke?void 0:ke.isUpgradeToAnotherGroup)&&(null===(Ne=Je.upgrade.accessGroupIds)||void 0===Ne?void 0:Ne.length))),gs=!ms&&(null===(Se=null==Je?void 0:Je.upgrade)||void 0===Se?void 0:Se.isLinkToCustomURL)&&"string"==typeof Je.upgrade.limitLink&&Je.upgrade.limitLink.trim().length>0?Je.upgrade.limitLink.trim():null,fs=gs&&"string"==typeof(null===(Ce=null==Je?void 0:Je.upgrade)||void 0===Ce?void 0:Ce.limitCTA)&&Je.upgrade.limitCTA.trim().length>0?Je.upgrade.limitCTA:(null==Ke?void 0:Ke["pricing.upgrade"])||(null==Ke?void 0:Ke.upgrade)||"Upgrade",vs=c((()=>{var e,t,n;return!!Ge&&(!!$e&&(!_t.isLoading&&(!((null!==(t=null===(e=_t.data)||void 0===e?void 0:e.messages.length)&&void 0!==t?t:0)>1)&&(!!(null===(n=$e.icebreakers)||void 0===n?void 0:n.length)&&(!qe&&!Kn)))))}),[$e,Ge,qe,Kn,_t.data,_t.isLoading]),hs=c((()=>{if(ft||Rt)return!1;const e=Mn&>.length>0&>.every((e=>"finished"===e.status));return!(!Tt.trim()&&!e)&>.every((e=>"finished"===e.status||e.isInsertedAsRaw))}),[Mn,ft,Rt,Tt,gt]);u(pe,(()=>({onSubmit:Is}))),d((()=>{Qe(vs)}),[vs]),d((()=>{var e;if(i){const t=Array.from(lt),n=null===(e=t[t.length-2].parts.find((e=>"text"===e.type)))||void 0===e?void 0:e.content;Is(n,!0)}}),[i]),d((()=>{if(!mn.current||!ue)return;const e=new ResizeObserver((e=>{for(const t of e)ue(t.contentRect.height)}));return e.observe(mn.current),()=>{e.disconnect()}}),[ue]),d((()=>{if(!bn)return;const e=on.current?`${on.current} `:"";Ut(`${e}${hn}`)}),[hn,bn]),d((()=>{if(!cn.current)return;(()=>{if(!cn.current)return;let e=cn.current.scrollHeight>52;Tt.includes("\n")||gt.length?e=!0:Tt.trim()||(e=!1),At(e)})()}),[Tt,gt]),d((()=>{const e=cn.current,t=un.current;if(!e||!t||Pt||Tt.includes("\n"))return void Lt(!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=Tt||Gn,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;Lt(i>l)}),[Tt,Pt,Gn]);const bs=e=>t(void 0,void 0,void 0,(function*(){if(!(e=null!=e?e:an.current))return!1;const t=oe(dn.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})},Rn&&{credentials:"include"}))).ok}catch(e){return console.warn("Failed to cancel submission",e),!1}})),ys=e=>{ln.current=e,pn.current&&(pn.current.abort(),pn.current=null),rn.current&&(rn.current.cancel().catch((()=>{})),rn.current=null)},xs=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}))},Rn&&{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})),js=()=>{const e=an.current;e&&!Rt&&!ft&&Tt.trim()&&(Bt((t=>{var n,s;return[...t,{id:se(),message:Tt,predecessorSubmissionId:null!==(s=null===(n=t[t.length-1])||void 0===n?void 0:n.id)&&void 0!==s?s:e}]})),Ut(""))},Is=(e,n=!1,s=!1,o)=>t(void 0,void 0,void 0,(function*(){var t,i,r,a;let l=null;try{if(dt&&!s||ft)return;const d=gt.filter((e=>"finished"===e.status&&!e.isInsertedAsRaw)),c=d.map((e=>e.documentId)).filter(Boolean),u=d.filter((e=>"image"===e.type)).map((e=>{const t=e.name.split(".").pop()||"";return{documentId:e.documentId,extension:t}})),m=null!=e?e:Tt,p=null!==(i=null===(t=null==$e?void 0:$e.documentuploadtype)||void 0===t?void 0:t.startsWith("enduserupload"))&&void 0!==i&&i&&c.length>0;if(!m&&!p)return;pt(""),yt(""),mt(null),Ut(""),ze(!1),ut("fetching"),It(),Ot();const g=n?lt.slice(0,lt.length-1):lt,f=(e=>e.reduce(((e,t)=>Math.max(e,t.id)),0)+1)(g),v=f+(n?0:1),h={id:v,role:"assistant",parts:[],documentIds:[]},b=[...g,...n?[]:[{id:f,role:"user",parts:[{type:"text",content:m,isVisible:!0}],documentIds:p?c:[]}],h];ct(b),Ot(),p&&bt([]);const y=q(Re),x=null!=o?o:se();l=x,an.current=x,ln.current=null,dn.current=[];const j=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({origin:Te,pickaxeId:Ue,sessionId:Pe,submissionId:x,senderType:De,value:m},p&&{documentIds:c}),Ae&&{sender:Ae}),ot&&{studioSessionToken:ot}),!ot&&!Ae&&{sender:W()}),Qn&&{portalId:Qn}),Re&&{deploymentId:Re}),y&&{metadata:y}),p&&u.length>0?{uploadedModelImages:u}:{})),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()})},Rn&&{credentials:"include"})),I=yield j.json();if(!I.success){if(I.limitData){const e=new Error(I.error||I.message||(null==Ke?void 0:Ke["failed-to-start-generation"])||"Failed to start generation");throw e.limitData=I.limitData,e}if(Vn(I))return;throw new Error(I.error||I.message||(null==Ke?void 0:Ke["failed-to-start-generation"])||"Failed to start generation")}const w=null!==(r=I.submissionId)&&void 0!==r?r:x;l=w,an.current=w;const O=()=>ln.current===w;if(O())return;Xn&&Ge&&Pe&&gn.current.add(Pe);const k=Object.assign(Object.assign({},Zn()),{message:m,documentIds:p?c:[],uploadedModelImages:p?u:[],hasUploadedDocuments:p,isHidden:n,metadata:null!=y?y:null});Qt?(es(),Q(k)):fn.current=k,ut("streaming"),pn.current=new AbortController;const N=[];let C=[...null!=kt?kt:[]],E=0,_=!1,T="";for(;!_;)try{const e=yield fetch(`${process.env.NEXT_PUBLIC_PICKAXE_API2_URL}/response/stream/${w}?index=${E}`,{signal:null===(a=pn.current)||void 0===a?void 0:a.signal,headers:{"Cache-Control":"no-cache",Connection:"keep-alive"}});if(!e.body)throw new Error("No response body");const t=e.body.getReader();rn.current=t;const n=new TextDecoder,s=S({onEvent:e=>{var t,n;if(O())_=!0;else if(e.event&&"ping"!==e.event&&E++,"stop"!==e.event){if("error"===e.event){const t=JSON.parse(e.data);if(t.limitData)return mt(t.limitData),pt(""),void(_=!0);const n=t.error||t.message||(null==Ke?void 0:Ke["something-went-wrong"])||"Something went wrong.";return Vn(t)||pt(n),void(_=!0)}if("delta"===e.event){const s=JSON.parse(e.data);if("data-error"===s.type&&me){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 _=!0,me({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 _=!0,me({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 _=!0,me({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 _=!0,me({provider:"composio",toolkitSlug:t.toolkitSlug,serverId:t.serverId,name:t.name}),new Error("STOP_STREAM")}}else if("text-start"===s.type)T="",N.push({type:"text",content:"",isVisible:null===(t=s.isVisible)||void 0===t||t});else if("text-delta"===s.type)T+=s.delta,N[N.length-1].content=T;else if("text-end"===s.type)T="";else if("reasoning-start"===s.type)T="",N.push({type:"reasoning",content:"",isVisible:null===(n=s.isVisible)||void 0===n||n});else if("reasoning-delta"===s.type)T+=s.delta,N[N.length-1].content=T;else if("reasoning-end"===s.type)T="";else if(s.type.startsWith("data-")){const e=s;N.push({type:e.type,content:JSON.stringify(e.data),isVisible:!0})}dn.current=oe(N);const o=oe(N);ct((e=>{const t=e.findIndex((e=>e.id===v)),n=Object.assign(Object.assign({},h),{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);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),St([...C]),Nt.startsWith("inline")||Ct({id:t.id,version:t.version})}else if("artifact_updated"===e.event){const t=JSON.parse(e.data);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"updating"})),St(C),Nt.startsWith("inline")||Ct({id:t.id,version:t.version})}else if("artifact_rewrite"===e.event){const t=JSON.parse(e.data);C=C.filter((e=>!(e.id===t.id&&e.version===t.version))),C.push(Object.assign(Object.assign({},t),{content:"",status:"streaming"})),St(C),Nt.startsWith("inline")||Ct({id:t.id,version:t.version})}else if("artifact_content"===e.event){const t=JSON.parse(e.data),n=t.token.replace(/\u200B/g,"");C=C.map((e=>e.id===t.id&&e.version===t.version?Object.assign(Object.assign({},e),{content:e.content+n,status:"streaming"}):e)),St(C)}else if("artifact_finished"===e.event){const t=JSON.parse(e.data);St(C.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 mt(t.limitData),pt(""),void(_=!0);const n=t.error||t.message||(null==Ke?void 0:Ke["something-went-wrong-try-again"])||"Something went wrong, please try again.";if(Vn(t))return void(_=!0);pt(n)}else"stop"===e.event&&(_=!0)}else _=!0}});for(;;){if(O()){_=!0,t.cancel().catch((()=>{}));break}const{value:e,done:o}=yield t.read();if(O()){_=!0,t.cancel().catch((()=>{}));break}if(o)break;s.feed(n.decode(e))}_||O()||(yield new Promise((e=>setTimeout(e,1e3))))}catch(e){if("STOP_STREAM"===e.message||ie(e)||O())return void(_=!0);console.warn("Stream connection lost, retrying...",e),yield new Promise((e=>setTimeout(e,1e3)))}null==st||st(Pe)}catch(e){if(ie(e))return;if(e.limitData)mt(e.limitData),pt("");else{let t=X(e)||"";t&&!t.includes("Unexpected token 'A',")||(t=(null==Ke?void 0:Ke["high-traffic-try-again-later"])||"Oops! We're experiencing high traffic at the moment. Please try again later."),Vn(t)||pt(t)}}finally{const e=!l||an.current===l;Ot(),e&&(ut("idle"),wt(),rn.current=null),l&&e&&(an.current=null,dn.current=[]),yield Wn()}}));return d((()=>{if(dt||Rt||Xt||0===$t.length)return;const e=$t[0];Kt(!0),Vt(e.id),t(void 0,void 0,void 0,(function*(){try{if(!(yield xs(e.predecessorSubmissionId)))return void pt((null==Ke?void 0:Ke["queued-message-waiting"])||"A queued message is waiting for the previous response to finish.");Bt((t=>t.filter((t=>t.id!==e.id)))),yield Is(e.message,!1,!0,e.id)}finally{Kt(!1),Vt(null)}}))}),[dt,Xt,Rt,$t]),Fn?null:n("div",Object.assign({className:V("flex w-full flex-shrink-0 flex-col items-center",!Kn&&"px-4 pb-8"),dir:He?"rtl":"ltr"},{children:s("div",Object.assign({className:"flex w-full max-w-[800px] flex-col"},{children:[$t.length>0&&n("div",Object.assign({className:"mx-3 -mb-3 overflow-hidden border pb-3",style:{borderColor:Xe.text+"18",backgroundColor:null!==(Ee=Pn.backgroundColor)&&void 0!==Ee?Ee:Xe.text+"08",color:Xe.text,borderTopLeftRadius:Math.max(Be.cornerRadius-4,12),borderTopRightRadius:Math.max(Be.cornerRadius-4,12)}},{children:$t.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<$t.length-1?{borderBottom:`1px solid ${Xe.text}12`}:void 0},{children:[n(T,{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})),Gt===e.id||Ft===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"}),Gt===e.id?(null==Ke?void 0:Ke.steering)||"Steering...":(null==Ke?void 0:Ke.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:Rt||!dt,onClick:()=>{(e=>{t(void 0,void 0,void 0,(function*(){const t=an.current;if(!t||Rt)return;const n=$t.findIndex((t=>t.id===e.id));if(-1===n)return;Mt(!0),Ht(e.id),pt(""),ys(t);let s=!1;try{if(!(yield bs(t)))throw new Error((null==Ke?void 0:Ke["failed-to-interrupt-current-response"])||"Failed to interrupt the current response.");if(!(yield xs(t)))throw new Error((null==Ke?void 0:Ke["current-response-still-stopping"])||"The current response is still stopping. Please send your message again in a moment.");ut("idle"),Bt((t=>t.filter((t=>t.id!==e.id)))),s=!0,Mt(!1),Ht(null),yield Is(e.message,!1,!0,e.id)}catch(t){ut("idle"),s&&Bt((t=>{if(t.some((t=>t.id===e.id)))return t;const s=[...t];return s.splice(n,0,e),s})),pt(X(t))}finally{Mt(!1),Ht(null)}}))})(e)},"aria-label":`${(null==Ke?void 0:Ke["steer-with"])||"Steer with"}: ${e.message}`},{children:[n("span",Object.assign({"aria-hidden":"true"},{children:"↳ "})),(null==Ke?void 0:Ke.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:Rt,onClick:()=>{return t=e.id,void Bt((e=>te(e,t)));var t},"aria-label":`${(null==Ke?void 0:Ke["remove-queued-message"])||"Remove queued message"}: ${e.message}`},{children:n(P,{className:"h-4 w-4","aria-hidden":"true"})})),s(M,Object.assign({id:`queued-message-menu-${e.id}`,className:"shrink-0"},{children:[n($,Object.assign({className:"flex h-7 w-7 items-center justify-center rounded-md opacity-50 transition-opacity hover:opacity-100",isDisabled:Rt,role:"button",tabIndex:Rt?-1:0,"aria-haspopup":"menu","aria-label":(null==Ke?void 0:Ke["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(B,Object.assign({role:"menu",align:He?"bottom-start":"bottom-end",positionStrategy:We?"absolute":"fixed",width:"auto",className:"p-1 text-sm shadow-xl",style:{backgroundColor:null!==(r=Pn.backgroundColor)&&void 0!==r?r:Xe.primary,color:Xe.text,borderRadius:"12px"},border:`1px solid ${Xe.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=>{Bt((t=>te(t,e.id))),Ut(e.message),requestAnimationFrame((()=>{const t=cn.current;t&&(t.focus(),t.setSelectionRange(e.message.length,e.message.length))}))})(e)},{children:[n(A,{className:"h-4 w-4 shrink-0"}),(null==Ke?void 0:Ke["edit-message"])||"Edit message"]}))}))]}))]})]}),e.id)}))})),s("div",Object.assign({ref:mn,className:V("relative z-10 flex flex-col w-full justify-end gap-y-3 py-[3px]","block"===Be.formFieldStyle&&"shadow"),style:Object.assign(Object.assign({},Pn),{maxHeight:`${vn}px`,overflowY:"auto"})},{children:[us&&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:Pn.backgroundColor?`${Pn.backgroundColor}E6`:void 0,borderColor:Xe.text+"20",color:Xe.text,borderTopRightRadius:Be.cornerRadius+"px",borderTopLeftRadius:Be.cornerRadius+"px"}},{children:[n("div",Object.assign({className:"flex items-center gap-2 text-sm font-medium"},{children:s("span",{children:[rs.toLocaleString()," ",zn?(null==Ke?void 0:Ke.credits)||"Credits":(null==Ke?void 0:Ke.uses)||"Uses"," ",(null==Ke?void 0:Ke.remaining)||"remaining"]})})),s("div",Object.assign({className:"flex items-center gap-3"},{children:[ps&&n("button",Object.assign({className:"rounded-md px-3 py-1.5 text-xs font-semibold transition-opacity hover:opacity-90",style:{backgroundColor:Xe.accent,color:Xe.accentText},onClick:e=>{if(e.preventDefault(),e.stopPropagation(),gs)return void window.open(gs,"_blank","noopener,noreferrer");if(nt)return void nt();const t=G({baseUrl:Jt,accessGroupId:null==Je?void 0:Je.accessGroupId});t&&H({deploymentId:Re,pricingUrl:t,studioId:null==$e?void 0:$e.studioid,studioSessionToken:ot})}},{children:fs})),n("button",Object.assign({className:"flex h-6 w-6 items-center justify-center rounded-full opacity-60 transition-opacity hover:opacity-100",onClick:()=>en(!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"})}))}))]}))]})),!dt&>.length>0&&n(D,{className:"p-4 pb-0",isDisabled:dt}),s("div",Object.assign({className:"relative flex w-full flex-col"},{children:[Bn&&s("div",Object.assign({className:V("pointer-events-none absolute top-1/2 z-10 flex -translate-y-1/2 select-none items-center gap-x-2",He?"right-4":"left-4")},{children:[n("span",{className:"h-2 w-2 animate-pulse rounded-full bg-c-secondary",style:{backgroundColor:null!==(_e=Xe.accent)&&void 0!==_e?_e:"#ff0000"}}),n("span",Object.assign({className:"text-sm text-c-secondary font-semilight",style:{color:Xe.text+"90"}},{children:(null==Ke?void 0:Ke.listening)||"Listening..."}))]})),n(L,Object.assign({ref:cn,className:V(Un.i1,"py-3.5 max-h-60 px-4 w-full border-transparent bg-transparent",!Tt.trim()&&!Tt.includes("\n")&&"overflow-hidden text-ellipsis whitespace-nowrap placeholder:whitespace-normal placeholder:overflow-visible",He?"text-right":"text-left",Hn&&"mb-12"),value:Tt,placeholder:Bn?"":Gn,onChange:e=>{Ut(e)},onKeyDown:e=>{Ve||jt||"Enter"===e.key&&(e.shiftKey||(e.preventDefault(),ft||Rt||(dt?js():Is())))},onPaste:e=>t(void 0,void 0,void 0,(function*(){const t=Array.from(e.clipboardData.files||[]);if(t.length>0){if(!Mn)return;e.preventDefault(),ze(!1),yield ht(t)}}))},re&&{onFocus:re},ce&&{onBlur:ce},{dir:He?"rtl":"ltr"})),n("div",Object.assign({ref:un,className:V("flex items-center gap-2 absolute z-2 transition-all duration-200 ease-in-out",Hn?"bottom-3 right-2":"right-0 top-1/2 -translate-y-1/2"),style:Object.assign(Object.assign({},!Hn&&Pn.backgroundColor&&{backgroundColor:Pn.backgroundColor}),{borderTopRightRadius:Be.cornerRadius+"px",borderBottomRightRadius:Be.cornerRadius+"px"})},{children:dt?s(o,{children:[n("button",Object.assign({"aria-label":(null==Ke?void 0:Ke["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=an.current;e&&(ys(e),bs(e)),ut("idle")},style:{backgroundColor:Xe.accent+"10",color:Xe.accent}},{children:n(U,{className:"h-4 w-4 shrink-0"})})),n("button",Object.assign({"aria-label":(null==Ke?void 0:Ke["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:Rt||ft||!Tt.trim(),onClick:js,style:{backgroundColor:Tt.trim()?Xe.accent:Xe.accent+"10",color:Tt.trim()?Xe.accentText:Xe.accent+"80"}},{children:n(E,{className:V("h-6 w-6 shrink-0",He&&"scale-x-[-1] transform")})}))]}):bn?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:In,style:{backgroundColor:Xe.accent,color:Xe.accentText}},{children:n(U,{className:"h-4 w-4 shrink-0"})})):s(o,{children:[Mn&&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:Sn?Xe.accent+"10":void 0,color:Sn?Xe.accent:Xe.accent+"80"},disabled:ft||dt,onClick:()=>{var e;return null===(e=sn.current)||void 0===e?void 0:e.click()}},Cn,{children:[n("input",{id:"file-upload",ref:sn,type:"file",accept:[...O,...k,...N].join(", "),multiple:!0,hidden:!0,className:"hidden",onChange:e=>t(void 0,void 0,void 0,(function*(){ze(!1),yield ht(Array.from(e.target.files||[])),e.target.value=""}))}),n(C,{className:"h-6 w-6 shrink-0"})]})),$n&&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:bn?Xe.accent:_n?Xe.accent+"10":void 0,color:bn?Xe.accentText:_n?Xe.accent:Xe.accent+"80"},disabled:ft||dt||yn,onClick:()=>{bn?In():(on.current=Tt,jn(Fe||"en-US"))}},Tn,{children:n(_,{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:On||hs?Xe.accent:Xe.accent+"10",color:On||hs?Xe.accentText:Xe.accent+"80"},disabled:!hs,onClick:()=>Is()},kn,{children:n(E,{className:V("h-6 w-6 shrink-0",He&&"scale-x-[-1] transform")})}))]})}))]}))]})),vt&&n(R,{error:vt,className:"mt-3"})]}))}))}));ce.displayName="Input";export{ce as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsxs as e,jsx as s}from"react/jsx-runtime";import{useMemo as o}from"react";import{usePickaxeContext as
|
|
1
|
+
import{jsxs as e,jsx as s}from"react/jsx-runtime";import{useMemo as o}from"react";import{usePickaxeContext as i}from"../../../../hooks/pickaxe/usePickaxeContext.js";import{useResponseContext as t}from"../../../../hooks/pickaxe/useResponseContext.js";import{useStyleFontSize as n}from"../../../../hooks/studio/useStyleFontSize.js";import{useScrollContext as l}from"../../Addons/Scroll/hooks/useScrollContext.js";import{useDocument as a}from"../../Addons/Document/hooks/useDocument.js";import{useArtifact as r}from"../../Addons/Artifact/hooks/useArtifact.js";import{PickaxeMarkdown as c}from"../../common/PickaxeMarkdown/index.js";import d from"../../common/PickaxeIcon.js";import m from"../../Addons/Scroll/ScrollLockView.js";import p from"../../common/PickaxeMessageParts/index.js";import u from"../../common/PickaxeMessageActions.js";import h from"../../../../common/cn.js";import{formatLocalDateTime as f}from"../../../../common/date.js";const x=()=>{var x,b,g,v,j,y;const{pickaxe:k,styles:w,colors:N,misc:C,translations:O,disableHtml:I,disableJs:A,disableCss:S,isRtl:D,setSessionId:P,setIsNewChat:M}=i(),{response:$,isGenerating:R}=t(),{scrollTargetRef:T}=l(),{setDocuments:q}=a(),{onLoadArtifact:H}=r(),F=n(),L=f(null!==(x=null==$?void 0:$.sentAt)&&void 0!==x?x:new Date,"hh:mm a MMM dd, yy"),J=o((()=>{var e,s;if(!$)return"";const o=(null==O?void 0:O["not-available"])||"n/a";return(null!==(s=null===(e=$.question)||void 0===e?void 0:e.inputs)&&void 0!==s?s:[]).map((e=>`<div style="display: flex; flex-direction: column; margin-bottom: 1em;">\n <p style="font-weight: 500;">${e.question}</p>\n <p>${e.answer||o}</p>\n</div>`)).join("")}),[$,O]);return $?e("div",Object.assign({ref:T,className:"flex flex-col shadow-black transition duration-300 hover:shadow"},{children:[s("div",Object.assign({className:"flex gap-x-3 overflow-hidden px-4 py-5",style:{backgroundColor:N.primary,color:N.text}},{children:e("div",Object.assign({className:"flex flex-col gap-y-1 overflow-x-auto pb-[6px] scrollbar scrollbar-thin"},{children:[s("input",{id:`${$.sessionId}-input`,type:"checkbox",className:"peer hidden",defaultChecked:J.length<280}),s("div",{className:"danger-html hidden flex-col opacity-50 peer-checked:flex",dangerouslySetInnerHTML:{__html:J}}),s("label",Object.assign({htmlFor:`${$.sessionId}-input`,className:h(F.b3,"mt-1 flex shrink-0 whitespace-nowrap font-semibold text-[#228DD7] peer-checked:hidden hover:cursor-pointer"),style:{color:N.accent}},{children:(null==O?void 0:O["see-input"])||"See input"})),s("label",Object.assign({htmlFor:`${$.sessionId}-input`,className:h(F.b3,"hidden shrink-0 whitespace-nowrap font-semibold text-[#228DD7] peer-checked:flex hover:cursor-pointer"),style:{color:N.accent}},{children:(null==O?void 0:O["hide-input"])||"Hide input"}))]}))})),e("div",Object.assign({className:"flex gap-x-3 px-4 py-5",style:{backgroundColor:N.secondary,color:N.secondaryText}},{children:[C.isChatImage&&s(d,{src:null==k?void 0:k.chaticon,alt:`${null==k?void 0:k.formtitle}'s Chat Icon`,width:24,height:24,className:"h-6 w-6 pt-1",textColor:N.secondaryText}),e("div",Object.assign({className:"flex w-full flex-col gap-y-2"},{children:[s(c,Object.assign({theme:w.theme,colors:N,isStreaming:R},D&&{rtl:!0},I&&{disableHtml:!0},A&&{disableJs:!0},S&&{disableCss:!0},{disableReasoning:null!==(b=null==k?void 0:k.enablereasoningdisplay)&&void 0!==b&&b,onArtifactClick:H},{children:s(p,{className:"overflow-x-auto pb-2 font-semilight scrollbar scrollbar-thin",parts:null!==(v=null===(g=$.question)||void 0===g?void 0:g.responseParts)&&void 0!==v?v:[],isStreaming:R})})),s("div",Object.assign({className:"flex flex-col"},{children:R?s("div",Object.assign({className:"flex items-center gap-x-2 rounded"},{children:Array.from({length:3}).map(((e,o)=>s("div",{className:h("h-1.5 w-1.5 animate-dot rounded-full",1===o&&"animate-dot-down"),style:{backgroundColor:N.secondaryText}},o)))})):e("div",Object.assign({className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-1"},{children:[s("div",Object.assign({className:"flex items-center gap-3"},{children:s(u,{content:(null!==(y=null===(j=$.question)||void 0===j?void 0:j.responseParts)&&void 0!==y?y:[]).filter((e=>e.isVisible&&"text"===e.type)).map((e=>e.content)).join("\n"),sessionId:$.sessionId,messagesCount:$.messageCount+1,onOpenChat:()=>{return e=$.sessionId,q([]),M(!1),void P(e);var e},isReadOut:!1})})),s("div",Object.assign({className:"flex shrink-0 grow justify-end"},{children:s("p",Object.assign({className:h(F.b3,"font-semibold uppercase opacity-30")},{children:L}))}))]}))}))]}))]})),s(m,{})]})):null};export{x as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e}from"react/jsx-runtime";import{useMemo as t,useEffect as r}from"react";import{usePickaxeMarkdownContext as n}from"../../hooks/usePickaxeMarkdownContext.js";import o from"../common/TextShimmer.js";const i=({node:r,children:i})=>{const{theme:s,actionState:c}=n(),
|
|
1
|
+
import{jsx as e}from"react/jsx-runtime";import{useMemo as t,useEffect as r}from"react";import{usePickaxeMarkdownContext as n}from"../../hooks/usePickaxeMarkdownContext.js";import o from"../common/TextShimmer.js";const i=({node:r,children:i})=>{const{theme:s,actionState:c,isStreaming:d}=n(),a=t((()=>{if(!r||!r.properties)return"processing";const e=r.properties.dataIndex;return e?c[e]:"processing"}),[c]),p=t((()=>{try{if("undefined"==typeof window||"undefined"==typeof document)return!1;if(!document.documentElement)return!1;return""!==getComputedStyle(document.documentElement).getPropertyValue("--tw-ring-color")}catch(e){return!1}}),[]),m=t((()=>"string"==typeof i?i:(null==i?void 0:i.toString())||"Processing..."),[i]),u=!d||"done"===a||"error"===a;return e(o,Object.assign({theme:s,isDisabled:u||!p},!u&&!p&&{className:"pxe-blink"},{children:m}))},s=({node:t})=>{const{setActionState:o}=n();return r((()=>{if(!t||!t.properties)return;const e=t.properties.dataIndex;e&&o((t=>Object.assign(Object.assign({},t),{[e]:"done"})))}),[]),e("div",{})},c=({node:t,children:o})=>{const{setActionState:i}=n();return r((()=>{if(!t||!t.properties)return;const e=t.properties.dataIndex;e&&i((t=>Object.assign(Object.assign({},t),{[e]:"error"})))}),[]),e("div",Object.assign({className:"pxe-red pxe-action-error"},{children:o}))};export{i as ActionCaption,c as ActionError,s as ActionFinished};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as o}from"react/jsx-runtime";import{createContext as e,useState as t}from"react";const r=e({}),n=({children:e,theme:n="light",syntaxTheme:
|
|
1
|
+
import{jsx as o}from"react/jsx-runtime";import{createContext as e,useState as t}from"react";const r=e({}),n=({children:e,theme:n="light",syntaxTheme:a,colors:l={primary:"#F6F8FA",text:"#000000",secondary:"#FFFFFF",secondaryText:"#000000",accent:"#228DD7",accentText:"#FFFFFF",error:"#EF4444"},styles:c={theme:"light",font:"Real Head Pro",fontSize:"md",formFieldStyle:"block",btnStyle:"filled",outlineThickness:1,cornerRadius:8},readOnly:i=!1,isStreaming:s=!1,rtl:d=!1,disableHtml:F=!1,disableJs:m=!1,disableCss:g=!1,disableReasoning:p=!1,onArtifactClick:b})=>{const[C,h]=t(n),[u,y]=t({});return o(r.Provider,Object.assign({value:Object.assign(Object.assign({theme:C,colors:l,styles:c,actionState:u,isStreaming:s,readOnly:i,rtl:d,disableHtml:F,disableJs:m,disableCss:g,disableReasoning:p,setTheme:h,setActionState:y},!!b&&{onArtifactClick:b}),{syntaxTheme:a||{'code[class*="language-"]':{color:"#c5c8c6",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:"Inconsolata, Monaco, Consolas, 'Courier New', Courier, monospace",direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",width:"max-content"},'pre[class*="language-"]':{color:"#c5c8c6",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:"Inconsolata, Monaco, Consolas, 'Courier New', Courier, monospace",direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",overflow:"auto",borderRadius:"0.3em",background:"#1d1f21",width:"max-content"},':not(pre) > code[class*="language-"]':{background:"#1d1f21",padding:".1em",borderRadius:".3em"},comment:{color:"#7C7C7C"},prolog:{color:"#7C7C7C"},doctype:{color:"#7C7C7C"},cdata:{color:"#7C7C7C"},punctuation:{color:"#c5c8c6"},".namespace":{opacity:".7"},property:{color:"#96CBFE"},keyword:{color:"#96CBFE"},tag:{color:"#96CBFE"},"class-name":{color:"#FFFFB6",textDecoration:"underline"},boolean:{color:"#99CC99"},constant:{color:"#99CC99"},symbol:{color:"#f92672"},deleted:{color:"#f92672"},number:{color:"#FF73FD"},selector:{color:"#A8FF60"},"attr-name":{color:"#A8FF60"},string:{color:"#A8FF60"},char:{color:"#A8FF60"},builtin:{color:"#A8FF60"},inserted:{color:"#A8FF60"},variable:{color:"#C6C5FE"},operator:{color:"#EDEDED"},entity:{color:"#FFFFB6",cursor:"help"},url:{color:"#96CBFE"},".language-css .token.string":{color:"#87C38A"},".style .token.string":{color:"#87C38A"},atrule:{color:"#F9EE98"},"attr-value":{color:"#F9EE98"},function:{color:"#DAD085"},regex:{color:"#E9C062"},important:{color:"#fd971f",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"}}})},{children:e}))};export{n as PickaxeMarkdown,r as PickaxeMarkdownContext,n as default};
|
package/dist/esm/components/Pickaxe/common/PickaxeMessageParts/ActionToolCaptionPart/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as i}from"react/jsx-runtime";import{usePickaxeContext as t}from"../../../../../hooks/pickaxe/usePickaxeContext.js";import o from"./TextShimmer.js";const e=({caption:e,isLoading:s,isVisible:r})=>{const{colors:n,translations:a}=t();return r?i(o,Object.assign({theme:"#000000"===n.text?"light":"dark",isDisabled:!s},{children:e||((null==a?void 0:a.loading)||"Loading...")})):null};export{e as default};
|
package/dist/esm/components/Pickaxe/common/PickaxeMessageParts/ReasoningCaptionPart/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as i}from"react/jsx-runtime";import{usePickaxeContext as o}from"../../../../../hooks/pickaxe/usePickaxeContext.js";import t from"../ActionToolCaptionPart/TextShimmer.js";const e=({caption:e,isLoading:s,isVisible:n})=>{const{colors:r,translations:a}=o();return n?i(t,Object.assign({theme:"#000000"===r.text?"light":"dark",isDisabled:!s},{children:e||((null==a?void 0:a.loading)||"Loading...")})):null};export{e as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e}from"react/jsx-runtime";import{useRef as t,Suspense as n,lazy as i}from"react";import{PickaxeMarkdownRenderer as
|
|
1
|
+
import{jsx as e}from"react/jsx-runtime";import{useRef as t,Suspense as n,lazy as i}from"react";import{PickaxeMarkdownRenderer as s}from"../PickaxeMarkdown/Renderer.js";import o,{isGeneratedFileUrl as r,normalizeMarkdownUrl as a,getFilePreviewInfo as l,shouldSuppressRichPreviewForUrl as c,shouldRenderFilePreview as p}from"../PickaxeMarkdown/Components/A/FilePreview.js";import{safeJSONParse as u}from"../../../../common/utils.js";import d from"../../../../common/cn.js";const m=i((()=>import("./TextPart/index.js"))),f=i((()=>import("./ReasoningPart/index.js"))),v=i((()=>import("./ActionToolCaptionPart/index.js"))),g=i((()=>import("./ReasoningCaptionPart/index.js"))),w=/(!?)\[([^\]\n]+)\]\((https?:\/\/[^\s)]+|www\.[^\s)]+)\)/g,h=e=>{const t=new Set;for(const n of e){if("data-tool-assets"!==n.type)continue;const e=u(n.content);if(null==e?void 0:e.assets)for(const n of e.assets)n.value&&!r(n.value)&&t.add(a(n.value))}return t},y=({className:i,parts:r,isStreaming:y=!1})=>{const j=t(new Set);j.current=new Set;const x=h(r),k=r.reduce(((e,t,n)=>t.isVisible?n:e),-1);return e("div",Object.assign({className:d("flex flex-col gap-2",i)},{children:e(n,Object.assign({fallback:e("div",{})},{children:r.map(((t,n)=>{if(!t.isVisible)return null;if("text"===t.type){const i=((e,t,n)=>{var i,s;const o=[];let r=0;for(const u of e.matchAll(w)){const d=null!==(i=u.index)&&void 0!==i?i:0,m=u[0],f="!"===u[1],v=null===(s=u[2])||void 0===s?void 0:s.trim(),g=u[3],w=l(g);if(!w)continue;if(c(w.url,n))continue;d>r&&o.push({type:"markdown",value:e.slice(r,d)});const h=v&&a(v)!==w.url?v:void 0;p(w,t)?o.push({type:"preview",key:`${w.url}-${d}`,fileInfo:w,displayName:h}):o.push({type:"markdown",value:f?m:`[${v||w.fileName}](${w.url})`}),r=d+m.length}return r<e.length&&o.push({type:"markdown",value:e.slice(r)}),o.length?o:[{type:"markdown",value:e}]})(t.content,j,x);return e(m,{children:i.map(((t,n)=>"preview"===t.type?e(o,{fileInfo:t.fileInfo,displayName:t.displayName},t.key):t.value?e(s,{value:t.value,filePreviewSeenRef:j,suppressedRichPreviewUrls:x},n):null))},n)}if("reasoning"===t.type)return e(f,Object.assign({isReasoning:n===r.length-1},{children:e(s,{value:t.content,suppressedRichPreviewUrls:x})}),n);if("data-action-tool-caption"===t.type){const i=u(t.content),s=n===k;return e(v,Object.assign({},i&&i,{isLoading:y&&s,isVisible:s}),n)}if("data-reasoning-caption"===t.type){const i=u(t.content),s=n===k;return e(g,Object.assign({},i&&i,{isLoading:y&&s,isVisible:s}),n)}return null}))}))}))};export{y as default,h as getSuppressedRichPreviewUrls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e}from"../../_virtual/_tslib.js";import{pickaxeApi2 as n}from"../../common/api/pickaxe.js";import{useState as r,useRef as
|
|
1
|
+
import{__awaiter as e}from"../../_virtual/_tslib.js";import{pickaxeApi2 as n}from"../../common/api/pickaxe.js";import{useState as r,useRef as o,useEffect as t,useCallback as i}from"react";const l={ar:"ar-SA",ca:"ca-ES",cs:"cs-CZ",da:"da-DK",de:"de-DE",en:"en-US",es:"es-ES",fi:"fi-FI",fr:"fr-FR",he:"he-IL",hi:"hi-IN",it:"it-IT",ja:"ja-JP",ko:"ko-KR",nb:"nb-NO",nl:"nl-NL",pl:"pl-PL",pt:"pt-PT",ro:"ro-RO",ru:"ru-RU",sv:"sv-SE",th:"th-TH",tr:"tr-TR",vi:"vi-VN",zh:"zh-CN",zu:"zu-ZA"};let s=null;const a=new Map,c=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),u=({text:r,language:o,provider:t,pickaxeId:i,preferredVoiceName:u,browserVoices:d=[],onLoading:p,onPlay:h,onEnd:v})=>{var f;null==s||s.cancel(),null===(f=window.speechSynthesis)||void 0===f||f.cancel();let w=null,y=null,g=null,m=null,S=null,b=!1,L=!1,k=!1,E=!1;const A=()=>{L||(L=!0,null==w||w.close(),w=null,null==S||S.abort(),S=null,null==g||g.pause(),g=null,m&&URL.revokeObjectURL(m),m=null,s===U&&(s=null),v())},R=()=>{b||L||h()},U={cancel:()=>{var e;b||L||(b=!0,null==y||y.close(),y=null,null==w||w.pause(),null==w||w.close(),w=null,null==S||S.abort(),S=null,null==g||g.pause(),g=null,m&&URL.revokeObjectURL(m),m=null,null===(e=window.speechSynthesis)||void 0===e||e.cancel(),A())}};s=U,p();const x=(t=!0)=>e(void 0,void 0,void 0,(function*(){var e;try{const[{data:i},s]=yield Promise.all([n.post("/speech"),import("microsoft-cognitiveservices-speech-sdk")]);if(!i.success||!i.token)throw new Error(i.error||"Azure Speech token was not returned");if(b||L)return;const d=(e=>{if(!e)return"en-US";const n=e.toLowerCase();return"pt-br"===n?"pt-BR":l[n.split("-")[0]]||e})(o),p=s.SpeechConfig.fromAuthorizationToken(i.token,"eastus");p.speechSynthesisLanguage=d,p.speechSynthesisOutputFormat=s.SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3;const h=new s.SpeakerAudioDestination;h.onAudioStart=()=>{const e=h.internalAudio;e?e.addEventListener("playing",R,{once:!0}):R()},h.onAudioEnd=A,w=h;const v=s.AudioConfig.fromSpeakerOutput(h),f=new s.SpeechSynthesizer(p,v);y=f;let g=(t?u:void 0)||a.get(d);if(!g){const n=yield f.getVoicesAsync(d);if(b||L)return;if(g=null===(e=n.voices.find((e=>e.locale===d)))||void 0===e?void 0:e.shortName,!g)throw new Error(`No Azure voice is available for ${d}`);a.set(d,g)}const m=g,S=yield new Promise(((e,n)=>{const o=`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${d}"><voice name="${c(m)}"><break time="500ms"/>${c(r)}</voice></speak>`;f.speakSsmlAsync(o,e,n)}));if(f.close(),y=null,b||L)return;if(S.reason!==s.ResultReason.SynthesizingAudioCompleted)throw new Error(S.errorDetails||"Azure speech synthesis failed")}catch(e){if(null==y||y.close(),y=null,null==w||w.close(),w=null,b||L)return;console.warn("Azure text-to-speech failed; using browser speech",e),(()=>{if(b||L||k)return;if(k=!0,!("speechSynthesis"in window)||!("SpeechSynthesisUtterance"in window))return void A();const e=new SpeechSynthesisUtterance(r),n=o||"en",t=d.find((e=>e.lang.startsWith(n)&&e.name.includes("Google")))||d.find((e=>e.lang.startsWith(n)));t?(e.voice=t,e.lang=t.lang):e.lang=n,e.onstart=R,e.onend=A,e.onerror=A,window.speechSynthesis.speak(e)})()}})),z=e=>{b||L||E||(E=!0,console.warn("ElevenLabs text-to-speech failed; using Azure speech",e),null==S||S.abort(),S=null,g&&(g.onplaying=null,g.onended=null,g.onerror=null,g.pause()),g=null,m&&URL.revokeObjectURL(m),m=null,x(!1))};return"elevenlabs"===t?e(void 0,void 0,void 0,(function*(){let e=!1,o=!1;try{if(!i)throw new Error("A Pickaxe ID is required");S=new AbortController;const t=yield fetch(`${n.defaults.baseURL}/speech/elevenlabs/stream`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:r,pickaxeId:i}),signal:S.signal});if(!t.ok)throw new Error("ElevenLabs speech synthesis failed");if(b||L)return;if(g=new Audio,g.onplaying=R,g.onended=()=>{!e||o?A():console.warn("ElevenLabs audio ended before its response stream completed; waiting for more audio")},g.onerror=()=>{const e=null==g?void 0:g.error;z(new Error("ElevenLabs audio playback failed"+(e?` (code ${e.code})`:"")))},!("MediaSource"in window)||!MediaSource.isTypeSupported("audio/mpeg")||!t.body)return m=URL.createObjectURL(yield t.blob()),g.src=m,void(yield g.play());e=!0;const l=new MediaSource;m=URL.createObjectURL(l),g.src=m;const s=yield new Promise(((e,n)=>{l.addEventListener("sourceopen",(()=>{try{e(l.addSourceBuffer("audio/mpeg"))}catch(e){n(e)}}),{once:!0})})),a=t.body.getReader();let c,u=!1,d=null;for(;!b&&!L&&!E;){const{done:e,value:n}=yield a.read();if(e)break;(null==n?void 0:n.byteLength)&&(yield new Promise(((e,r)=>{const o=()=>{s.removeEventListener("updateend",t),s.removeEventListener("error",i)},t=()=>{o(),e()},i=()=>{o(),r(new Error("Audio buffer failed"))};s.addEventListener("updateend",t),s.addEventListener("error",i),s.appendBuffer(n)})),u?!g.paused||b||L||g.play().catch(z):(u=!0,d=g.play().catch((e=>{c=e}))))}if(o=!0,b||"open"!==l.readyState||l.endOfStream(),b||E||!(null==g?void 0:g.ended)||A(),!d)throw new Error("ElevenLabs returned no audio");if(yield d,c)throw c}catch(e){z(e)}})):x(),U},d=(e=!0,n={})=>{const[l,s]=r(!1),[a,c]=r(!1),[d,p]=r([]),h=o(null),v=o(!0);t((()=>(v.current=!0,()=>{var e;v.current=!1,null===(e=h.current)||void 0===e||e.cancel(),h.current=null})),[]),t((()=>{if(!e||!("speechSynthesis"in window))return;const n=()=>{const e=window.speechSynthesis.getVoices();e.length>0&&p(e)};return n(),window.speechSynthesis.addEventListener("voiceschanged",n),()=>{window.speechSynthesis.removeEventListener("voiceschanged",n)}}),[e]);const f=i((()=>{var e;null===(e=h.current)||void 0===e||e.cancel(),h.current=null}),[]);return{isLoading:l,isSpeaking:a,speak:i(((e,r)=>{if(!e)return;const o=u({text:e,language:r,provider:n.provider,pickaxeId:n.pickaxeId,preferredVoiceName:n.voiceName,browserVoices:d,onLoading:()=>{v.current&&(s(!0),c(!1))},onPlay:()=>{v.current&&(s(!1),c(!0))},onEnd:()=>{h.current===o&&(h.current=null),v.current&&(s(!1),c(!1))}});h.current=o}),[d,n]),stop:f}};export{d as useTextToSpeech};
|
|
@@ -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};
|