1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{};e._posthogReleaseId=e._posthogReleaseId||"01a0f37e-c3c7-0000-be7f-3fe4a1107402";var n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="7f2d715c-599b-5076-a783-2d2245f7a562")}catch(e){}}();const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index.es-CFf7dwvF.js","assets/index-DxbaJC5V.js"])))=>i.map(i=>d[i]); 2import{r as s,j as r}from"./index-DxbaJC5V.js";import{a as hp,u as pp}from"./useConversationRegistration-BfNGnjXM.js";import{u as mp}from"./pending-chat-context-22417Yc5.js";import{a as gp}from"./useQuery-ByUEXDjV.js";import{f as Br,b as ec,g as Fr,s as _n,d as xp,i as Id,e as yp,p as $i,h as bp,j as tc,w as nc,c as rc,k as sc}from"./benchTextures-Bx_SO82a.js";import{B as st}from"./Button-C3-Bd2pt.js";import{u as Cd,M as hr,G as wp,T as vp,L as kp,l as Sp,D as Ed,m as Ip,t as Cp,e as Ep,n as Rp,o as Mp,p as jp,q as Np,S as cs,b as Dp,W as Tp,s as ri,f as Ap,r as Pi,h as oc,i as $p,j as Pp,k as ic}from"./textShadow-Bgzwdrlo.js";import{M as ds,u as ac,c as Vs,F as lc,N as Lp,O as zp,G as _p,b as Op,E as Bp,I as Fp,K as Gp,r as si,d as Wp,P as oi,D as sr,x as Sr,e as Rd,n as Hp,Q as Up,m as Md,v as Xp,w as Yp,A as Kp,j as Vp,k as qp,z as Jp}from"./MultiSelectPanel-B61zSuLC.js";import{D as At}from"./DeckIcon-DLB-qwAQ.js";import{a as Zp}from"./alignElementOnCanvas-fNnJsFz1.js";import{a as Un,C as Xn}from"./presentation-CeYPK36v.js";import{b as Ln,N as uo,g as jd,L as ar,I as qs,E as Qp,G as ii,F as ai,h as em,f as tm,D as Gr,k as Nd,n as nm}from"./presentationFactory-COg4YBI1.js";import{s as rm,a as sm}from"./textSizeMode-KSY43vVW.js";import{g as Js,f as cc,h as dc,w as uc,b as fc,a as om,s as hc,e as im}from"./gradientFill-rgkyeWaQ.js";import{a as am,g as lm,F as xo}from"./catalog-CDRZuitP.js";import{b as li,a as Li,e as Dd}from"./loadFont-C4ICaR32.js";import{B as zi,C as Td,D as ko,E as Ji,F as cm,G as dm,H as um,W as cr,I as Ad,J as zn,K as fm,S as pc,L as hm,M as Cn,N as En,v as Wr,O as ms,Q as pm,h as mm,j as gm,R as xm,T as ym,k as bm,l as wm,z as mc,U as vm,y as $d,V as gc,X as _i,P as km,Y as xc,u as Sm,Z as So,_ as Io,$ as Pd}from"./birtvyDocSync-BqtO_Ife.js";import{a as Kn}from"./proxy-BPtuvrEa.js";import{c as Im,f as yc,a as bc,t as Zs,u as Cm,m as wc}from"./imageElement-Cqv6Pkr3.js";import{P as Oi}from"./PresentationOverlay-BsgeBqpJ.js";import{d as Ld,b as zd,c as _d}from"./ElementVisual-CNLaY1FO.js";import{i as rn,a as Ke,S as Je,G as In,b as gn,d as yo,e as Zi,C as Od,f as Em,c as Bd,g as Fd,h as Gd,t as vc}from"./birtvySlide-ZLYJ5aYm.js";import{h as kc,a as Rm,d as Sc,e as Mm,c as ci,E as Yn,s as Ic,f as Cc}from"./snapElementBounds-CNAbaO9G.js";import{u as Qi}from"./toast-context-CVDjJXWN.js";import{A as jm}from"./AvatarDropdown-cQyECgcN.js";import{C as Nm}from"./CanvasZoomControl-Cft4T33r.js";import{c as Dm}from"./index-B3J564RP.js";import{T as ur}from"./Tooltip-B99_xLlT.js";import{u as Tm,a as Am}from"./canvasPlacement-DVx1GeFo.js";import{E as ea}from"./OutlinePanel.module-DgE39wHR.js";import{u as Wd,p as fo,F as $m,a as Pm,d as Bi}from"./formatting-toolbar.config-CYuaxtU5.js";import{_ as ta}from"./preload-helper-ckwbz45p.js";import{y as Ec}from"./typeScale-DaL2j0P-.js";import{g as na,s as Lm,f as di,a as zm,c as _m,i as Om,b as Bm,d as Rc,e as Mc,C as Fm}from"./birtvyPresent-CCJNRAS5.js";import{W as Gm}from"./WidgetCollapse-JzCHS1vP.js";import{s as Qt,d as Wm}from"./PlanWidgetUI-CbtOGRZB.js";import{r as Hd,h as Hm,s as Um,i as Xm,l as Ym}from"./birtvyRealDeck-B94UucZV.js";import{w as Vn,k as bo,C as Km,D as Ud,m as Hr,E as ra,F as sa,G as Co,H as Xd,c as Yd,I as Vm}from"./birtvyOpenDoc-CnAfUiBu.js";import{b as qm,s as Jm}from"./artifactMeta-BrftK_GI.js";import{l as Zm,r as Qm}from"./artifactLogos-D3fbY9kp.js";import{C as Ir}from"./CreditSlider-BkN48Bd3.js";import{n as eg,F as jc,W as tg}from"./textScale-DAmDM3M-.js";import{a as ng}from"./ColorWheel-K0lWquPx.js";import{o as rg,e as sg}from"./brandFonts-DUP_gOe4.js";import{s as og}from"./FontPicker-mbuuokK8.js";import{p as ig,c as Nc,e as ag,a as lg,F as cg,u as dg}from"./useOverviewSections-CoAyluhH.js";import{u as ug}from"./usePlanningModel-CZqhqe7b.js";import{B as fg}from"./BirtvyThemeModal-BrFZisXR.js";import{s as hg,S as Dc}from"./birtvySnap-k8y8gug_.js";import{c as pg,a as mg,b as gg,w as xg}from"./captureSlide-CVoaMuYG.js";import{a as yg}from"./sanitizeHtml-DavX7wGo.js";import{v as Fi,f as bg}from"./artifactValidate-DLjE1M5d.js";import{s as wg,d as vg,e as kg,h as Sg,i as Ig}from"./deckgenDecks-rFXkRrgY.js";import{u as Cg}from"./useBirtvyPersistence-C8mw_OLZ.js";import{s as Kd,b as Vd,O as qd}from"./bakeFlowHtml-cvLgJPYW.js";import{d as Eo,p as oa,b as ia,m as Jd,r as vs,c as Eg}from"./moodboardStyle-D7D6GYRR.js";import{g as aa,G as Zd,D as Rg}from"./deckGenSchema-DgB85Meq.js";import{g as Ur,D as Ro,A as Mg,h as ui,b as jg,c as Ng,d as Dg,f as Gi}from"./generationControls-DKll6CG3.js";import{s as Tc}from"./birtvyOpenGenerate-BccaGh3Q.js";import{d as ho,a as Tg}from"./docStream-2-WAOIsT.js";import{d as Ag}from"./artifactProgress-DxlnfgLn.js";import{r as $g}from"./styleForArtifact-BgNC0TdP.js";import{g as Pg}from"./artifactPackages-CSBcXF7e.js";import{c as Lg}from"./CanvasLoader-UqSD9dVQ.js";import{T as Qd}from"./ThinkingIndicatorUI-D70kHrRS.js";import{C as zg,S as _g}from"./WebSearchToggleButtonUI-6TezT6kG.js";import"./dotm-square-11-Bk-omRrD.js";import{A as Og}
2from"./AttachmentCardsGridUI-Dn8bHpF1.js";import{M as eu}from"./ModelDropdownButtonUI-CZAokCZP.js";import{u as Ac,M as tu}from"./ModelDropdownMenuUI-CBdreqT6.js";import{u as nu}from"./useModelAccess-Cm6pzxm7.js";import{r as Mo}from"./index-BtHjyibE.js";import{P as Bg}from"./PlanningChat-OkRXb4iV.js";import{a as Fg}from"./pdfToImages-BZ0feSFZ.js";import{a as Gg,s as Wg}from"./designSystemSynthesis-ZgyEcwq6.js";import{a as Hg}from"./confirmStore-DTQpaa-Q.js";import{A as Ug}from"./index-CapY4Fza.js";import"./useMutation-DRSZIGbt.js";import"./mutation-TfB09QrR.js";import"./constants-Cu_zl2wa.js";import"./index-B5HoE9QT.js";import"./utils-CDN07tui.js";import"./Icon-B0lBIVI0.js";import"./gradientCss-DfDVxKo3.js";import"./subscription-DMe-nmKX.js";import"./constants-Bp5JMrgz.js";import"./presentationStore-D9HDFtxZ.js";import"./slideCanvasLayout-Cv4vkKlH.js";import"./slideGroup-DKTKl4mk.js";import"./canvasSnap-DQlnzUtF.js";import"./elementZIndex-DXYaS4i6.js";import"./presentationItems-DbrVQyRv.js";import"./overview.utils-DelvYQGL.js";import"./purify.es-Cx4rtWv4.js";import"./canvasDocsUtils-DqzHRhVw.js";import"./labSlideHtml-BS6tBKp1.js";import"./Dropdown-BNj-bRX3.js";import"./ToolbarPopoverPanel-5FpBYgev.js";import"./DropdownMenu-D80mxcwk.js";import"./index-DTJLDMlB.js";import"./index-BlV1dE-u.js";import"./floating-ui.dom-B7T1_iwA.js";import"./DemoScaledPortalContext-CXpB5kaP.js";import"./useCreditBalance-C9AlhbmP.js";import"./profile-context-ZoGTVkiC.js";import"./components-DO3U5poI.js";import"./index-Dd8WUQxZ.js";import"./index-BOIOgD3-.js";import"./index-CNPM7ZIh.js";import"./linkify-BOZn_LAz.js";import"./use-reduced-motion-BmfqWHpC.js";import"./useRollingThinkingText-D_MZvd3A.js";import"./LogoUI-DSLaITqI.js";import"./TypewriterReveal-DbDmCS3s.js";import"./kitImport-DoEztU_a.js";import"./kitSite-CJghb54X.js";import"./styleRender-DUBt_qhZ.js";import"./deckFlowPrompt-BD3jD9KK.js";import"./brandLogoContrast-CHo9rYfZ.js";import"./PricingTable.module-BSzb_fTy.js";import"./colorMath-92igDrdG.js";import"./Input-CL7zbOyD.js";import"./index-Bbnb0w5g.js";import"./styleImport-TfNS93kc.js";import"./PlanBadge-D20bL5oP.js";import"./useSubscriptionTier-C_KuQEO2.js";import"./file-validation-BJjJtITJ.js";import"./useEnabledModels-Qelr3GTf.js";import"./useChatInputState-C-xnOzS9.js";import"./integration-oauth-B3AuaZWf.js";import"./outOfCredits-B7ZwISpW.js";import"./date-utils-DZNKK9IS.js";function la(e,t,n=!0,o){s.useEffect(()=>{if(!n)return;const i=u=>{var d,p;const c=u.target;(d=e.current)!=null&&d.contains(c)||(p=c==null?void 0:c.closest)!=null&&p.call(c,"[data-birtvy-rail]")||o||t()},a=u=>{u.key==="Escape"&&t()},l=window.setTimeout(()=>{window.addEventListener("pointerdown",i,!0),window.addEventListener("keydown",a)},0);return()=>{window.clearTimeout(l),window.removeEventListener("pointerdown",i,!0),window.removeEventListener("keydown",a)}},[n,t,o])}let fi=[];function ru({conversationId:e,onPlace:t,onClose:n,positionClassName:o,positionStyle:i}){const{images:a,isLoading:l,isUploading:u,error:c,clearError:d,uploadImages:p,deleteImages:h}=Cd(e),m=!!e,[g,k]=s.useState(()=>fi),y=m?a:g,f=s.useRef(null),I=s.useRef(null);la(f,n);const w=async S=>{const A=(S?Array.from(S):[]).filter(T=>T.type.startsWith("image/"));if(A.length===0)return;if(m){d();try{await p(A)}catch{}return}const O=await Promise.all(A.map(async T=>({id:crypto.randomUUID(),url:await Td(T),name:T.name})));k(T=>{const X=[...T,...O];return fi=X,X})},x=S=>{if(m){h([S]);return}k(A=>{const O=A.filter(T=>T.id!==S);return fi=O,O})},D="z-[1400] flex w-[320px] flex-col overflow-hidden rounded-[20px] border border-[var(--color-border-default)] bg-[var(--color-default)] shadow-[var(--shadow-modal-lg)]",R=o??"fixed left-[calc(var(--spacing-12)+72px)] top-1/2 -translate-y-1/2",j=i!=null;return r.jsxs(Kn.div,{ref:f,className:`${R} ${D}
2`,style:{transformOrigin:j?"bottom center":"left center",...i},initial:j?{opacity:0,scale:.96,y:6}:{opacity:0,scale:.96,x:-4},animate:{opacity:1,scale:1,x:0,y:0},transition:{duration:.14,ease:[.22,1,.36,1]},onPointerDown:S=>S.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center gap-[var(--spacing-8)] border-b border-[var(--color-border-default)] py-[var(--spacing-12)] pl-[var(--spacing-16)] pr-[var(--spacing-12)]",children:[r.jsx("span",{className:"flex-1 text-sm font-medium text-[var(--color-text-default)]",children:"Media"}),r.jsx(st,{type:"button",variant:"ghost",size:"xs",disabled:u,loading:u,leadIcon:"upload",title:"Upload images (PNG, JPG, WebP or SVG)",onClick:()=>{var S;return(S=I.current)==null?void 0:S.click()},children:u?"Uploadingâ¦":"Upload"}),r.jsx("input",{ref:I,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:S=>{w(S.target.files),S.target.value=""}})]}),r.jsxs("div",{className:"h-[320px] overflow-y-auto p-[var(--spacing-8)]",children:[l?r.jsx("div",{className:"grid grid-cols-3 gap-[var(--spacing-8)]",children:Array.from({length:9}).map((S,A)=>r.jsx("div",{className:`aspect-square rounded-[12px] ${hr.shimmer}`},A))}):y.length===0?r.jsxs("div",{className:"px-2 py-6 text-center text-sm text-[var(--color-text-muted)]",children:["No media yet.",r.jsx("button",{type:"button",className:"ml-1 font-medium text-[var(--color-text-default)] underline disabled:opacity-50",disabled:u,onClick:()=>{var S;return(S=I.current)==null?void 0:S.click()},children:"Upload one"})]}):r.jsx("div",{className:"grid grid-cols-3 gap-[var(--spacing-8)]",children:y.map(S=>r.jsxs("div",{className:"group relative block rounded-[12px] ring-1 ring-[var(--color-border-default)] transition-all duration-150",children:[r.jsx("button",{type:"button",title:S.name,draggable:!0,className:"block aspect-square w-full cursor-grab overflow-hidden rounded-[12px] bg-[var(--color-subtle)] outline-none active:cursor-grabbing",onClick:()=>{t(S.url),n()},onDragStart:A=>{A.dataTransfer.setData(zi,S.url),A.dataTransfer.effectAllowed="copy";const O=A.currentTarget.querySelector("img");O&&A.dataTransfer.setDragImage(O,O.clientWidth/2,O.clientHeight/2)},children:r.jsx("img",{src:S.url,alt:S.name,draggable:!1,className:"h-full w-full object-cover"})}),r.jsx("button",{type:"button","aria-label":"Delete image",title:"Delete",style:{width:18,height:18},className:"absolute right-1.5 top-1.5 flex items-center justify-center rounded-[6px] bg-black/40 text-white opacity-0 backdrop-blur-[1px] transition-all hover:bg-[var(--color-state-error,#dc2626)] group-hover:opacity-100",onClick:A=>{A.stopPropagation(),x(S.id)},children:r.jsx(At,{name:"delete-bin-6",size:12})})]},S.id))}),c?r.jsx("p",{className:"px-2 pt-2 text-xs text-[var(--color-state-error,#dc2626)]",children:c}):null]})]})}const Xg="_inert_tcqrs_3",Yg="_placeholder_tcqrs_9",Kg="_placeholderTitle_tcqrs_24",Vg="_placeholderNote_tcqrs_30",Qs={inert:Xg,placeholder:Yg,placeholderTitle:Kg,placeholderNote:Vg};function qg(e){if(!e||typeof e!="object")return null;const t=e.content;return typeof(t==null?void 0:t.title)=="string"&&t.title.trim()?t.title.trim():null}function jo({config:e,interactive:t=!0}){const n=qg(e);return r.jsxs("div",{className:`${Qs.placeholder} ${t?"":Qs.inert}`,children:[n?r.jsx("span",{className:Qs.placeholderTitle,children:n}):null,r.jsx("span",{className:Qs.placeholderNote,children:"Chart unavailable"})]})}function Wi({config:e,element:t}){const n=Math.max(0,Math.min(t.cornerRadius??0,Math.floor(Math.min(t.width,t.height)/2)));return r.jsx("div",{style:{position:"absolute",inset:0,boxSizing:"border-box",overflow:n>0?"hidden":"visible",..._d({...t,fillImage:void 0,shapeFillMode:"color"}),...zd(t),borderRadius:Ld(t,t.width,t.height,n)},children:r.jsx(jo,{config:e,interactive:!0})})}const Jg=8;function Zg(e,t){const n=s.useRef(e);n.current=e;const o=s.useRef({key:e,map:new Map});o.current.key!==e&&(o.current={key:e,map:new Map});const i=S=>{const A=o.current;let O=A.map.get(S);return O||(O=kc(n.current,new Set([S])),A.map.set(S,O)),O},a=s.useRef({}),l=s.useRef({}),u=s.useRef(!1),c=s.useRef(null),d=s.useRef(null),p=s.useRef([]),h=s.useRef([]),m=s.useRef([]),g=s.useRef(!1),k=s.useRef(null),y=(S,A,O=null,T=null,X=[])=>{const L=Jg,W=Math.max(t,.01),H=1/W,ae=5/W,ge=3/W,J=c.current,ce=d.current;J&&(S==null?J.style.display="none":(J.style.display="block",J.style.width=`${H}px`,J.style.left=`${S}px`,O?(J.style.top=`${O.start-L}
2px`,J.style.height=`${O.end-O.start+L*2}px`):(J.style.top="0px",J.style.height=`${Xn}px`))),ce&&(A==null?ce.style.display="none":(ce.style.display="block",ce.style.height=`${H}px`,ce.style.top=`${A}px`,T?(ce.style.left=`${T.start-L}px`,ce.style.width=`${T.end-T.start+L*2}px`):(ce.style.left="0px",ce.style.width=`${Un}px`)));const we=p.current,ve=h.current,oe=m.current;for(let pe=0;pe<we.length;pe+=1){const K=we[pe],fe=oe[pe],ie=ve[pe*2],Y=ve[pe*2+1],re=X[pe];if(!re){K&&(K.style.display="none"),fe&&(fe.style.display="none"),ie&&(ie.style.display="none"),Y&&(Y.style.display="none");continue}const le=Math.max(0,re.to-re.from),b=(re.from+re.to)/2,C=(z,B)=>{z&&(z.style.display="block",re.axis==="x"?(z.style.left=`${B-H/2}px`,z.style.top=`${re.perp-ae}px`,z.style.width=`${H}px`,z.style.height=`${ae*2}px`):(z.style.left=`${re.perp-ae}px`,z.style.top=`${B-H/2}px`,z.style.width=`${ae*2}px`,z.style.height=`${H}px`))};C(ie,re.from),C(Y,re.to),K&&(K.style.display="block",re.axis==="x"?(K.style.left=`${re.from}px`,K.style.top=`${re.perp-H/2}px`,K.style.width=`${le}px`,K.style.height=`${H}px`):(K.style.left=`${re.perp-H/2}px`,K.style.top=`${re.from}px`,K.style.width=`${H}px`,K.style.height=`${le}px`)),fe&&(fe.textContent=String(Math.round(le)),fe.style.display=le>0?"flex":"none",fe.style.alignItems="center",fe.style.justifyContent="center",fe.style.width="max-content",fe.style.height=`${17/W}px`,fe.style.fontSize=`${11/W}px`,fe.style.padding=`0 ${6/W}px`,fe.style.borderRadius=`${3/W}px`,re.axis==="x"?(fe.style.left=`${b}px`,fe.style.top=`${re.perp+ge}px`,fe.style.transform="translateX(-50%)"):(fe.style.left=`${re.perp+ge}px`,fe.style.top=`${b}px`,fe.style.transform="translateY(-50%)"))}},f=()=>{g.current||(k.current&&(window.clearTimeout(k.current),k.current=null),k.current=window.setTimeout(()=>y(null,null),180))},I=s.useRef(()=>{});return I.current=()=>{g.current=!1,y(null,null)},s.useEffect(()=>{const S=()=>{g.current=!1,k.current&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>I.current(),180)};return window.addEventListener("pointerup",S),window.addEventListener("pointercancel",S),()=>{window.removeEventListener("pointerup",S),window.removeEventListener("pointercancel",S)}},[]),s.useEffect(()=>{const S=O=>{u.current=O.metaKey||O.ctrlKey},A=()=>{u.current=!1};return window.addEventListener("keydown",S),window.addEventListener("keyup",S),window.addEventListener("blur",A),()=>{window.removeEventListener("keydown",S),window.removeEventListener("keyup",S),window.removeEventListener("blur",A)}},[]),s.useEffect(()=>()=>{k.current&&window.clearTimeout(k.current)},[]),{createSnapDragPosition:S=>{const A=new Set([S.id]);return(O,T)=>{g.current=!0;const X=O<-1||T<-1||O+S.width>Un+1||T+S.height>Xn+1;if(u.current||X)return a.current[S.id]=Yn,y(null,null),{x:Math.round(O),y:Math.round(T)};const L=Ic(O,T,S.width,S.height,a.current[S.id]??Yn,{guides:i(S.id),scale:t});a.current[S.id]=L.session;let W=L.x,H=L.y;const ae=[];if(L.verticalGuide==null){const J=Cc(n.current,A,{x:W,y:H,width:S.width,height:S.height},"x",t);J.position!=null&&(W=Math.round(J.position),ae.push(...J.segments))}if(L.horizontalGuide==null){const J=Cc(n.current,A,{x:W,y:H,width:S.width,height:S.height},"y",t);J.position!=null&&(H=Math.round(J.position),ae.push(...J.segments))}const ge=ci(n.current,A,{x:W,y:H,width:S.width,height:S.height},L.verticalGuide,L.horizontalGuide);return y(L.verticalGuide,L.horizontalGuide,ge.verticalSpan,ge.horizontalSpan,ae),f(),{x:W,y:H}}},createSnapResize:S=>{const A=new Set([S.id]);return(O,T)=>{if(g.current=!0,u.current)return l.current[S.id]=Sc,y(null,null),O;const{patch:X,verticalGuide:L,horizontalGuide:W,resizeSession:H}=Mm(O,T,l.current[S.id]??Sc,{guides:i(S.id),scale:t});l.current[S.id]=H;const ae={x:typeof X.x=="number"?X.x:S.x,y:typeof X.y=="number"?X.y:S.y,width:typeof X.width=="number"?X.width:S.width,height:typeof X.height=="number"?X.height:S.height},ge=ci(n.current,A,ae,L,W);return y(L,W,ge.verticalSpan,ge.horizontalSpan),f(),L==null&&W==null?O:X}},snapCommitPatch:(S,A,O)=>{if(typeof A.width=="number"||typeof A.height=="number"){const X=l.current[S.id];delete l.current[S.id];const{patch:L,verticalGuide:W,horizontalGuide:H}=Rm(S,A,{guides:i(S.id),scale:t,resizeSession:X,resizeDirection:O});return y(W,H),f(),L}return delete a.current[S.id],delete l.current[S.id],A},beginGroupSnap:S=>{const A=new Set(S.map(ce=>ce.id));let O=1/0,T=1/0,X=-1/0,L=-1/0;for(const ce of S)O=Math.min(O,ce.x),T=Math.min(T,ce.y),X=Math.max(X,ce.x+ce.width),L=Math.max(L,ce.y+ce.height);const W={minX:O,minY:T,width:X-O,height:L-T},H=kc(e,A);let ae=Yn;return g.current=!0,{snapDelta:(ce,we)=>{const ve=W.minX+ce<-1||W.minY+we<-1||W.minX+ce+W.width>Un+1||W.minY+we+W.height>Xn+1;if(u.current||ve)return ae=Yn,y(null,null),{dx:ce,dy:we};const oe=Ic(W.minX+ce,W.minY+we,W.width,W.height,ae,{guides:H,scale:t});ae=oe.session;const pe=ci(e,A,{x:oe.x,y:oe.y,width:W.width,height:W.height},oe.verticalGuide,oe.horizontalGuide);return y(oe.verticalGuide,oe.horizontalGuide,pe.verticalSpan,pe.horizontalSpan),f(),{dx:oe.x-W.minX,dy:oe.y-W.minY}},end:()=>{g.current=!1}}},renderGuides:()=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"pointer-events-none absolute inset-0",style:{zIndex:0}
2,"aria-hidden":!0,children:[r.jsx("div",{ref:c,style:{position:"absolute",top:0,display:"none",background:ds}}),r.jsx("div",{ref:d,style:{position:"absolute",left:0,display:"none",background:ds}})]}),r.jsxs("div",{className:"pointer-events-none absolute inset-0",style:{zIndex:900002},"aria-hidden":!0,children:[[0,1,2,3].map(S=>r.jsx("div",{ref:A=>{p.current[S]=A},style:{position:"absolute",display:"none",background:ds}},S)),[0,1,2,3,4,5,6,7].map(S=>r.jsx("div",{ref:A=>{h.current[S]=A},style:{position:"absolute",display:"none",background:ds}},`cap-${S}`)),[0,1,2,3].map(S=>r.jsx("div",{ref:A=>{m.current[S]=A},style:{position:"absolute",display:"none",background:ds,color:"#fff",fontWeight:500,lineHeight:1,whiteSpace:"nowrap"}},`label-${S}`))]})]})}}const su=e=>e.type==="group"||e.type==="stack",or=(e,t)=>{const n=Ln(e),o=[],i=new Set;for(const a of t){const l=uo(n,a);i.has(l)||(i.add(l),o.push(l))}return o},hi=(e,t)=>{const n=Ln(e),o=[],i=new Set;for(const a of t)for(const l of ar(n,a))i.has(l)||(i.add(l),o.push(l));return o},pi=(e,t,n,o,i)=>{const a=Ln(e),l=[],u=new Set;for(const h of t)if(!(!a.has(h)||u.has(h))){u.add(h),l.push(h);for(const m of jd(a,h))u.has(m)||(u.add(m),l.push(m))}const c=new Map(l.map(h=>[h,n()])),d=l.map(h=>{var g;const m=a.get(h);return{...m,id:c.get(h),x:m.x+o,y:m.y+i,parentId:m.parentId!=null&&c.has(m.parentId)?c.get(m.parentId):null,childIds:(g=m.childIds)==null?void 0:g.map(k=>c.get(k)??k)}}),p=d.filter(h=>!su(h)).map(h=>h.id);return{clones:d,newLeafIds:p}},Qg=e=>{let t=e;for(let n=0;n<8;n+=1){const o=new Set(t.map(l=>l.id));let i=!1;t=t.map(l=>{if(!l.childIds)return l;const u=l.childIds.filter(c=>o.has(c));return u.length!==l.childIds.length?(i=!0,{...l,childIds:u}):l});const a=t.filter(l=>{var u;return!(su(l)&&(((u=l.childIds)==null?void 0:u.length)??0)===0)});if(a.length!==t.length&&(i=!0),t=a,!i)break}return t},$c=e=>{var t;return((t=am(e))==null?void 0:t.id)??"inter"};function mi(e){const t=lm(e);return t?`${t.family}, sans-serif`:"Inter, ui-sans-serif, system-ui, sans-serif"}function gi(e,t){if(!e||e==="transparent")return{hex:t,opacity:e==="transparent"?0:100};const n=e.match(/rgba?\(\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\s*\)/);if(n){const[o,i,a]=[n[1],n[2],n[3]].map(c=>parseInt(c,10)),l=n[4]!==void 0?parseFloat(n[4]):1;return{hex:`#${[o,i,a].map(c=>c.toString(16).padStart(2,"0")).join("")}`,opacity:Math.round(l*100)}}return e.startsWith("#")&&e.length>=7?{hex:e,opacity:100}:{hex:t,opacity:100}}function ir(e,t){if(t>=100)return e;const n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16);return`rgba(${n}, ${o}, ${i}, ${t/100})`}function ex({shape:e,slides:t,excludedIds:n,presentIds:o,graphyConfig:i,graphyConfigById:a,onSwitchSlide:l,onClose:u,onChange:c,stageInsetEdge:d=0,stageInsetRight:p=0,stageInsetAnimated:h=!0,isAgentOpen:m=!1,onToggleAgent:g,conversationId:k}){var Qr;const y=s.useRef(e.baked);y.current=e.baked;const f=s.useMemo(()=>new Proxy({},{get:(v,V)=>Reflect.get(y.current,V),set:(v,V,be)=>Reflect.set(y.current,V,be),has:(v,V)=>Reflect.has(y.current,V),deleteProperty:(v,V)=>Reflect.deleteProperty(y.current,V),ownKeys:()=>Reflect.ownKeys(y.current),getOwnPropertyDescriptor:(v,V)=>{const be=Object.getOwnPropertyDescriptor(y.current,V);return be?{...be,configurable:!0}:void 0}}),[]),[,I]=s.useState(0),w=()=>{I(v=>v+1),c()},[x,D]=s.useState(()=>new Set),R=s.useRef(x);R.current=x;const j=x.size?Array.from(x)[x.size-1]:null,S=v=>D(new Set([v])),A=()=>D(v=>v.size?new Set:v),O=(v,V)=>D(be=>{const ke=new Set(be);return V?ke.has(v)?ke.delete(v):ke.add(v):(ke.clear(),ke.add(v)),ke}),[T,X]=s.useState("select"),[L,W]=s.useState(null),[H,ae]=s.useState(!0),ge=!1,[J,ce]=s.useState(null),[we,ve]=s.useState(!1),[oe,pe]=s.useState(null),[K,fe]=s.useState(0),[ie,Y]=s.useState(null),[re,le]=s.useState(null),[b,C]=s.useState(null),z=s.useRef(null),B=s.useRef(null),[M,q]=s.useState(null),[ue,ye]=s.useState(!1),[ee,U]=s.useState(null),_=s.useRef(null),N=s.useRef(1),Z=s.useRef(null);s.useMemo(()=>t.map((v,V)=>({id:String(v.id),title:`Slide ${V+1}`})),[t]);const Q=24,G=s.useRef(null),[se,ne]=s.useState(.4);s.useEffect(()=>{const v=G.current;if(!v)return;const V=()=>{const ke=v.getBoundingClientRect();ne(Math.max(.05,Math.min((ke.width-96)/Un,(ke.height-128-Q)/Xn)))};V();const be=new ResizeObserver(V);return be.observe(v),()=>be.disconnect()},[]);const de=s.useRef(se);de.current=se;const F=s.useRef(null),$=(v,V)=>{var Le;const be=(Le=F.current)==null?void 0:Le.getBoundingClientRect(),ke=de.current;return be?{x:(v-be.left)/ke,y:(V-be.top)/ke}:{x:0,y:0}},P=s.useRef(null),me=s.useRef(null),he=j!=null?f.elements.find(v=>v.id===j)??null:null,Me=ac(v=>v.preview),He=ac(v=>v.setFontPreview),{createSnapDragPosition:Ee,createSnapResize:qe,snapCommitPatch:Ae,beginGroupSnap:jt,renderGuides:kt}=Zg(f.elements,se),Ge=Ln(f.elements),Qe=x.size?or(f.elements,x):[],ht=Qe.length===1&&qs(Ge.get(Qe[0]))&&(()=>{const v=ar(Ge,Qe[0]);return v.length>=2&&v.length===x.size&&v.every(V=>x.has(V))})(),xt=(v,V)=>{const be=Ln(f.elements),ke=uo(be,v);if(ke===v||!V&&x.size===1&&x.has(v)){O(v,V);return}const Le=ar(be,ke);D(V?Ie=>new Set([...Ie,...Le]):new Set(Le))},Xe=Array.from(x).sort().join("|");s.useEffect(()=>{var v;fe(ht?((v=Ge.get(Qe[0]))==null?void 0:v.rotation)??0:0)},[Xe]);const Ue=v=>{if(v.button!==0||T!=="select"||v.target!==v.currentTarget)return;const V=v.currentTarget,be=V.getBoundingClientRect(),ke=de.current,Le=(wt,Gt)=>({x:(wt-be.left)/ke,y:(Gt-be.top)/ke}),Ie=Le(v.clientX,v.clientY),Pe=v.pointerId;try{V.setPointerCapture(Pe)}catch{}let ze=Ie,et=!1;const Ze=v.shiftKey,ft=Ze?new Set(x):new Set;ce({x0:Ie.x,y0:Ie.y,x1:Ie.x,y1:Ie.y});
2const zt=()=>{const wt=Math.min(Ie.x,ze.x),Gt=Math.min(Ie.y,ze.y),nn=Math.max(Ie.x,ze.x),gr=Math.max(Ie.y,ze.y);return f.elements.filter(_t=>!(rn(_t)&&i==null)).filter(_t=>!(_t.x>nn||_t.x+_t.width<wt||_t.y>gr||_t.y+_t.height<Gt)).map(_t=>_t.id)},Et=()=>{window.removeEventListener("pointermove",Vt),window.removeEventListener("pointerup",Tn),window.removeEventListener("pointercancel",Zn);try{V.releasePointerCapture(Pe)}catch{}ce(null)},Vt=wt=>{if(wt.pointerId!==Pe)return;if(wt.buttons===0){console.warn("[birtvy-editor] watchdog: marquee outlived its pointerup â ending gesture"),Et();return}ze=Le(wt.clientX,wt.clientY),(Math.abs(ze.x-Ie.x)>4||Math.abs(ze.y-Ie.y)>4)&&(et=!0),ce({x0:Ie.x,y0:Ie.y,x1:ze.x,y1:ze.y});const Gt=or(f.elements,zt());D(new Set([...ft,...hi(f.elements,Gt)]))},Tn=wt=>{wt.pointerId===Pe&&(Et(),!et&&!Ze&&A())},Zn=wt=>{wt.pointerId===Pe&&Et()};window.addEventListener("pointermove",Vt),window.addEventListener("pointerup",Tn),window.addEventListener("pointercancel",Zn)},_e=(v,V)=>{const be=f.elements.findIndex(Le=>Le.id===v);if(be<0)return;const ke={...f.elements[be],...V};f.elements=f.elements.map(Le=>Le.id===v?ke:Le),w()},yt=v=>{f.elements=f.elements.filter(V=>V.id!==v),D(V=>{if(!V.has(v))return V;const be=new Set(V);return be.delete(v),be}),w()},bt=v=>{const V={...v,id:`lab${e.id}dup${N.current++}`,x:v.x+24,y:v.y+24};f.elements=[...f.elements,V],S(V.id),w()},Rt=()=>D(new Set(f.elements.map(v=>v.id))),Nt=()=>{x.size&&(f.elements=Qg(f.elements.filter(v=>!x.has(v.id))),D(new Set),w())},vt=()=>{const v=or(f.elements,x);if(!v.length)return;const{clones:V,newLeafIds:be}=pi(f.elements,v,()=>`lab${e.id}dup${N.current++}`,24,24);f.elements=[...f.elements,...V],D(new Set(be)),w()},je=v=>{const V=x.has(v)?Array.from(x):[v],be=or(f.elements,V);if(!be.length)return;B.current={snapshot:f.elements};const{clones:ke}=pi(f.elements,be,()=>`lab${e.id}dup${N.current++}`,0,0),Le=new Set(hi(f.elements,be));let Ie=f.elements.reduce((Pe,ze)=>Math.max(Pe,ze.zIndex??0),0)+1;f.elements=[...f.elements,...ke].map(Pe=>Le.has(Pe.id)?{...Pe,zIndex:Ie++}:Pe),w()},Oe=()=>{B.current&&(f.elements=B.current.snapshot,B.current=null,w())},tt=()=>{const v=or(f.elements,x);if(!v.length){z.current=null;return}const V=Ln(f.elements),be=new Set;for(const ke of v){be.add(ke);for(const Le of jd(V,ke))be.add(Le)}z.current=f.elements.filter(ke=>be.has(ke.id)).map(ke=>({...ke}))},ot=v=>{const V=z.current;if(!(V!=null&&V.length))return;const be=new Set(V.map(et=>et.id)),ke=V.filter(et=>et.parentId==null||!be.has(et.parentId)).map(et=>et.id);let Le=24,Ie=24;if(v){let et=1/0,Ze=1/0,ft=-1/0,zt=-1/0;
2for(const Et of V)Et.type==="group"||Et.type==="stack"||(et=Math.min(et,Et.x),Ze=Math.min(Ze,Et.y),ft=Math.max(ft,Et.x+Et.width),zt=Math.max(zt,Et.y+Et.height));Le=Math.round(v.x-(et+(ft-et)/2)),Ie=Math.round(v.y-(Ze+(zt-Ze)/2))}const{clones:Pe,newLeafIds:ze}=pi(V,ke,()=>`lab${e.id}dup${N.current++}`,Le,Ie);f.elements=[...f.elements,...Pe],D(new Set(ze)),w()},mt=(v,V)=>{const ke=[...f.elements].sort((Ie,Pe)=>(Pe.zIndex??0)-(Ie.zIndex??0)).findIndex(Ie=>Ie.id===v);if(ke<0)return;const Le=V==="front"?0:V==="back"?f.elements.length:V==="forward"?ke-1:ke+1;dn(v,Le)},dt=v=>{const V=Ln(f.elements),be=or(f.elements,x);if(!be.length)return;const ke=Pe=>{const ze=ar(V,Pe).map(Et=>V.get(Et)).filter(Boolean);let et=1/0,Ze=1/0,ft=-1/0,zt=-1/0;for(const Et of ze)et=Math.min(et,Et.x),Ze=Math.min(Ze,Et.y),ft=Math.max(ft,Et.x+Et.width),zt=Math.max(zt,Et.y+Et.height);return{x:et,y:Ze,width:ft-et,height:zt-Ze}},Le=new Map;if(be.length===1){const Pe=ke(be[0]),ze=Zp(Pe,v);Le.set(be[0],{dx:ze.x-Pe.x,dy:ze.y-Pe.y})}else{const Pe=lc(f.elements.filter(ze=>x.has(ze.id)));for(const ze of be){const et=ke(ze);let Ze=et.x,ft=et.y;v.horizontal==="left"?Ze=Pe.x:v.horizontal==="center"?Ze=Math.round(Pe.x+(Pe.width-et.width)/2):v.horizontal==="right"&&(Ze=Pe.x+Pe.width-et.width),v.vertical==="top"?ft=Pe.y:v.vertical==="middle"?ft=Math.round(Pe.y+(Pe.height-et.height)/2):v.vertical==="bottom"&&(ft=Pe.y+Pe.height-et.height),Le.set(ze,{dx:Ze-et.x,dy:ft-et.y})}}const Ie=new Map;for(const[Pe,ze]of Le)for(const et of ar(V,Pe))Ie.set(et,ze);f.elements=f.elements.map(Pe=>{const ze=Ie.get(Pe.id);return!ze||ze.dx===0&&ze.dy===0?Pe:{...Pe,x:Pe.x+ze.dx,y:Pe.y+ze.dy}}),w()},$e=()=>{if(x.size<2)return;const v=or(f.elements,x),V=`lab${e.id}grp${N.current++}`,be=em(f.elements,v,V);be&&(f.elements=be,D(new Set(ar(Ln(be),V))),w())},lt=()=>{const v=Ln(f.elements),V=or(f.elements,x).filter(Le=>qs(v.get(Le)));if(!V.length)return;let be=f.elements;const ke=[];for(const Le of V){const Ie=tm(be,Le);Ie&&(be=Ie.elements,ke.push(...Ie.childIds))}f.elements=be,D(new Set(hi(be,ke))),w()},it=v=>{v.preventDefault();const V=$(v.clientX,v.clientY),be=[...f.elements].sort((ke,Le)=>(Le.zIndex??0)-(ke.zIndex??0)).find(ke=>V.x>=ke.x&&V.x<=ke.x+ke.width&&V.y>=ke.y&&V.y<=ke.y+ke.height);be?x.has(be.id)||xt(be.id,!1):A(),C({x:v.clientX,y:v.clientY,world:V})},Dt=v=>{var Pe;const V=x.size,ke={kind:"item",label:"Paste",shortcut:"âV",disabled:!!!((Pe=z.current)!=null&&Pe.length),onSelect:()=>ot(v)};if(V===0)return[ke,{kind:"item",label:"Select all",shortcut:"âA",disabled:f.elements.length===0,onSelect:Rt}];const Ie=[{kind:"item",label:"Copy",shortcut:"âC",onSelect:tt},ke,{kind:"item",label:"Duplicate",shortcut:"âD",onSelect:vt},{kind:"separator"},{kind:"item",label:"Align",submenu:[{kind:"item",label:"Align left",icon:"align-left",onSelect:()=>dt({horizontal:"left"})},{kind:"item",label:"Align center",icon:"align-horizontal-center",onSelect:()=>dt({horizontal:"center"})},{kind:"item",label:"Align right",icon:"align-right",onSelect:()=>dt({horizontal:"right"})},{kind:"separator"},{kind:"item",label:"Align top",icon:"align-top",onSelect:()=>dt({vertical:"top"})},{kind:"item",label:"Align middle",icon:"align-vertical-center",onSelect:()=>dt({vertical:"middle"})},{kind:"item",label:"Align bottom",icon:"align-bottom",onSelect:()=>dt({vertical:"bottom"})}]},{kind:"separator"}];if(Qe.length>=2?Ie.push({kind:"item",label:"Group",shortcut:"âG",onSelect:$e},{kind:"separator"}):ht&&Ie.push({kind:"item",label:"Ungroup",shortcut:"ââ§G",onSelect:lt},{kind:"separator"}),V===1){const ze=Array.from(x)[0];Ie.push({kind:"item",label:"Bring to front",shortcut:"ââ§]",onSelect:()=>mt(ze,"front")},{kind:"item",label:"Bring forward",shortcut:"â]",onSelect:()=>mt(ze,"forward")},{kind:"item",label:"Send backward",shortcut:"â[",onSelect:()=>mt(ze,"backward")},{kind:"item",label:"Send to back",shortcut:"ââ§[",onSelect:()=>mt(ze,"back")},{kind:"separator"})}return Ie.push({kind:"item",label:"Delete",shortcut:"â«",destructive:!0,onSelect:Nt}),Ie};s.useEffect(()=>{const v=V=>{var Ie,Pe,ze;if(M!=null||(Ie=V.target)!=null&&Ie.isContentEditable)return;const be=(Pe=V.target)==null?void 0:Pe.tagName;if(be==="INPUT"||be==="TEXTAREA"||be==="SELECT")return;const ke=V.metaKey||V.ctrlKey,Le=V.key.toLowerCase();if(V.key==="Escape")V.stopPropagation(),x.size?A():u();
2else if(!ke&&!V.altKey&&(Le==="v"||Le==="t"||Le==="r"||Le==="c"))V.preventDefault(),X(Le==="v"?"select":Le==="t"?"text":Le==="r"?"rectangle":"circle");else if((V.key==="Delete"||V.key==="Backspace")&&x.size>0)V.stopPropagation(),Nt();else if(ke&&Le==="c"&&x.size)V.preventDefault(),tt();else if(ke&&Le==="v"&&((ze=z.current)!=null&&ze.length))V.preventDefault(),ot();else if(ke&&Le==="d"&&x.size)V.preventDefault(),vt();else if(ke&&Le==="a")V.preventDefault(),Rt();else if(ke&&(V.key==="]"||V.key==="}")&&x.size===1)V.preventDefault(),mt(Array.from(x)[0],V.shiftKey?"front":"forward");else if(ke&&(V.key==="["||V.key==="{")&&x.size===1)V.preventDefault(),mt(Array.from(x)[0],V.shiftKey?"back":"backward");else if(ke&&Le==="g"&&!V.shiftKey)V.preventDefault(),$e();else if(ke&&Le==="g"&&V.shiftKey)V.preventDefault(),lt();else if(!ke&&x.size&&(V.key==="ArrowLeft"||V.key==="ArrowRight"||V.key==="ArrowUp"||V.key==="ArrowDown")){V.preventDefault();const et=V.shiftKey?10:1,Ze=V.key==="ArrowLeft"?-et:V.key==="ArrowRight"?et:0,ft=V.key==="ArrowUp"?-et:V.key==="ArrowDown"?et:0;f.elements=f.elements.map(zt=>x.has(zt.id)?{...zt,x:zt.x+Ze,y:zt.y+ft}:zt),w()}};return window.addEventListener("keydown",v,{capture:!0}),()=>window.removeEventListener("keydown",v,{capture:!0})},[x,M]);const en=(v,V)=>{const be=f.elements.reduce((Le,Ie)=>Math.max(Le,Ie.zIndex??0),0)+1;let ke=null;if(T==="text"){const{width:Le,height:Ie}=Qp("",{fontSize:ai.Body,lineHeight:ii.Body,fontFamily:"Inter, ui-sans-serif, system-ui, sans-serif",fontWeight:400,fontStyle:"normal"});ke={id:`lab${e.id}n${N.current++}`,type:"text",x:Math.round(v),y:Math.round(V-Ie/2),width:Le,height:Ie,zIndex:be,text:"",textRole:"Body",fontSize:ai.Body,lineHeight:ii.Body,fontFamily:"Inter, ui-sans-serif, system-ui, sans-serif",fontWeight:400,fontStyle:"normal",listStyle:"none",textSizeMode:"auto",color:"#0f172a",background:"transparent"}}else if(T==="rectangle"||T==="circle"){const Le=T==="circle"?{w:240,h:240}:{w:320,h:200};ke={id:`lab${e.id}n${N.current++}`,type:"shape",shapeKind:T==="circle"?"circle":"rectangle",x:Math.round(v-Le.w/2),y:Math.round(V-Le.h/2),width:Le.w,height:Le.h,zIndex:be,background:"#dbeafe",strokeWidth:0,cornerRadius:T==="circle"?void 0:16}}ke&&(f.elements=[...f.elements,ke],S(ke.id),X("select"),w())},Bt=(v,V,be,ke,Le)=>{const Ie=T==="circle"?"circle":"rectangle",Pe=f.elements.reduce((wt,Gt)=>Math.max(wt,Gt.zIndex??0),0)+1,ze=`lab${e.id}n${N.current++}`,et={id:ze,type:"shape",shapeKind:Ie,x:Math.round(v),y:Math.round(V),width:1,height:1,zIndex:Pe,background:"#dbeafe",strokeWidth:0,cornerRadius:Ie==="circle"?void 0:16};f.elements=[...f.elements,et],S(ze),Z.current={id:ze,startX:v,startY:V,rectLeft:be.left,rectTop:be.top},w();const Ze=de.current,ft=document.body.style.userSelect;document.body.style.userSelect="none";try{Le.setPointerCapture(ke)}catch{}const zt=()=>{window.removeEventListener("pointermove",Vt),window.removeEventListener("pointerup",Tn),window.removeEventListener("pointercancel",Zn),document.body.style.userSelect=ft;try{Le.releasePointerCapture(ke)}catch{}},Et=()=>{const wt=Z.current;Z.current=null;const Gt=wt?f.elements.find(nn=>nn.id===wt.id):null;if(wt&&(!Gt||(Gt.width??0)<8||(Gt.height??0)<8)){const nn=Ie==="circle"?{w:240,h:240}:{w:320,h:200};_e(wt.id,{x:Math.round(wt.startX-nn.w/2),y:Math.round(wt.startY-nn.h/2),width:nn.w,height:nn.h})}X("select")},Vt=wt=>{if(wt.pointerId!==ke)return;if(wt.buttons===0){console.warn("[birtvy-editor] watchdog: draft-shape drag outlived its pointerup â ending gesture"),zt(),Et();return}const Gt=Z.current;if(!Gt)return;const nn=(wt.clientX-Gt.rectLeft)/Ze,gr=(wt.clientY-Gt.rectTop)/Ze;let _t=nn-Gt.startX,Fn=gr-Gt.startY;if(wt.shiftKey){const es=Math.max(Math.abs(_t),Math.abs(Fn));_t=(_t<0?-1:1)*es,Fn=(Fn<0?-1:1)*es}_e(Gt.id,{x:Math.round(Gt.startX+Math.min(0,_t)),y:Math.round(Gt.startY+Math.min(0,Fn)),width:Math.max(1,Math.round(Math.abs(_t))),height:Math.max(1,Math.round(Math.abs(Fn)))})},Tn=wt=>{wt.pointerId===ke&&(zt(),Et())},Zn=wt=>{wt.pointerId===ke&&(zt(),Et())};window.addEventListener("pointermove",Vt),window.addEventListener("pointerup",Tn),window.addEventListener("pointercancel",Zn)},tn=async v=>{const V=await ko(v),be=Im(V.width,V.height),ke=f.elements.reduce((Ie,Pe)=>Math.max(Ie,Pe.zIndex??0),0)+1,Le={id:`lab${e.id}n${N.current++}`,type:"shape",shapeKind:"image",x:be.x,y:be.y,width:be.width,height:be.height,zIndex:ke,background:"transparent",shapeFillMode:"image",f
2illImage:v,imageFit:"cover",strokeWidth:0,cornerRadius:16};f.elements=[...f.elements,Le],S(Le.id),ye(!1),w()},sn=()=>{var V;if(ue){ye(!1);return}const v=(V=_.current)==null?void 0:V.querySelector('[aria-label="Image"]');if(v){const be=v.getBoundingClientRect();U({left:Math.max(8,Math.min(be.left+be.width/2-160,window.innerWidth-328)),bottom:window.innerHeight-be.top+8})}ye(!0)},dn=(v,V)=>{const be=[...f.elements].sort((Pe,ze)=>(ze.zIndex??0)-(Pe.zIndex??0)),ke=be.findIndex(Pe=>Pe.id===v);if(ke<0)return;const[Le]=be.splice(ke,1);be.splice(Math.max(0,Math.min(V,be.length)),0,Le);const Ie=new Map(be.map((Pe,ze)=>[Pe.id,be.length-ze]));f.elements=f.elements.map(Pe=>{const ze=Ie.get(Pe.id);return ze!==void 0&&ze!==Pe.zIndex?{...Pe,zIndex:ze}:Pe}),w()},Jt=v=>({x:v.x,y:v.y,onXChange:V=>_e(v.id,{x:Math.min(Math.max(0,Math.round(V)),Un-v.width)}),onYChange:V=>_e(v.id,{y:Math.min(Math.max(0,Math.round(V)),Xn-v.height)}),onCanvasAlignHorizontal:V=>dt({horizontal:V}),onCanvasAlignVertical:V=>dt({vertical:V})}),Re=v=>{var Le;const V=gi(v.background,"#dbeafe"),be=gi(v.strokeColor,"#93c5fd"),ke=()=>f.elements.find(Ie=>Ie.id===v.id)??v;return{width:v.width,height:v.height,onWidthChange:Ie=>_e(v.id,{width:Math.max(8,Math.round(Ie))}),onHeightChange:Ie=>_e(v.id,{height:Math.max(8,Math.round(Ie))}),fillColor:V.hex,fillOpacity:v.fillGradient?cc(v.fillGradient):V.opacity,onFillColorChange:Ie=>{ke().fillGradient||_e(v.id,{background:ir(Ie,V.opacity),fillGradient:void 0})},onFillOpacityChange:Ie=>{const Pe=ke();if(Pe.fillGradient){const ze=uc(Pe.fillGradient,Ie);_e(v.id,{fillGradient:ze,background:Js(ze,{width:v.width,height:v.height})});return}_e(v.id,{background:ir(V.hex,Ie),fillGradient:void 0})},fillMode:v.fillGradient?v.fillGradient.mode:"solid",fillGradientStops:(Le=v.fillGradient)==null?void 0:Le.stops,onFillModeChange:Ie=>{var Ze,ft,zt,Et;if(Ie==="solid"){const Vt=((zt=(ft=(Ze=v.fillGradient)==null?void 0:Ze.stops)==null?void 0:ft[0])==null?void 0:zt.color)??V.hex;_e(v.id,{fillGradient:void 0,background:ir(Vt,V.opacity)});return}const ze=((Et=ke().fillGradient)==null?void 0:Et.stops)??dc(V.hex),et={mode:Ie,stops:ze};_e(v.id,{fillGradient:et,background:Js(et,{width:v.width,height:v.height})})},onFillGradientChange:Ie=>{var et;const Pe=ke(),ze={...Pe.fillGradient,mode:((et=Pe.fillGradient)==null?void 0:et.mode)??"linear",stops:Ie};_e(v.id,{fillGradient:ze,background:Js(ze,{width:v.width,height:v.height})})},onFillEditOpenChange:Ie=>W(Ie?v.id:null),imageFit:v.imageFit??"cover",onImageFitChange:Ie=>_e(v.id,{imageFit:Ie}),imagePosition:v.imagePosition,onImagePositionChange:Ie=>_e(v.id,{imagePosition:Ie}),strokeStyle:v.strokeStyle??"solid",onStrokeStyleChange:Ie=>_e(v.id,{strokeStyle:Ie}),strokeSize:v.strokeWidth??0,onStrokeSizeChange:Ie=>_e(v.id,{strokeWidth:Math.max(0,Math.round(Ie))}),strokeColor:be.hex,strokeOpacity:be.opacity,onStrokeColorChange:Ie=>_e(v.id,{strokeColor:ir(Ie,be.opacity)}),onStrokeOpacityChange:Ie=>_e(v.id,{strokeColor:ir(be.hex,Ie)}),border:v.border,onBorderChange:Ie=>_e(v.id,{border:Ie}),strokeAlign:v.strokeAlign??"inside",onStrokeAlignChange:Ie=>_e(v.id,{strokeAlign:Ie}),cornerRadius:v.cornerRadius??16,onCornerRadiusChange:Ie=>_e(v.id,{cornerRadius:Math.max(0,Math.round(Ie))}),cornerRadii:v.cornerRadii,onCornersChange:Ie=>{var Pe;return _e(v.id,{...Ie.cornerRadius!==void 0?{cornerRadius:Math.max(0,Math.round(Ie.cornerRadius))}:{},cornerRadii:(Pe=Ie.cornerRadii)==null?void 0:Pe.map(ze=>Math.max(0,Math.round(ze)))})},opacity:v.opacity??100,onOpacityChange:Ie=>_e(v.id,{opacity:Ie}),shadows:v.boxShadows??om(v.boxShadow)??void 0,onShadowsChange:Ie=>_e(v.id,{boxShadows:Ie,boxShadow:im(Ie)}),layerBlur:v.layerBlur??fc(v.filter),onLayerBlurChange:Ie=>_e(v.id,{layerBlur:Ie,filter:hc(v.filter)}),backdropBlur:v.backdropBlur??fc(v.backdropFilter),onBackdropBlurChange:Ie=>_e(v.id,{backdropBlur:Ie,backdropFilter:hc(v.backdropFilter)}),rotation:Ft,onRotationChange:Bn,onDuplicate:()=>bt(v),onDelete:()=>yt(v.id)}},Ne=gi(f.background,"#ffffff"),Be=f.fillGradient?Js(f.fillGradient,{width:Un,height:Xn}):f.background??"#ffffff",ct=v=>{const V=Math.max(0,Math.min(v.cornerRadius??0,Math.floor(Math.min(v.width,v.height)/2)));return r.jsx("div",{style:{position:"absolute",inset:0,boxSizing:"border-box",overflow:V>0?"hidden":"visible",transform:"translateZ(0)",willChange:"transform",isolation:"isolate",..._d({...v,fillImage:void 0,shapeFillMode:"color"}),...zd(v),borderRadius:Ld(v,v.width,v.height,V)},children:r.jsx(jo,{config:i,interactive:!1,responsive:!0})})},De=t.filter(v=>v.baked&&!(n!=null&&n.has(v.id))&&((o==null?void 0:o.has(v.id))??!0)),Ve=De.map(v=>({id:String(v.id),title:"",elements:v.baked.elements,background:v.baked.background,fillGradient:v.baked.fillGradient})),Ct=(v,V)=>{const be=a==null?void 0:a[v.id];return be&&rn(V)?r.jsx(Wi,{config:be,element:V}):null},Mt=f.elements.filter(v=>x.has(v.id)),Te=Mt.length>=2,ut=Mt.map(v=>({id:v.id,x:v.x,y:v.y,width:v.width,height:v.height,rotation:v.rotation})),Tt=Te?Vs(ut,K):null,$t=Te?lc(Mt):null,Pt=v=>{f.elements=f.elements.map(V=>{const be=v.get(V.id);return be?{...V,...be}:V}),w()},un=v=>{if(!v.length)return;const V=new Map;for(const{elementId:be,patch:ke}of v)V.set(be,{...V.get(be),...ke});Pt(V)},bn=(()=>{const v=Lp(Mt,V=>$c(V.fontFamily));return zp(v)?void 0:v})(),wn=()=>
2{if(!P.current){const v=Mt.map(V=>({id:V.id,x:V.x,y:V.y,width:V.width,height:V.height,rotation:V.rotation}));P.current={obb:Vs(v,K),children:v}}return P.current},Nn=(v,V,be,ke)=>{const Le=wn(),{patches:Ie}=Wp(Le.obb,Le.children,v,V,be),Pe=new Map;Ie.forEach((ze,et)=>Pe.set(et,{x:Math.round(ze.x),y:Math.round(ze.y),width:Math.max(1,Math.round(ze.width)),height:Math.max(1,Math.round(ze.height))})),Pt(Pe),ke&&(P.current=null)},Lt=(v,V)=>{const be=wn(),{patches:ke,angle:Le}=si(be.obb,be.children,Math.round(v)),Ie=new Map;ke.forEach((ze,et)=>{const Ze=Math.round(ze.rotation);Ie.set(et,{x:Math.round(ze.x),y:Math.round(ze.y),rotation:Ze===0?void 0:Ze})});const Pe=Math.round(Le);ht&&Ie.set(Qe[0],{...Ie.get(Qe[0]),rotation:Pe===0?void 0:Pe}),Pt(Ie),fe(Pe),V&&(P.current=null)},Ft=Te?K:(he==null?void 0:he.rotation)??0,Do=(v,V,be)=>{if(v.children.length!==V.length)return!1;const{patches:ke}=si(v.obb,v.children,Math.round(oi(be-v.baseAngle))),Le=V[0],Ie=ke.get(Le.id);return Ie?Math.abs(Math.round(Ie.x)-Le.x)<=1&&Math.abs(Math.round(Ie.y)-Le.y)<=1:!1},Bn=v=>{const V=oi(Math.round(v));if(Te){const be=Mt.map(et=>({id:et.id,x:et.x,y:et.y,width:et.width,height:et.height,rotation:et.rotation}));let ke=me.current;if((!ke||ke.key!==Xe||!Do(ke,be,K))&&(ke={key:Xe,obb:Vs(be,K),children:be,baseAngle:K},me.current=ke),V===Math.round(K))return;const{patches:Le,angle:Ie}=si(ke.obb,ke.children,oi(V-ke.baseAngle)),Pe=new Map;Le.forEach((et,Ze)=>{const ft=Math.round(et.rotation);Pe.set(Ze,{x:Math.round(et.x),y:Math.round(et.y),rotation:ft===0?void 0:ft})});const ze=Math.round(Ie);ht&&Pe.set(Qe[0],{...Pe.get(Qe[0]),rotation:ze===0?void 0:ze}),Pt(Pe),fe(ze)}else he&&_e(he.id,{rotation:V===0?void 0:V})},Er=s.useRef(null),pr=v=>{const V=Ln(f.elements),be=uo(V,v);let ke;qs(V.get(be))?(ke=new Set(ar(V,be)),D(new Set(ke))):ke=new Set(R.current);const Le=f.elements.filter(Ie=>ke.has(Ie.id));Er.current={startEls:Le.map(Ie=>({id:Ie.id,x:Ie.x,y:Ie.y})),origin:null,snap:jt(Le)}},To=(v,V)=>{const be=Er.current;if(!be)return;const ke=$(v,V);if(!be.origin){be.origin=ke;return}const{dx:Le,dy:Ie}=be.snap.snapDelta(ke.x-be.origin.x,ke.y-be.origin.y),Pe=new Map;be.startEls.forEach(ze=>Pe.set(ze.id,{x:Math.round(ze.x+Le),y:Math.round(ze.y+Ie)})),Pt(Pe)},mr=()=>{var v;(v=Er.current)==null||v.snap.end(),Er.current=null},[Dn,Rr]=s.useState(null),Yr=s.useRef(Dn);Yr.current=Dn,s.useLayoutEffect(()=>{var Le;if(x.size!==1){Rr(null);return}const v=Array.from(x)[0],V=(Le=F.current)==null?void 0:Le.querySelector(`[data-deckgen-element-id="${v}"]`);if(!V){Rr(null);return}const be=()=>Rr({width:V.offsetWidth,height:V.offsetHeight});be();const ke=new ResizeObserver(be);return ke.observe(V),()=>ke.disconnect()},[x]);const fn=Mt.length===1?{x:Mt[0].x,y:Mt[0].y,width:(Dn==null?void 0:Dn.width)??Mt[0].width,height:(Dn==null?void 0:Dn.height)??Mt[0].height}:null,Kr=fn?{cx:fn.x+fn.width/2,cy:fn.y+fn.height/2,left:fn.x,top:fn.y}:null,Vr=!!Kr&&!we,Rs=s.useRef(Vr);Rs.current=Vr;const qr=fn??($t?{x:$t.x,y:$t.y,width:$t.width,height:$t.height}:null),Jr=s.useRef(()=>{});Jr.current=(v,V)=>{const be=$(v,V),ke=f.elements.filter(Ie=>!x.has(Ie.id)&&be.x>=Ie.x&&be.x<=Ie.x+Ie.width&&be.y>=Ie.y&&be.y<=Ie.y+Ie.height).sort((Ie,Pe)=>(Pe.zIndex??0)-(Ie.zIndex??0))[0],Le=ke?{x:ke.x,y:ke.y,width:ke.width,height:ke.height}:{x:0,y:0,width:Un,height:Xn};pe(Ie=>Ie&&Ie.x===Le.x&&Ie.y===Le.y&&Ie.width===Le.width&&Ie.height===Le.height?Ie:Le)},s.useEffect(()=>{const v=ke=>{ke.key==="Alt"&&ve(!0)},V=ke=>{ke.key==="Alt"&&(ve(!1),pe(null))},be=()=>{ve(!1),pe(null)};return window.addEventListener("keydown",v),window.addEventListener("keyup",V),window.addEventListener("blur",be),()=>{window.removeEventListener("keydown",v),window.removeEventListener("keyup",V),window.removeEventListener("blur",be)}},[]),s.useEffect(()=>{if(!we)return;const v=V=>Jr.current(V.clientX,V.clientY);return window.addEventListener("pointermove",v),()=>window.removeEventListener("pointermove",v)},[we]);const Ms=s.useRef(null),hn=s.useRef(null),Mn=s.useRef(null);s.useEffect(()=>{const v=()=>{Mn.current=null};return window.addEventListener("pointerup",v),window.addEventListener("pointercancel",v),()=>{window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",v)}},[]);const vn=(v,V)=>{var zt,Et;if(!Rs.current){Mn.current=null;return}const be=V.x??v.x,ke=V.y??v.y,Le=V.width??((zt=Yr.current)==null?void 0:zt.width)??v.width,Ie=V.height??((Et=Yr.current)==null?void 0:Et.height)??v.height,Pe=be+Le/2,ze=ke+Ie/2;Mn.current={cx:Pe,cy:ze,left:be,top:ke};const et=1/Math.max(de.current,.01),Ze=Ms.current,ft=hn.current;Ze&&(Ze.style.left=`${Pe}px`,Ze.style.height=`${Math.max(0,ke)}px`,Ze.style.borderLeftWidth=`${et}px`),ft&&(ft.style.top=`${ze}px`,ft.style.width=`${Math.max(0,be)}px`,ft.style.borderTopWidth=`${et}px`)},Zr=h?"top 280ms cubic-bezier(0.22,1,0.36,1), left 280ms cubic-bezier(0.22,1,0.36,1), bottom 280ms cubic-bezier(0.22,1,0.36,1), right 280ms cubic-bezier(0.22,1,0.36,1), border-radius 280ms cubic-bezier(0.22,1,0.36,1)":void 0;return r.jsx(wp,{value:L,children:r.jsx(vp,{children:r.jsxs("div",{className:"fixed z-[3000] flex flex-col overflow-hidden bg-default",style:{to
2p:d,left:d,bottom:d,right:p,borderRadius:d>0?"var(--radius-lg)":0,border:d>0?"1px solid var(--color-border-default)":void 0,transition:Zr},onPointerDown:v=>v.stopPropagation(),onDoubleClick:v=>v.stopPropagation(),children:[r.jsxs("div",{className:"flex h-[56px] shrink-0 items-center gap-[var(--spacing-8)] border-b border-[var(--color-border-default)] bg-default px-[var(--spacing-16)]",children:[r.jsxs("div",{className:"flex shrink-0 items-center gap-[var(--spacing-8)]",children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"close",onClick:u,"aria-label":"Back to canvas",title:"Back to canvas",className:"pointer-events-auto"}),ge]}),r.jsx("div",{className:"min-w-0 flex-1"}),r.jsxs("div",{className:"flex shrink-0 items-center gap-[var(--spacing-8)]",children:[r.jsx(st,{variant:"ghost",size:"sm",leadIcon:"share-2",children:"Share"}),r.jsx(st,{variant:"default",size:"sm",leadIcon:"play",onClick:()=>q(Math.max(0,De.findIndex(v=>v.id===e.id))),children:"Present"}),r.jsx(st,{variant:"ghost",size:"sm",leadIcon:m?"chat-1-fill":"chat-1",onClick:g,"aria-label":"Toggle Agent",children:"Agent"})]})]}),r.jsxs("div",{className:"flex min-h-0 flex-1",children:[ge,r.jsxs("div",{ref:G,className:"relative flex min-w-0 flex-1 items-center justify-center",style:{paddingBottom:Q},onPointerDown:v=>{v.target===v.currentTarget&&A()},children:[r.jsx("div",{style:{width:Un*se,height:Xn*se},className:"relative shrink-0 overflow-hidden rounded-[8px] shadow-[0_24px_80px_rgba(0,0,0,0.12)]",children:r.jsxs("div",{ref:F,onPointerDownCapture:v=>{if(T==="select")return;v.stopPropagation(),v.preventDefault();const V=v.currentTarget.getBoundingClientRect(),be=(v.clientX-V.left)/se,ke=(v.clientY-V.top)/se;T==="text"?en(be,ke):Bt(be,ke,V,v.pointerId,v.currentTarget)},onPointerDown:Ue,onContextMenu:it,style:{position:"absolute",left:0,top:0,width:Un,height:Xn,transform:`scale(${se})`,transformOrigin:"0 0",background:Be,cursor:T==="select"?void 0:"crosshair"},children:[kt(),r.jsx(kp.Provider,{value:de,children:f.elements.filter(v=>v.type!=="group"&&v.type!=="stack").map(v=>{const V=uo(Ge,v.id),be=V!==v.id&&qs(Ge.get(V)),ke=ht&&V===Qe[0],Le=x.size===1&&x.has(v.id),Ie=!be&&x.size>1&&x.has(v.id),Pe=be&&!Le||Ie,ze=i!=null&&rn(v),et=Me!=null&&Me.elementId===v.id?{...v,fontFamily:Me.fontFamily}:v;return r.jsx(Sp,{element:et,scale:se,selectionElevatedZIndex:1e4,selected:ke?!1:x.has(v.id),isInMultiSelection:x.size>1&&x.has(v.id),belongsToGroup:be,deferDragToParent:Pe,hoverContainerId:be&&!ke?V:null,hovered:re===v.id,onHoverChange:Ze=>{le(Ze?v.id:ft=>ft===v.id?null:ft),be&&(Ze?ke||Y(V):Y(ft=>ft===V?null:ft))},onSelect:Ze=>xt(v.id,!!(Ze!=null&&Ze.additive)),onRequestEnter:()=>S(v.id),onDragStart:Ze=>{Ze&&je(v.id),Pe&&pr(v.id)},onAltDragCancel:Oe,lockAxisOnShift:!0,lockAspectRatio:!1,plainMoveCursor:!0,onCanvasDragMove:Pe?(Ze,ft)=>To(Ze,ft):void 0,onCanvasDragEnd:Pe?mr:void 0,snapDragPosition:Pe?void 0:Ee(v),snapResize:ze?void 0:qe(v),onPreview:Ze=>vn(v,Ze),onCommit:(Ze,ft)=>{if(Pe&&!(ft!=null&&ft.resizeDirection)){mr();return}ze?_e(v.id,ft!=null&&ft.resizeDirection?{...Ze,fillImage:void 0,shapeFillMode:"color"}:Ze):_e(v.id,Ae(v,Ze,ft==null?void 0:ft.resizeDirection))},onDelete:()=>yt(v.id),renderOverride:i?Ze=>rn(Ze)?ct(Ze):null:void 0},v.id)})}),J?r.jsx("div",{style:{position:"absolute",left:Math.min(J.x0,J.x1),top:Math.min(J.y0,J.y1),width:Math.abs(J.x1-J.x0),height:Math.abs(J.y1-J.y0),background:"rgba(37,99,235,0.10)",border:`${1/se}px solid var(--color-state-primary, #2563eb)`,zIndex:900002,pointerEvents:"none"}}):null,ie&&!ht&&!J?(()=>{const v=Ge.get(ie);if(!v)return null;const V=ar(Ge,ie).map(ke=>Ge.get(ke)).filter(ke=>!!ke);if(V.length<2)return null;const be=Vs(V.map(ke=>({id:ke.id,x:ke.x,y:ke.y,width:ke.width,height:ke.height,rotation:ke.rotation})),v.rotation??0);return r.jsx("div",{"aria-hidden":!0,style:{position:"absolute",left:be.cx-be.width/2,top:be.cy-be.height/2,width:be.width,height:be.height,transform:be.angle?`rotate(${be.angle}deg)`:void 0,transformOrigin:"center",outline:`${1.5/Math.max(se,.01)}px solid var(--color-state-primary)`,pointerEvents:"none",zIndex:900003}})})():null,Te&&!J&&$t&&Tt?r.jsx(_p,{obb:Tt,scale:se,clientToSlide:$,onResize:Nn,onRotate:Lt}):null,Kr&&!we?(()=>{const v=Mn.current??Kr;return r.jsxs("div",{className:"pointer-events-none absolute inset-0",style:{zIndex:9e5}
2,"aria-hidden":!0,children:[r.jsx("div",{ref:Ms,style:{position:"absolute",left:v.cx,top:0,width:0,height:Math.max(0,v.top),borderLeft:`${1/Math.max(se,.01)}px dashed var(--color-state-primary)`}}),r.jsx("div",{ref:hn,style:{position:"absolute",top:v.cy,left:0,height:0,width:Math.max(0,v.left),borderTop:`${1/Math.max(se,.01)}px dashed var(--color-state-primary)`}})]})})():null,we&&qr&&oe?r.jsx(Op,{a:qr,b:oe,scale:se,zIndex:900001}):null]})}),r.jsx("div",{ref:_,className:"absolute bottom-4 left-1/2 z-[220] -translate-x-1/2",children:r.jsx(Ed,{mode:"slide",activeTool:T,onToolChange:X,onAddImage:sn,toolShortcuts:!0,showCursor:!0})}),ue?r.jsx(ru,{conversationId:k,onPlace:v=>void tn(v),onClose:()=>ye(!1),positionClassName:ee?"fixed z-[1400]":void 0,positionStyle:ee?{left:ee.left,bottom:ee.bottom}:void 0}):null]}),r.jsx("aside",{className:"pointer-events-auto relative z-[210] flex h-full w-[240px] shrink-0 flex-col items-stretch gap-3 overflow-y-auto border-l border-[var(--color-border-default)] bg-default [&_.toolbar-panel-root]:!justify-start",children:Te?r.jsx(Bp,{elements:Mt,onCommit:un,onAlignHorizontal:v=>dt({horizontal:v}),onAlignVertical:v=>dt({vertical:v}),selectionAngle:K,onRotate:Bn,fontId:bn,onFontChange:v=>{li(v),un(Fp(Mt,{fontFamily:mi(v)}))}}):he?he.type==="text"?r.jsx(Ip,{layout:"panel",onDuplicate:()=>bt(he),onDelete:()=>yt(he.id),...Jt(he),rotation:Ft,onRotationChange:Bn,width:he.width,height:he.height,textSizeMode:he.textSizeMode,onTextSizeModeChange:v=>_e(he.id,{textSizeMode:v}),onWidthChange:v=>_e(he.id,{width:Math.max(8,Math.round(v)),textSizeMode:sm(he.textSizeMode)}),onHeightChange:v=>_e(he.id,{height:Math.max(8,Math.round(v)),textSizeMode:rm(he.textSizeMode)}),opacity:he.opacity??100,onOpacityChange:v=>_e(he.id,{opacity:v}),cornerRadius:he.cornerRadius??0,onCornerRadiusChange:v=>_e(he.id,{cornerRadius:Math.max(0,Math.round(v))}),cornerRadii:he.cornerRadii,onCornersChange:v=>{var V;return _e(he.id,{...v.cornerRadius!==void 0?{cornerRadius:Math.max(0,Math.round(v.cornerRadius))}:{},cornerRadii:(V=v.cornerRadii)==null?void 0:V.map(be=>Math.max(0,Math.round(be)))})},textRole:he.textRole??"Body",onTextRoleChange:v=>_e(he.id,{textRole:v,fontSize:ai[v],lineHeight:ii[v]}),selectedFont:$c(he.fontFamily),onFontChange:v=>{He(null),li(v),_e(he.id,{fontFamily:mi(v)})},onFontPreview:v=>{v?(li(v),He({elementId:he.id,fontFamily:mi(v)})):He(null)},fontWeight:he.fontWeight??400,onFontWeightChange:v=>_e(he.id,{fontWeight:v}),fontSize:Math.round(he.fontSize??30),onFontSizeChange:v=>_e(he.id,{fontSize:Math.round(v)}),lineHeight:he.lineHeight??1.3,onLineHeightChange:v=>_e(he.id,{lineHeight:v}),letterSpacing:he.letterSpacing??0,onLetterSpacingChange:v=>_e(he.id,{letterSpacing:v}),align:he.textAlign??"left",onAlignChange:v=>_e(he.id,{textAlign:v}),listStyle:he.listStyle??"none",onListStyleChange:v=>_e(he.id,{listStyle:v,textHtml:void 0}),color:he.color??"#111115",onColorChange:v=>_e(he.id,{color:v}),text:he.text,textHtml:he.textHtml,onRichTextChange:v=>_e(he.id,v),shadows:Cp(he.textShadow),onShadowsChange:v=>_e(he.id,{textShadow:Ep(v)})},he.id):he.shapeKind==="image"?r.jsx(Rp,{layout:"panel",...Jt(he),...Re(he),fillImage:he.fillImage,onFillImageChange:v=>_e(he.id,{fillImage:v,shapeFillMode:"image"})},he.id):he.shapeKind==="circle"?r.jsx(Mp,{layout:"panel",...Jt(he),...Re(he)},he.id):r.jsx(jp,{layout:"panel",...Jt(he),...Re(he)},he.id):r.jsx(Np,{layout:"panel",panelTitle:"Slide",fillColor:Ne.hex,fillOpacity:f.fillGradient?cc(f.fillGradient):Ne.opacity,fillMode:f.fillGradient?f.fillGradient.mode:"solid",fillGradientStops:(Qr=f.fillGradient)==null?void 0:Qr.stops,onFillColorChange:v=>{f.fillGradient||(f.background=ir(v,Ne.opacity),w())},onFillOpacityChange:v=>{f.fillGradient?f.fillGradient=uc(f.fillGradient,v):f.background=ir(Ne.hex,v),w()},onFillModeChange:v=>{var V,be,ke,Le;if(v==="solid"){const Ie=((ke=(be=(V=f.fillGradient)==null?void 0:V.stops)==null?void 0:be[0])==null?void 0:ke.color)??Ne.hex;f.fillGradient=void 0,f.background=ir(Ie,Ne.opacity)}else{const Ie=((Le=f.fillGradient)==null?void 0:Le.stops)??dc(Ne.hex);f.fillGradient={mode:v,stops:Ie}}w()},onFillGradientChange:v=>{var V;f.fillGradient={...f.fillGradient,mode:((V=f.fillGradient)==null?void 0:V.mode)??"linear",stops:v},w()}},"slide")})]}),M!=null?r.jsx(Oi,{slides:Ve,startIndex:M,onClose:()=>q(null),renderOverride:Ct}):null,b?r.jsx(Gp,{x:b.x,y:b.y,items:Dt(b.world),onClose:()=>C(null)}):null]})})})}const Pc="flex items-center rounded-xl border border-[var(--color-border-default)] bg-white shadow-md gap-[var(--spacing-6)] px-[var(--spacing-6)] py-[var(--spacing-6)]",tx=220,xi="rounded-[var(--radius-lg)] px-[var(--spacing-8)] text-sm text-[var(--color-text-default)]",yi={height:32,lineHeight:"32px",fontWeight:500};function nx({value:e,onCommit:t}){const[n,o]=s.useState(!1),[i,a]=s.useState(e),l=s.useRef(null),u=s.useRef(null),[c,d]=s.useState(0);s.useEffect(()=>{n||a(e)},[e,n]),s.useEffect(()=>{var m,g;n&&((m=l.current)==null||m.focus(),(g=l.current)==null||g.select())},[n]);const p=n?i:e;s.useEffect(()=>{u.current&&d(Math.ceil(u.current.getBoundingClientRect().width)+1)},[p]);const h=()=>{t(i.trim()||"Untitled"),o(!1)};return r.jsxs("div",{className:"pointer-events-auto relative",style:{width:c,maxWidth:tx}
2,children:[r.jsx("span",{ref:u,"aria-hidden":!0,className:`pointer-events-none invisible absolute left-0 top-0 whitespace-pre ${xi}`,style:yi,children:p||" "}),n?r.jsx("input",{ref:l,value:i,onChange:m=>a(m.target.value),onBlur:h,onKeyDown:m=>{m.key==="Enter"?(m.preventDefault(),h()):m.key==="Escape"&&(m.preventDefault(),a(e),o(!1))},"aria-label":"Deck name",className:`w-full min-w-0 border-0 bg-transparent outline-none ${xi}`,style:yi}):r.jsx("button",{type:"button",onClick:()=>o(!0),title:e,className:`block w-full min-w-0 cursor-text truncate text-left transition-colors hover:bg-[var(--color-subtle)] ${xi}`,style:yi,children:e})]})}function rx({title:e,onRename:t,onGenerateDeck:n,isAgentOpen:o,onToggleAgent:i,zoomPct:a,zoomControls:l,leftOffset:u,rightOffset:c=0,topOffset:d=12,hideAvatar:p=!1,hideIdentity:h=!1,hideTrailing:m=!1}){const g=Dm(),k="top 280ms cubic-bezier(0.22,1,0.36,1), left 280ms cubic-bezier(0.22,1,0.36,1), right 280ms cubic-bezier(0.22,1,0.36,1)";return r.jsxs(r.Fragment,{children:[h?null:r.jsxs("div",{className:`fixed z-[100] ${Pc}`,style:{top:d,left:u,transition:k},onPointerDown:y=>y.stopPropagation(),children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"home-2",onClick:()=>g("/dashboard"),"aria-label":"Go to dashboard",title:"Go to dashboard"}),r.jsx("span",{className:"w-px shrink-0 bg-[var(--color-border-default)]",style:{height:16}}),r.jsx(nx,{value:e,onCommit:t})]}),m?null:r.jsxs("div",{className:`fixed z-[100] ${Pc}`,style:{top:d,right:12+c,transition:k},onPointerDown:y=>y.stopPropagation(),children:[r.jsx(st,{variant:"secondary",size:"sm",leadIcon:"sparkling-fill",onClick:n,"aria-label":"Generate deck",title:"Generate deck",children:"Generate Deck"}),r.jsx(st,{variant:"ghost",size:"sm",onClick:i,"aria-label":"Toggle Agent",leadIcon:o?"chat-1-fill":"chat-1",children:"Agent"}),r.jsx(Nm,{zoom:a/100,controls:l}),p?null:r.jsx(jm,{})]})]})}function sx({onAddSlide:e,onAddNote:t,onToggleImageMenu:n,onToggleDocumentMenu:o,onAddWebsite:i,leftOffset:a=12}){return r.jsxs("div",{"data-birtvy-rail":!0,onPointerDown:l=>l.stopPropagation(),className:"fixed top-1/2 z-30 flex -translate-y-1/2 flex-col gap-[var(--spacing-8)] rounded-[20px] border border-[var(--color-border-default)] bg-default p-[var(--spacing-8)] shadow-[var(--shadow-modal-md)]",style:{left:a,transition:"left 280ms cubic-bezier(0.22,1,0.36,1)"},children:[r.jsx(ur,{content:"Add slide",side:"right",sideOffset:12,className:"z-[1500]",children:r.jsx(st,{variant:"ghost",size:"icon-lg",leadIcon:"canvas","aria-label":"Add slide",onClick:e})}),r.jsx(ur,{content:"Note",side:"right",sideOffset:12,className:"z-[1500]",children:r.jsx(st,{variant:"ghost",size:"icon-lg",leadIcon:"sticky-note","aria-label":"Note",onClick:t})}),r.jsx(ur,{content:"Image",side:"right",sideOffset:12,className:"z-[1500]",children:r.jsx(st,{variant:"ghost",size:"icon-lg",leadIcon:"image","aria-label":"Image",onClick:n})}),r.jsx(ur,{content:"Document",side:"right",sideOffset:12,className:"z-[1500]",children:r.jsx(st,{variant:"ghost",size:"icon-lg",leadIcon:"file-text","aria-label":"Document",onClick:o})}),r.jsx(ur,{content:"Website",side:"right",sideOffset:12,className:"z-[1500]",children:r.jsx(st,{variant:"ghost",size:"icon-lg",leadIcon:"global","aria-label":"Website",onClick:i})})]})}const bi={duration:.6,ease:[.22,1,.36,1]},us=280,fs="cubic-bezier(0.22, 1, 0.36, 1)",ox="0px 24px 80px 0px rgba(0,0,0,0.10)";function Lc({card:e,readOnly:t=!1,onContentChange:n,interactive:o=!0}){const i=s.useCallback(u=>n(u),[n]),a=t?void 0:i,l=Wd(e.content,a,!!a&&o);return r.jsxs("div",{className:fo.docProse,style:{paddingTop:Sr.padTop,paddingLeft:Sr.padX,paddingRight:Sr.padX,paddingBottom:Sr.padTop},children:[a&&l&&o?r.jsx($m,{editor:l,buttons:Pm}):null,r.jsx(ea,{editor:l})]})}function ix({doc:e,origin:t,onClose:n,onContentChange:o,stageInsetEdge:i=0,stageInsetRight:a=0,stageInsetAnimated:l=!0,isAgentOpen:u=!1,onToggleAgent:c}){const[d,p]=s.useState("opening"),h=e;s.useEffect(()=>{p("open")},[]);const[m,g]=s.useState({w:0,h:0});s.useEffect(()=>{const X=()=>g({w:window.innerWidth,h:window.innerHeight});return X(),window.addEventListener("resize",X),()=>window.removeEventListener("resize",X)},[]),s.useEffect(()=>{const X=W=>{W.key==="Escape"&&(W.preventDefault(),n())};document.addEventListener("keydown",X);const L=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",X),document.body.style.overflow=L}},[n]);const y=(m.w-a)/2+i/2,f=l?`top ${us}ms ${fs}, left ${us}ms ${fs}, bottom ${us}ms ${fs}, right ${us}ms ${fs}, border-radius ${us}ms ${fs}`:void 0,I=y-sr.width/2,w=t,x=w?w.height/sr.height:.3,D=w?w.x+w.width/2-y:0,R=w?w.y+w.height/2-sr.height*x/2-i:0,j={scale:x,x:D,y:R,opacity:1},S={scale:1,x:0,y:0,opacity:1},A={...j,opacity:0}
2,O={...bi,opacity:{duration:.2,delay:.38}},T=()=>{p("opening"),n()};return m.w===0?null:r.jsxs(r.Fragment,{children:[r.jsx(Kn.div,{className:"fixed inset-0 z-[1300] bg-white",style:{top:i,left:i,bottom:i,right:a,borderRadius:i>0?"var(--radius-lg)":0,boxShadow:i>0?"inset 0 0 0 1px var(--color-border-default)":void 0,transition:f},initial:{opacity:1},animate:{opacity:1},transition:{duration:0}}),r.jsxs("div",{className:"pointer-events-none fixed left-0 top-0 z-[1302] flex items-center justify-between p-5",style:{right:a,transition:f},children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"close",onClick:n,"aria-label":"Back to canvas",title:"Back to canvas",className:"pointer-events-auto",style:{transform:"translateX(0)",opacity:1,transition:"transform 150ms ease-in-out, opacity 150ms ease-in-out"}}),c?r.jsx(st,{variant:"ghost",size:"sm",leadIcon:u?"chat-1-fill":"chat-1",onClick:c,"aria-label":"Toggle Agent",className:"pointer-events-auto",children:"Agent"}):null]}),d==="open"?r.jsx("div",{className:"fixed inset-0 z-[1301] overflow-y-auto",style:{to
2p:i,left:i,bottom:i,right:a,transition:f},children:r.jsx("div",{className:"flex justify-center",style:{minHeight:"100%"},children:r.jsx("div",{style:{width:sr.width},children:r.jsx(Lc,{card:h,onContentChange:o,interactive:!0})})})}):r.jsxs(r.Fragment,{children:[r.jsx(Kn.div,{"aria-hidden":!0,className:"pointer-events-none fixed z-[1301]",style:{left:I,top:i,width:sr.width,height:sr.height,borderRadius:16,transformOrigin:"top center",boxShadow:ox,willChange:"transform, opacity"},initial:{...d==="closing"?S:j,opacity:d==="closing"?0:1},animate:{...d==="closing"?j:S,opacity:d==="closing"?1:0},transition:bi}),r.jsx(Kn.div,{className:"fixed z-[1301] overflow-hidden bg-white",style:{left:I,top:i,width:sr.width,height:sr.height,borderRadius:16,transformOrigin:"top center",willChange:"transform"},initial:d==="closing"?S:j,animate:d==="closing"?A:S,transition:d==="closing"?O:bi,onAnimationComplete:()=>{d==="opening"?p("open"):d==="closing"&&T()},children:r.jsx(Lc,{card:h,onContentChange:o,interactive:!1})})]})]})}const ax=280,lx=1200,cx=/\.(md|markdown|mdx|txt|text|csv|json)$/i,dx=512*1024,ux=8*1024*1024,ou="âbirtvy-canvas-clipboard:v1",fx=e=>e.type.startsWith("image/"),hx=e=>e.size>0&&(e.type.startsWith("text/")||e.type==="application/json"||cx.test(e.name));function Hi(e){const t=Array.from(e);return t.includes("Files")||t.includes("text/uri-list")||t.includes("text/html")||t.includes("text/plain")}function px(e){for(const t of e.split(/\r?\n/)){const n=t.trim();if(n&&!n.startsWith("#"))return n}return""}function mx(e){const t=/<!--\s*StartFragment\s*-->([\s\S]*?)<!--\s*EndFragment\s*-->/i.exec(e);return(t?t[1]:e).trim()}const gx=/(^|\n)[ \t]{0,3}(#{1,6}[ \t]|[-*+][ \t]|\d+[.)][ \t]|>[ \t]|```|\|)/,xx=/(\*\*|~~|`[^`]+`|\[[^\]]+\]\([^)]+\)|<u>)/;function iu(e){const t=e.trim();return gx.test(t)||/\n[ \t]*\n/.test(t)}function yx(e){return iu(e)||xx.test(e)}function bx(e,t){return t&&!Gr(t)&&yx(t)?t.trim():e.trim()}function wx(e,t){const n=bx(e,t);if(Gr(n))return null;const o=(Gr(e)?n:e).trim().length;return o<=ax?{kind:"note",content:n}:o>=lx?{kind:"doc",content:n}:{kind:iu(n)?"doc":"note",content:n}}function au(e){const t=e.files&&e.files.length>0?Array.from(e.files):Array.from(e.items??[]).filter(u=>u.kind==="file").map(u=>u.getAsFile()).filter(u=>!!u);if(t.length>0){const u=[];for(const c of t)fx(c)?u.push({kind:"image-file",file:c}):hx(c)&&u.push({kind:"text-file",file:c});return u}const n=e.getData("text/plain")??"",o=e.getData("text/html")||null,i=px(e.getData("text/uri-list")??""),a=i&&yc(i)?i:yc(n)?n.trim():"";if(a)return[{kind:"image-url",url:a}];const l=i&&bc(i)?i:bc(n)?n.trim():"";return l?[{kind:"web-url",url:l}]:!Gr(n)||o&&!Gr(o)?[{kind:"text",plain:n,html:o}]:[]}async function vx(e){const{default:t}=await ta(async()=>{const{default:i}=await import("./turndown.browser.es-DqC8V-Us.js");return{default:i}},[]),n=new t({headingStyle:"atx",bulletListMarker:"-",emDelimiter:"*",strongDelimiter:"**",codeBlockStyle:"fenced",hr:"---",linkStyle:"inlined"}),o=new Set(["SCRIPT","STYLE","NOSCRIPT","IFRAME","SVG","FORM"]);return n.remove(i=>o.has(i.nodeName.toUpperCase())),n.addRule("strikethrough",{filter:["del","s"],replacement:i=>i.trim()?`~~${i}~~`:i}),n.addRule("checkbox",{filter:i=>i.nodeName==="INPUT"&&["checkbox","radio"].includes((i.getAttribute("type")??"").toLowerCase()),replacement:(i,a)=>{const l=a;return l.checked||l.hasAttribute("checked")?"[x] ":"[ ] "}}),n.addRule("emptyLink",{filter:i=>{var a;return i.nodeName==="A"&&!((a=i.textContent)!=null&&a.trim())&&!i.querySelector("img")},replacement:()=>""}),n.addRule("image",{filter:"img",replacement:(i,a)=>{const l=a,u=l.getAttribute("src")||l.getAttribute("data-src")||"";return!u||u.startsWith("data:image/gif")?"":`![${(l.getAttribute("alt")??"").replace(/[[\]]/g,"")}](${u})`}}),n.turndown(mx(e)).trim()}const zc=64;function kx({src:e,aspect:t,onClose:n}){const[o,i]=s.useState({w:0,h:0});if(s.useEffect(()=>{const m=()=>i({w:window.innerWidth,h:window.innerHeight});return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),s.useEffect(()=>{const m=k=>{k.key==="Escape"&&(k.preventDefault(),n())};document.addEventListener("keydown",m);const g=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=g}},[n]),o.w===0)return null;const a=t>0?t:16/9,l=Math.max(1,o.w-zc*2),u=Math.max(1,o.h-zc*2);let c=l,d=c/a;d>u&&(d=u,c=d*a);const p=o.w/2-c/2,h=o.h/2-d/2;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[1300] bg-white",onPointerDown:n}),r.jsx("div",{className:"pointer-events-none fixed left-0 top-0 z-[1302] flex items-center p-5",children:r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"close",onClick:n,"aria-label":"Back to canvas",title:"Back to canvas",className:"pointer-events-auto"})}),r.jsx("div",{className:"fixed z-[1301] overflow-hidden bg-white",style:{left:p,top:h,width:c,height:d,borderRadius:16},onPointerDown:m=>m.stopPropagation(),children:r.jsx("img",{src:e,alt:"",draggable:!1,
2className:"h-full w-full select-none object-contain"})})]})}const Sx=64,Ix=24,Cx=32;function Ex({cardId:e,src:t,alt:n}){const o=s.useRef(null);return s.useEffect(()=>{let i=0;const a=()=>{const l=o.current;if(!l)return;const u=l.scrollHeight-l.clientHeight;u>0?l.scrollTop=dm(e)*u:i++<60&&requestAnimationFrame(a)};a()},[e]),s.useEffect(()=>{const i=o.current;if(!i)return;const a=()=>{const l=i.scrollHeight-i.clientHeight;um(e,l>0?i.scrollTop/l:0)};return i.addEventListener("scroll",a,{passive:!0}),()=>i.removeEventListener("scroll",a)},[e]),r.jsx("div",{ref:o,"data-webcard-scroll":!0,className:"h-full w-full overflow-y-auto overscroll-contain bg-white",children:r.jsx("img",{src:t,alt:n,draggable:!1,className:"block w-full select-none"})})}function Rx({web:e,onClose:t}){var h;const[n,o]=s.useState({w:0,h:0});if(s.useEffect(()=>{const m=()=>o({w:window.innerWidth,h:window.innerHeight});return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),s.useEffect(()=>{const m=k=>{k.key==="Escape"&&(k.preventDefault(),t())};document.addEventListener("keydown",m);const g=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",m),document.body.style.overflow=g}},[t]),n.w===0||!e.screenshotUrl&&!e.post)return null;const i=((h=e.title)==null?void 0:h.trim())||Ji(e.url),a=e.width>0&&e.height>0?e.width/e.height:16/9,l=Sx,u=Math.max(1,n.w-Cx*2);let c=Math.max(1,n.h-l-Ix),d=c*a;d>u&&(d=u,c=d/a);const p=n.w/2-d/2;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[1300] bg-white",onPointerDown:t}),r.jsxs("div",{className:"pointer-events-none fixed left-0 right-0 top-0 z-[1302] flex items-center justify-between gap-3 p-5",children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"close",onClick:t,"aria-label":"Back to canvas",title:"Back to canvas",className:"pointer-events-auto"}),r.jsx("div",{className:"pointer-events-none absolute left-1/2 top-1/2 flex max-w-[40%] -translate-x-1/2 -translate-y-1/2 justify-center",children:r.jsx("span",{className:"truncate text-sm font-medium text-[var(--color-text-default)]",title:e.url,children:i})}),r.jsx(st,{variant:"ghost",size:"sm",tailIcon:"arrow-right-up","aria-label":e.post?"Open post":"Open site",onClick:()=>window.open(e.url,"_blank","noopener,noreferrer"),className:"pointer-events-auto",children:e.post?"Open post":"Open site"})]}),r.jsx("div",{className:`fixed z-[1301] overflow-hidden bg-white ${e.post?"":"border border-[var(--color-border-default)]"}`,style:{left:p,top:l,width:d,height:c,borderRadius:16},onPointerDown:m=>m.stopPropagation(),children:e.post?r.jsx("div",{style:{width:e.width,height:e.height,transform:`scale(${d/e.width})`,transformOrigin:"top left"},children:r.jsx(cm,{web:e,autoResize:!1})}):e.frameable?r.jsx("div",{className:"relative h-full w-full bg-white",children:r.jsx("iframe",{src:e.url,title:i,className:"h-full w-full border-0",sandbox:"allow-scripts allow-same-origin allow-popups allow-forms allow-popups-to-escape-sandbox"})}):r.jsx(Ex,{cardId:e.id,src:e.screenshotUrl??"",alt:i})})]})}const fr=8,Mx=.25,jx=.21,Nx=9,_c=.2,Dx=5,gs=.01;function Tx(){if(typeof window>"u")return"dom";try{const e=new URLSearchParams(window.location.search).get("renderer");if(e==="webgl"||e==="dom")return e}catch{}return"webgl"}const qn=(e,t,n)=>Math.max(t,Math.min(n,e)),eo=new Set,to="transform 220ms cubic-bezier(0.22, 1, 0.36, 1)",Ax=12,Cr=(e,t)=>{if(!e.has(t))return e;const n=new Set(e);return n.delete(t),n};function $x({store:e,setHoveredWebId:t,setViewerWebId:n}){const{websRef:o,setWebs:i,setSelectedIds:a,setSelectedDocIds:l,setSelectedNoteIds:u,setSelectedImageIds:c,setSelectedWebIds:d,idRef:p,requestSave:h,placeInView:m,bringToFront:g}=e,k=s.useCallback((R,j)=>{const{x:S,y:A}=m(cr,j),O=p.current++,T={id:O,x:S,y:A,width:cr.width,height:cr.height,url:R,status:"loading",sourceImages:[]};return i(X=>[...X,T]),h(),O},[e]),y=s.useCallback(R=>{const{x:j,y:S}=m(cr,R),A=p.current++,O={id:A,x:j,y:S,width:cr.width,height:cr.height,url:"",status:"empty",sourceImages:[]};return i(T=>[...T,O]),a(new Set),l(new Set),u(new Set),c(new Set),d(new Set),h(),A},[e]),f=s.useCallback((R,j)=>{i(S=>S.map(A=>A.id===R?{...A,...j}:A)),h()},[e]),I=s.useCallback((R,j)=>{i(S=>S.map(A=>
2A.id===R&&Math.abs(A.height-j)>1?{...A,height:j}:A)),h()},[e]),w=s.useCallback(R=>{i(j=>j.filter(S=>S.id!==R)),d(j=>Cr(j,R)),t(j=>j===R?null:j),n(j=>j===R?null:j),h()},[e,t,n]),x=s.useCallback(R=>{const j=o.current.find(O=>O.id===R);if(!j)return;const S=p.current++,A={...j,id:S,x:j.x+64,y:j.y+64};i(O=>[...O,A]),d(new Set([S])),g([`web:${S}`]),h()},[e]),D=s.useCallback((R,j)=>{const S=Ad(R,j,()=>p.current++);if(S.length===0)return;const A=Tm(S),O=m({width:A.width+zn*2,height:A.height+zn*2},{x:A.x+A.width/2,y:A.y+A.height/2}),T=O.x+zn-A.x,X=O.y+zn-A.y,L=T||X?S.map(W=>({...W,x:Math.round(W.x+T),y:Math.round(W.y+X)})):S;o.current=[...o.current,...L],i(W=>[...W,...L]),h()},[e]);return{createWebCard:k,addEmptyWeb:y,updateWeb:f,updateWebHeight:I,deleteWeb:w,duplicateWeb:x,addBrandTiles:D}}const Px=400,Lx=200,Oc=24,zx=200,_x=7;function Ox(e){const t=s.useRef(e);t.current=e;const n=s.useCallback((d,p)=>{const{conversationId:h,updateWeb:m}=t.current;if(!h)return;if(m(d,{status:"loading",url:p}),fm(p)){(async()=>{var k;try{const y=await fetch(`/conversation-social-extract-api/${encodeURIComponent(h)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p})});if(!y.ok)throw new Error(`social-extract ${y.status}`);const f=await y.json(),I=((k=f.text)==null?void 0:k.trim())??"",w=f.images??[],x=f.videos??[];if(!I&&w.length===0&&x.length===0)throw new Error("empty post");m(d,{status:"ready",title:f.title??"",sourceImages:w,post:{platform:f.platform??"social",author:f.author,authorAvatar:f.authorAvatar,text:I,images:w,videos:x},width:pc.width,height:pc.height,url:f.url??p})}catch{m(d,{status:"error"})}})();return}const g=(async()=>{try{const k=await fetch(`/conversation-web-preview-api/${encodeURIComponent(h)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p})});if(!k.ok)throw new Error(`web-preview ${k.status}`);const y=await k.json();if(!y.screenshotUrl)throw new Error("no screenshot");return m(d,{status:"ready",screenshotUrl:y.screenshotUrl,title:y.title??"",sourceImages:y.images??[],frameable:y.frameable??!1,url:y.url??p}),y.screenshotUrl}catch{m(d,{status:"error"});return}})();(async()=>{var k;try{const y=await fetch(`/conversation-web-style-api/${encodeURIComponent(h)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:p})});if(!y.ok)return;const f=await y.json();if(!f||!((k=f.palette)!=null&&k.length||Object.keys(f.roles??{}).length))return;m(d,{brandStyle:f});const I=await Ec(f,await g);I!==f&&m(d,{brandStyle:I})}catch{}})()},[]),o=s.useCallback((d,p)=>{const{conversationId:h,createWebCard:m}=t.current;if(!h)return null;const g=Zs(d),k=m(g,p);return n(k,g),k},[n]),i=s.useCallback((d,p)=>{n(d,Zs(p))},[n]),a=s.useCallback(async d=>{var g,k;const{conversationId:p,addNoteAt:h,addDocAt:m}=t.current;if(!p)return!1;try{const y=await fetch(`/conversation-social-extract-api/${encodeURIComponent(p)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:d.url})});if(!y.ok)return!1;const f=await y.json(),I=d.post?(g=f.text)==null?void 0:g.trim():hm(f.text??"");if(!I)return!1;const w=I.split(` 3`).filter(x=>x.trim()!=="").length;return I.length>zx||w>_x?(await m(I,{x:d.x+d.width+40+En/2,y:d.y+Cn/2},((k=d.title)==null?void 0:k.trim())||Ji(d.url)),"doc"):(h(I,{x:d.x+d.width+40+214,y:d.y+214}),"note")}catch{return!1}},[]),l=s.useCallback(async d=>{const{conversationId:p,addImageAt:h,findSpaceFor:m}=t.current;if(!p)return 0;const g=async T=>{try{const X=await fetch(`/conversation-images-api/${encodeURIComponent(p)}/from-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:T})});if(!X.ok)return null;const L=await X.json();if(!L.url)return null;const W=await wc(L.url);return W?{url:L.url,width:W.width,height:W.height}:null}catch{return null}};let k;if(d.post){const T=[...new Set(d.post.images??[])].slice(0,Oc);if(T.length===0)return 0;k=(await Promise.all(T.map(g))).filter(L=>L!=null)}else{const T=[...new Set((d.sourceImages??[]).map(Cm))];if(T.length===0)return 0;const L=(await Promise.all(T.map(async H=>({url:H,dim:await wc(H)})))).filter(H=>H.dim!=null&&Math.max(H.dim.width,H.dim.height)>=Px&&Math.min(H.dim.width,H.dim.height)>=Lx).slice(0,Oc);if(L.length===0)return 0;k=(await Promise.all(L.map(H=>g(H.url)))).filter(H=>H!=null)}if(k.length===0)return 0;const y=2400,f=[];let I=0,w=0,x=0,D=0;for(const T of k){const X=Wr(T.width,T.height);I>0&&I+X.width>y&&(I=0,w+=x+ms,x=0),f.push({img:T,box:X,dx:I,dy:w}),I+=X.width+ms,x=Math.max(x,X.height),D=Math.max(D,I-ms)}const R=w+x,j={x:d.x+d.width+zn+D/2,y:d.y+R/2},S=m({width:D+zn*2,height:R+zn*2},j),A=S.x+zn,O=S.y+zn;for(const{img:T,box:X,dx:L,dy:W}of f)h(T.url,T.width,T.height,{x:A+L+X.width/2,y:O+W+X.height/2},d.url);return k.length},[]),u=s.useCallback(async d=>{var y;const{conversationId:p,addBrandTiles:h,updateWeb:m}=t.current;
3if(!p)return!1;let g=d.brandStyle;if(!g)try{const f=await fetch(`/conversation-web-style-api/${encodeURIComponent(p)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:d.url})});f.ok&&(g=await f.json(),g&&m(d.id,{brandStyle:g}))}catch{}if(!g||!((y=g.palette)!=null&&y.length)&&Object.keys(g.roles??{}).length===0)return!1;const k=await Ec(g,d.screenshotUrl);return k!==g&&m(d.id,{brandStyle:k}),h({x:d.x,y:d.y+d.height+zn},k),!0},[]),c=s.useCallback(async d=>{const{conversationId:p,getWebs:h}=t.current;if(!p)return;const m=Zs(d);if(h().some(x=>x.kind!=="swatch"&&x.kind!=="fonts"&&x.kind!=="logo"&&Zs(x.url)===m))return;const k=o(m);if(k==null)return;const y=Date.now(),I=await new Promise(x=>{const D=()=>{const R=t.current.getWebs().find(j=>j.id===k);if(!R)return x(null);if(R.status==="ready")return x(R);if(R.status==="error"||Date.now()-y>3e4)return x(null);window.setTimeout(D,250)};D()});if(!I)return;await l(I);const w=t.current.getWebs().find(x=>x.id===k);w&&await u(w)},[o,l,u]);return{placeWebFromUrl:o,ingestUrlIntoCard:i,extractImagesFromWeb:l,extractTextFromWeb:a,extractStyleFromWeb:u,ingestWebsiteToCanvas:c}}function Bx({actions:e}){const[t,n]=s.useState(null);return r.jsx(r.Fragment,{children:e.map(o=>r.jsxs("div",{className:"relative",children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:o.icon,"aria-label":o.label,title:o.label,disabled:o.disabled,onClick:i=>{i.stopPropagation(),o.menu?n(a=>a===o.key?null:o.key):o.onClick()}}),o.menu&&t===o.key?r.jsx("div",{className:"absolute left-1/2 top-full z-[1600] mt-2 flex w-max -translate-x-1/2 flex-col rounded-[14px] border border-[var(--color-border-default)] bg-[var(--color-default)] p-1 shadow-[var(--shadow-modal-md)]",children:o.menu.map(i=>r.jsx("button",{type:"button",className:"rounded-[10px] px-3 py-2 text-left text-[14px] font-medium text-[var(--color-text-default)] transition-colors hover:bg-[var(--color-subtle)]",onClick:a=>{a.stopPropagation(),n(null),i.onClick()},children:i.label},i.key))}):null]},o.key))})}function lu({itemHeight:e,actions:t,extraLeading:n,topSlot:o,shape:i="card",onPointerEnter:a,onPointerLeave:l}){const u=r.jsxs(r.Fragment,{children:[n,r.jsx(Bx,{actions:t})]}),d=`w-max ${i==="pill"?"rounded-full":"rounded-[18px]"} border border-[var(--color-border-default)] bg-[var(--color-default)] p-[var(--spacing-6)] shadow-[var(--shadow-modal-md)]`;return r.jsx("div",{className:"pointer-events-auto absolute",style:{left:"50%",top:e,zIndex:1005},onPointerDown:p=>p.stopPropagation(),onPointerEnter:a,onPointerLeave:l,children:r.jsx("div",{style:{transform:"translateX(-50%) scale(var(--sel-scale, 1))",transformOrigin:"top center",paddingTop:i==="pill"?40:12},children:o?r.jsx("div",{className:"w-max",children:o}):r.jsx("div",{className:`flex items-center gap-[var(--spacing-6)] whitespace-nowrap ${d}`,children:u})})})}const po=20,Fx=12,wi=po*3;function Gx({x:e,y:t,w:n=Ke,h:o=Je,sides:i=["right"],portsFor:a,onPortDown:l,onPointerEnter:u,onPointerLeave:c}){const d=e+n/2,p=t+o/2,h={top:{left:d,top:t},right:{left:e+n,top:p},bottom:{left:d,top:t+o},left:{left:e,top:p}},m=Array.from(new Set(["right",...i])),g=m.join(","),k=s.useRef(null);return s.useEffect(()=>{var x;if(!l||(x=window.matchMedia)!=null&&x.call(window,"(prefers-reduced-motion: reduce)").matches)return;const y=k.current;if(!y)return;const f=wi/2,I=po+2,w=D=>{y.querySelectorAll("[data-port-hit]").forEach(j=>{const S=j.firstElementChild;if(!S)return;const A=j.getBoundingClientRect(),O=D.clientX-(A.left+A.width/2),T=D.clientY-(A.top+A.height/2),X=Math.hypot(O,T);if(X>f||X===0){S.style.transform="translate(0px, 0px)";return}const L=Math.min(X*.45,I);S.style.transform=`translate(${O/X*L}px, ${T/X*L}px)`})};return window.addEventListener("pointermove",w),()=>{window.removeEventListener("pointermove",w),y.querySelectorAll("[data-port-hit] > *").forEach(D=>{D.style.transform="translate(0px, 0px)"})}},[l,g]),r.jsx("div",{ref:k,"data-ports-for":a,style:{position:"absolute",left:0,top:0,pointerEvents:"none"},children:m.map(y=>{const f=h[y];return r.jsx("div",{"data-port-hit":!0,onPointerDown:l,onPointerEnter:u,onPointerLeave:c,style:{position:"absolute",left:f.left,top:f.top,width:wi,height:wi,display:"flex",alignItems:"center",justifyContent:"center",transform:"translate(-50%, -50%) scale(var(--port-scale, 1))",transformOrigin:"center",pointerEvents:l?"auto":"none",cursor:l?"crosshair":void 0,zIndex:1001},children:r.jsx("div",{style:{width:po,height:po,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 2px 8px rgba(9,9,11,0.2)",display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",boxSizing:"border-box",pointerEvents:"none",transition:"transform 120ms cubic-bezier(0.22, 1, 0.36, 1)"},children:r.jsx(At,{name:"add",size:Fx,className:"text-white"})})},y)})})}const Bc=24;function Wx({x:e,y:t,w:n,h:o,portsFor:i,onHandleDown:a}){const l=[{corner:"nw",left:e,top:t,cursor:"nwse-resize"},{corner:"ne",left:e+n,top:t,cursor:"nesw-resize"},{corner:"sw",left:e,top:t+o,cursor:"nesw-resize"},{corner:"se",left:e+n,top:t+o,cursor:"nwse-resize"}];return r.jsx("div",{"data-ports-for":i,style:{position:"absolute",left:0,top:0,pointerEvents:"none"},children:l.map(u=>r.jsx("div",{onPointerDown:c=>a(u.corner,c),style:{position:"absolute",left:u.left,top:u.top,width:Bc,height:Bc,transform:"translate(-50%, -50%) scale(var(--port-scale, 1))",transformOrigin:"center",pointerEvents:"auto",cursor:u.cursor,zIndex:1002}},u.corner))})}const cu=s.createContext(null);function Rn(){const e=s.useContext(cu);if(!e)throw new Error("birtvy: a canvas render layer was mounted outside BirtvyCanvasContext");return e}function xs({kind:e,keyPrefix:t,items:n,hoveredId:o,selectedIds:i,suppressed:a=!1}){const{chromeVisible:l,singleSelection:u,portSidesFor:c,startWire:d,hoverKeep:p,hoverClearSoon:h}=Rn();if(a||!l)return null;const m=new Set;return o!=null&&m.add(o),u&&i.size===1&&m.add([...i][0]),m.size===0?null:r.jsx(r.Fragment,{children:[...m].map(g=>{const k=n.find(y=>y.id===g);return k?r.jsx(Gx,{x:k.x,y:k.y,w:k.width,h:k.height,sides:c({kind:e,id:g}),portsFor:`${e}:${g}`,onPortDown:y=>d({kind:e,id:g},y),onPointerEnter:p,onPointerLeave:h},`${t}${g}`):null})})}function Hx({kind:e,id:t,x:n,y:o,width:i,itemHeight:a,actions:l,extraLeading:u,topSlot:c}){const{hoverKeep:d,hoverClearSoon:p}=Rn();return r.jsx("div",{"data-ports-for":`${e}:${t}`,style:{position:"absolute",left:n,top:o,width:i,pointerEvents:"none"},children:r.jsx(lu,{itemHeight:a,actions:l,onPointerEnter:d,onPointerLeave:p,topSlot:c,extraLeading:u})})}function Ux(){const{chromeVisible:e,demoChrome:t,demoBusyKinds:n,deleteWeb:o,duplicateWeb:i,handleWebExtractImages:a,handleWebExtractStyle:l,handleWebExtractText:u,hover:c,hoverClearSoon:d,hoverKeep:p,hoveredWebId:h,ingestUrlIntoCard:m,onWebPointerDown:g,selectForContext:k,selectedWebIds:y,setViewerWebId:f,singleSelection:I,updateWebHe
3ight:w,webBusy:x,webResult:D,webs:R,zOrder:j}=Rn();return r.jsxs(r.Fragment,{children:[R.map(S=>{var O;const A=S.kind==="swatch"||S.kind==="fonts"||S.kind==="logo";return r.jsxs(s.Fragment,{children:[r.jsx(pm,{web:S,z:j[`web:${S.id}`],selected:!t&&y.has(S.id),onPointerDown:T=>g(S.id,T),onPointerEnter:()=>c("web",S.id),onPointerLeave:d,onOpen:()=>f(S.id),onSubmitUrl:(T,X)=>m(T,X),onHeightChange:T=>w(S.id,T),animateIn:t}),!A&&!t&&S.status!=="empty"?r.jsx("div",{"data-web-label":S.id,style:{position:"absolute",left:S.x,top:S.y,pointerEvents:"none"},children:r.jsx("div",{style:{transform:"translateY(calc(-100% - 8px))"},title:S.url,children:r.jsx("span",{onPointerDown:T=>{T.stopPropagation(),k("web",S.id)},className:"pointer-events-auto block cursor-pointer overflow-hidden text-ellipsis whitespace-nowrap text-base font-medium leading-tight text-[var(--color-text-default)]",style:{maxWidth:280},children:((O=S.title)==null?void 0:O.trim())||Ji(S.url)})})}):null]},S.id)}),t?null:r.jsx(xs,{kind:"web",keyPrefix:"webports",items:R,hoveredId:h,selectedIds:y}),(()=>{if(!e)return null;const S=h??(I&&y.size===1?[...y][0]:null);if(S==null)return null;const A=R.find(ce=>ce.id===S);if(!A)return null;const O=A.kind==="swatch"||A.kind==="fonts"||A.kind==="logo",T=(x==null?void 0:x.id)===A.id?x.kind:null,X=ce=>T===ce||n.has(ce),L=ce=>t&&X(ce),W=ce=>!t&&T===ce,H=(ce,we)=>!t&&T===ce?"Extractingâ¦":we,ae=(D==null?void 0:D.id)===A.id?D.text:null,ge=!O&&(A.status==="ready"||A.status==="error"),J=t?[]:[{key:"duplicate",icon:"Copy",label:"Duplicate website",onClick:()=>i(A.id)},{key:"delete",icon:"delete-bin-6",label:"Delete website",onClick:()=>o(A.id)}];return J.length===0&&!ge?null:r.jsxs("div",{"data-ports-for":`web:${A.id}`,style:{position:"absolute",left:A.x,top:A.y,width:A.width,pointerEvents:"none"},children:[r.jsx(lu,{itemHeight:A.height,shape:"pill",actions:J,onPointerEnter:p,onPointerLeave:d,extraLeading:ge?r.jsxs(r.Fragment,{children:[r.jsx(st,{variant:L("text")?"soft":"ghost",size:"sm",loading:W("text"),busy:L("text"),leadIcon:"file-text",onClick:ce=>{ce.stopPropagation(),u(A)},children:H("text","Extract Context")}),r.jsx(st,{variant:L("images")?"soft":"ghost",size:"sm",loading:W("images"),busy:L("images"),leadIcon:"image",onClick:ce=>{ce.stopPropagation(),a(A)},children:H("images","Extract images")}),A.post?null:r.jsx(st,{variant:L("style")?"soft":"ghost",size:"sm",loading:W("style"),busy:L("style"),leadIcon:"color-wheel",onClick:ce=>{ce.stopPropagation(),l(A)},children:H("style","Extract styles")}),J.length>0?r.jsx("span",{className:"h-[18px] w-px shrink-0 bg-[var(--color-border-default)]"}):null]}):void 0}),ae?r.jsx("div",{className:"pointer-events-none absolute",style:{left:"50%",top:A.height+12,transform:"translateX(-50%)"},children:r.jsx("div",{style:{transform:"translateY(-100%)"},children:r.jsxs("div",{className:"flex w-max items-center gap-1.5 whitespace-nowrap rounded-full border border-[var(--color-border-default)] bg-[var(--color-default)] px-3 py-1.5 text-xs font-medium text-[var(--color-text-default)] shadow-[var(--shadow-modal-sm)]",children:[r.jsx(At,{name:"check",size:14,className:"text-[var(--color-icon-default-muted)]"}),ae]})})}):null]})})()]})}const Ss="#9ca3af",No="#00000008",Jn="#0000000f",Is="#6b7280",yn="#3b82f6",Xx="Inter, ui-sans-serif, system-ui, sans-serif",Fc=960,Cs=1.5,ca=.55;function du(e,t,n){var c;const o=((c=na(e))==null?void 0:c.aspect)||1.7777777777777777,i=Gc(n==null?void 0:n.width,Fc,120),a=Gc(n==null?void 0:n.height,i/o,80),l={w:i,h:a,k:Math.max(.4,i/Fc),labels:Array.isArray(t)?t:[]},u=iy[e]??hu;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${at(i)} ${at(a)}" width="${at(i)}" height="${at(a)}">`+u(l)+"</svg>"}function Gc(e,t,n){const o=typeof e=="number"&&Number.isFinite(e)&&e>0?e:t;return Math.max(n,Math.round(o))}function Yx(e){return[...e].filter(n=>!(n.length===1&&n.charCodeAt(0)>=55296&&n.charCodeAt(0)<=57343)).join("").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function at(e){return String(Math.round((Number.isFinite(e)?e:0)*10)/10)}
3function Xt(e,t,n){const o=typeof e[t]=="string"?e[t].trim():"";return o.length>0?o:n}function Yt(e,t,n){const o=Math.floor(t/Math.max(1,n*ca));return e.length<=o?e:o<=1?"â¦":`${e.slice(0,o-1).trimEnd()}â¦`}function uu(e,t,n,o){const i=t/Math.max(1,e.length*ca);return Math.max(o,Math.min(n,i))}function Zt(e,t,n,o,i,a={}){const l=a.dashed?` stroke-dasharray="${at(6*i)} ${at(6*i)}"`:"";return`<rect x="${at(e)}" y="${at(t)}" width="${at(n)}" height="${at(o)}" rx="${at(a.rx??8*i)}" fill="${a.fill??No}" stroke="${a.accent?yn:Ss}" stroke-width="${at(Cs*i)}"${l}/>`}function On(e,t,n,o,i=Jn){return`<rect x="${at(e)}" y="${at(t)}" width="${at(n)}" height="${at(o)}" rx="${at(Math.min(n,o)/2)}" fill="${i}"/>`}function Kt(e,t,n,o,i={}){const a=i.mid?t+o*.35:t,l=i.weight?` font-weight="${i.weight}"`:"";return`<text x="${at(e)}" y="${at(a)}" fill="${i.fill??Is}" font-family="${Xx}" font-size="${at(o)}" text-anchor="${i.anchor??"middle"}"${l}>${Yx(n)}</text>`}function ks(e,t,n,o,i,a=!1){const l=a?` stroke-dasharray="${at(6*i)} ${at(6*i)}"`:"";return`<path d="M ${at(e)} ${at(t)} L ${at(n)} ${at(o)}" fill="none" stroke="${Ss}" stroke-width="${at(Cs*i)}"${l}/>`}function wo(e,t,n,o,i,a=!1){const l=a?yn:Ss,u=8*i,c=Math.hypot(n-e,o-t)||1,d=(n-e)/c,p=(o-t)/c,h=n-d*u,m=o-p*u,g=-p*u*.6,k=d*u*.6;return`<path d="M ${at(e)} ${at(t)} L ${at(h)} ${at(m)}" fill="none" stroke="${l}" stroke-width="${at(Cs*i)}" stroke-linecap="round"/><path d="M ${at(n)} ${at(o)} L ${at(h+g)} ${at(m+k)} L ${at(h-g)} ${at(m-k)} Z" fill="${l}"/>`}function Kx(e,t,n,o,i){const a=(n-e)*.5;return`<path d="M ${at(e)} ${at(t)} C ${at(e+a)} ${at(t)}, ${at(n-a)} ${at(o)}, ${at(n)} ${at(o)}" fill="none" stroke="${Ss}" stroke-width="${at(Cs*i)}"/>`}function fu(e,t,n,o,i=!1){return`<circle cx="${at(e)}" cy="${at(t)}" r="${at(n)}" fill="${i?yn:Jn}" stroke="${i?yn:Ss}" stroke-width="${at(Cs*o)}"/>`}function Wc(e,t,n,o){const i=Math.hypot(n/Math.max(1,e),o/Math.max(1,t));return i>0?1/i:0}function vi(e,t,n){const o=e.x+e.w/2,i=e.y+e.h/2,a=t.x+t.w/2,l=t.y+t.h/2,u=Math.hypot(a-o,l-i)||1,c=(a-o)/u,d=(l-i)/u,p=Wc(e.w/2,e.h/2,c,d),h=Wc(t.w/2,t.h/2,c,d);return ks(o+c*p,i+d*p,a-c*h,l-d*h,n)}function Vx({w:e,h:t,k:n,labels:o}){const i=e*.06,a=e*.26,l=t*.14,u=e*.28,c=t*.34,d=e-i-u,p=(t-c)/2,h=(t-i*2-l*4)/3,m=14*n,g=[];for(let y=0;y<4;y++)g.push(Kx(i+a,i+y*(l+h)+l/2,d,t/2,n));for(let y=0;y<4;y++){const f=i+y*(l+h),I=Yt(Xt(o,y,`Source ${y+1}`),a-18*n,m);g.push(Zt(i,f,a,l,n,{dashed:!0})),g.push(Kt(i+a/2,f+l/2,I,m,{mid:!0}))}const k=17*n;return g.push(Zt(d,p,u,c,n,{accent:!0,fill:Jn})),g.push(Kt(d+u/2,p+c/2,Yt(Xt(o,4,"One slide"),u-22*n,k),k,{mid:!0,fill:yn,weight:500})),g.join("")}function qx({w:e,h:t,k:n,labels:o}){const i=e*.06,a=e*.12,l=(e-i*2-a)/2,u=t*.13,c=t*.6,d=e-i-l,p=16*n,h=[];h.push(Zt(i,u,l,c,n,{dashed:!0}));const m=[[.1,.14,.5,.075,-7],[.2,.36,.4,.07,5],[.08,.57,.62,.075,-3],[.3,.76,.34,.07,8]];for(const[g,k,y,f,I]of m){const w=i+l*g,x=u+c*k,D=l*y,R=c*f;h.push(`<g transform="rotate(${I} ${at(w+D/2)} ${at(x+R/2)})">${On(w,x,D,R)}</g>`)}h.push(Zt(d,u,l,c,n));for(let g=0;g<3;g++)h.push(On(d+l*.14,u+c*(.22+g*.22),l*(g===0?.5:.72),c*.09));return h.push(wo(i+l+a*.12,u+c/2,d-a*.12,u+c/2,n,!0)),h.push(Kt(i+l/2,u+c+28*n,Yt(Xt(o,0,"Before"),l,p),p,{mid:!0})),h.push(Kt(d+l/2,u+c+28*n,Yt(Xt(o,1,"After"),l,p),p,{mid:!0,weight:500})),h.join("")}function Jx({w:e,h:t,k:n,labels:o}){const a=e*.045,l=e*.045,u=(e-a*2-l*4)/5,c=t*.34,d=t*.3,p=14*n,h=[];for(let m=0;m<5;m++){const g=a+m*(u+l),k=m===4,y=Yt(Xt(o,m,`Step ${m+1}`),u-16*n,p);h.push(Zt(g,d,u,c,n,{accent:k,fill:k?Jn:No})),h.push(Kt(g+u/2,d+c/2,y,p,{mid:!0,fill:k?yn:Is,weight:k?500:void 0})),h.push(On(g+u*.2,d+c+18*n,u*.6,8*n)),k||h.push(wo(g+u+l*.14,d+c/2,g+u+l*.86,d+c/2,n))}return h.join("")}function Zx({w:e,h:t,k:n,labels:o}){const i=e*.07,a=t*.08,l=e-i*2,u=t*.8,c=t*.1,d=l*.26,p=[];p.push(Zt(i,a,l,u,n)),p.push(ks(i,a+c,i+l,a+c,n));for(let x=0;x<3;x++)p.push(fu(i+(18+x*15)*n,a+c/2,4*n,n));const h=13*n,m=Yt(Xt(o,0,"Product"),l*.5,h);p.push(Kt(i+70*n,a+c/2,m,h,{anchor:"start",mid:!0})),p.push(ks(i+d,a+c,i+d,a+u,n));const g=u*.1;for(let x=0;x<3;x++){const D=a+c+u*.08+x*g*1.5;if(x===0){const R=12*n,j=Yt(Xt(o,1,"Selected"),d-46*n,R);p.push(Zt(i+12*n,D,d-24*n,g,n,{accent:!0,rx:6*n,fill:Jn}
3)),p.push(Kt(i+24*n,D+g/2,j,R,{anchor:"start",mid:!0,fill:yn}))}else p.push(On(i+22*n,D+g/2-5*n,d*.58,10*n))}const k=i+d+l*.05,y=a+c+u*.1,f=l-d-l*.1,I=u-c-u*.2,w=15*n;return p.push(Zt(k,y,f,I,n,{dashed:!0})),p.push(Kt(k+f/2,y+I/2,Yt(Xt(o,2,"Main view"),f-26*n,w),w,{mid:!0})),p.join("")}function Qx({w:e,h:t,k:n,labels:o}){const a=e*.14,l=t*.13,u=t*.055,c=(t-(4*l+3*u))/2,d=e*.05,p=17*n,h=["Top layer","Layer 2","Layer 3","Base"],m=[];for(let g=0;g<4;g++){const k=e-a*2-(3-g)*d,y=(e-k)/2,f=c+g*(l+u),I=g===0;m.push(Zt(y,f,k,l,n,{accent:I,fill:I?Jn:No})),m.push(Kt(e/2,f+l/2,Yt(Xt(o,g,h[g]),k-26*n,p),p,{mid:!0,fill:I?yn:Is,weight:I?500:void 0}))}return m.join("")}function ey({w:e,h:t,k:n,labels:o}){const i=e*.06,a=e*.03,l=(e-i*2-a*2)/3,u=t*.12,c=t*.72,d=c*.24,p=16*n,h=13*n,m=[];for(let g=0;g<3;g++){const k=i+g*(l+a),y=g===2,f=Yt(Xt(o,g,`Option ${"ABC"[g]}`),l-22*n,p),I=Yt(Xt(o,g+3,"What it gives you"),l-22*n,h);m.push(Zt(k,u,l,c,n,{accent:y,fill:y?Jn:No})),m.push(ks(k,u+d,k+l,u+d,n)),m.push(Kt(k+l/2,u+d/2,f,p,{mid:!0,fill:y?yn:Is,weight:500})),m.push(Kt(k+l/2,u+d+c*.18,I,h,{mid:!0}));for(let w=0;w<2;w++)m.push(Zt(k+l*.1,u+d+c*(.32+w*.2),l*.8,c*.13,n,{dashed:!0,rx:6*n}))}return m.join("")}function ty({w:e,h:t,k:n,labels:o}){const i=Xt(o,0,"00%"),a=e*.76,l=uu(i,a,t*.3,24*n),u=19*n,c=15*n,d=e*.24,p=e*.52,h=t*.68,m=t*.2,g=[];return g.push(Kt(e/2,t*.36,Yt(i,a,l),l,{mid:!0,fill:yn,weight:600})),g.push(Kt(e/2,t*.57,Yt(Xt(o,1,"What it measures"),e*.7,u),u,{mid:!0})),g.push(Zt(d,h,p,m,n,{dashed:!0})),g.push(Kt(e/2,h+m/2,Yt(Xt(o,2,"Why it matters"),p-30*n,c),c,{mid:!0})),g.join("")}function ny({w:e,h:t,k:n,labels:o}){const a=e*.12,l=e-a*2,u=t*.5,c=14*n,d=l/3*.86,p=[];p.push(ks(a,u,e-a,u,n));for(let h=0;h<4;h++){const m=a+l*h/3,g=h===3;p.push(On(m-22*n,u-36*n,44*n,9*n)),p.push(fu(m,u,7*n,n,g)),p.push(Kt(m,u+34*n,Yt(Xt(o,h,`Milestone ${h+1}`),d,c),c,{mid:!0,fill:g?yn:Is}))}return p.join("")}function ry({w:e,h:t,k:n,labels:o}){const i=e*.06,a=e*.025,l=t*.05,u=(e-i*2-a*2)/3,c=t*.1,d=(t-c*2-l)/2,p=14*n,h=[];for(let m=0;m<6;m++){const g=i+m%3*(u+a),k=c+Math.floor(m/3)*(d+l);h.push(Zt(g,k,u,d,n)),h.push(Zt(g+18*n,k+d*.16,34*n,34*n,n,{dashed:!0,rx:6*n})),h.push(Kt(g+18*n,k+d*.7,Yt(Xt(o,m,`Item ${m+1}`),u-36*n,p),p,{anchor:"start",mid:!0})),h.push(On(g+18*n,k+d*.84,u*.5,8*n))}return h.join("")}function hu({w:e,h:t,k:n,labels:o}){const i=Xt(o,0,"Your one sentence"),a=e*.74,l=uu(i,a,t*.13,18*n),u=[];return u.push(Zt(e*.08,t*.16,e*.84,t*.68,n,{dashed:!0,rx:12*n})),u.push(Kt(e/2,t*.46,Yt(i,a,l),l,{mid:!0,weight:500})),u.push(On(e/2-44*n,t*.64,88*n,3*n,yn)),u.join("")}function sy({w:e,h:t,k:n,labels:o}){const i={x:e/2-e*.1,y:t/2-t*.07,w:e*.2,h:t*.14},a=e*.19,l=t*.12,u=e*.33,c=t*.32,d=13*n,p=[];for(let g=0;g<5;g++){const k=(-90+g*72)*Math.PI/180;p.push({x:e/2+Math.cos(k)*u-a/2,y:t/2+Math.sin(k)*c-l/2,w:a,h:l})}const h=[];for(const g of p)h.push(vi(i,g,n));h.push(vi(p[1],p[2],n)),h.push(vi(p[3],p[4],n)),p.forEach((g,k)=>{h.push(Zt(g.x,g.y,g.w,g.h,n)),h.push(Kt(g.x+g.w/2,g.y+g.h/2,Yt(Xt(o,k+1,`Node ${k+1}`),g.w-16*n,d),d,{mid:!0}))});const m=15*n;return h.push(Zt(i.x,i.y,i.w,i.h,n,{accent:!0,fill:Jn})),h.push(Kt(i.x+i.w/2,i.y+i.h/2,Yt(Xt(o,0,"Core"),i.w-18*n,m),m,{mid:!0,fill:yn,weight:500})),h.join("")}function oy({w:e,h:t,k:n,labels:o}){const i=e*.09,a=e-i*2,l=t*.12,u=t*.15,c=16*n,d=Yt(Xt(o,0,"Ask for a slide"),a*.6,c),p=i+26*n,h=u*.62,m=i+a-h-(u-h)/2,g=[];g.push(Zt(i,l,a,u,n,{rx:u/2})),g.push(Kt(p,l+u/2,d,c,{anchor:"start",mid:!0})),g.push(On(p+d.length*c*ca+3*n,l+u*.28,2.5*n,u*.44,yn)),g.push(Zt(m,l+(u-h)/2,h,h,n,{rx:h*.3,fill:Jn})),g.push(wo(m+h*.3,l+u/2,m+h*.72,l+u/2,n)),g.push(wo(e/2,l+u+12*n,e/2,t*.42,n));const k=i*1.3,y=t*.46,f=e-k*2,I=t*.42,w=18*n,x=14*n;return g.push(Zt(k,y,f,I,n,{dashed:!0})),g.push(Kt(k+26*n,y+I*.24,Yt(Xt(o,1,"Result"),f-52*n,w),w,{anchor:"start",mid:!0,weight:500})),g.push(Kt(k+26*n,y+I*.45,Yt(Xt(o,2,"What it made"),f-52*n,x),x,{anchor:"start",mid:!0})),g.push(On(k+26*n,y+I*.66,f*.62,9*n)),g.push(On(k+26*n,y+I*.78,f*.44,9*n)),g.join("")}const iy={converge:Vx,beforeAfter:qx,flow:Jx,productMock:Zx,layers:Qx,compare:ey,metric:ty,timeline:ny,tiles:ry,statement:hu,nodeMap:sy,chatBar:oy},no=268,ro=16,lr=12,ay=620,Hc=236,ly=96,cy=148;function dy(e,t,n,o){const i=e.x-ro-lr,a=n-(e.x+e.width)-ro-lr,l=i>=no,u=a>
3=no,c=l?"left":u?"right":i>=a?"left":"right",d=c==="left"?e.x-ro-no:e.x+e.width+ro,p=Math.max(lr,Math.min(d,n-no-lr)),h=e.y+e.height/2-t/2,m=Math.max(lr,Math.min(h,Math.max(lr,o-t-lr)));return{left:p,top:m,side:c}}function uy({open:e,loading:t,concepts:n,error:o,anchorRect:i,pickingIndex:a,moreLoading:l,canLoadMore:u,onMore:c,onPick:d,onRetry:p,onClose:h}){const m=s.useRef(null),g=s.useRef([]),[k,y]=s.useState(0),[f,I]=s.useState(()=>({w:typeof window>"u"?0:window.innerWidth,h:typeof window>"u"?0:window.innerHeight}));s.useEffect(()=>{if(!e)return;const A=X=>{var W,H,ae;const L=X.target;(W=m.current)!=null&&W.contains(L)||(H=L==null?void 0:L.closest)!=null&&H.call(L,"[data-birtvy-rail]")||(ae=L==null?void 0:L.closest)!=null&&ae.call(L,"[data-birtvy-concepts-trigger]")||h()},O=X=>{X.key==="Escape"&&h()},T=window.setTimeout(()=>{window.addEventListener("pointerdown",A,!0),window.addEventListener("keydown",O)},0);return()=>{window.clearTimeout(T),window.removeEventListener("pointerdown",A,!0),window.removeEventListener("keydown",O)}},[e,h]),s.useEffect(()=>{if(!e)return;const A=()=>I({w:window.innerWidth,h:window.innerHeight});return A(),window.addEventListener("resize",A),()=>window.removeEventListener("resize",A)},[e]),s.useLayoutEffect(()=>{const A=m.current;if(!e||!A)return;const O=()=>y(A.offsetHeight);O();const T=new ResizeObserver(O);return T.observe(A),()=>T.disconnect()},[e]);const w=n.map(A=>A.archetypeId).join("|"),x=s.useRef(null);s.useEffect(()=>{var A;if(!e){x.current=null;return}t||n.length===0||x.current===w||(x.current=w,(A=g.current[0])==null||A.focus({preventScroll:!0}))},[e,t,n.length,w]);const D=s.useMemo(()=>dy(i,k,f.w,f.h),[i,k,f.w,f.h]),R=A=>{var L;if(A.key!=="ArrowDown"&&A.key!=="ArrowUp"&&A.key!=="Home"&&A.key!=="End")return;const O=g.current.filter(W=>!!W);if(O.length===0)return;A.preventDefault();const T=O.indexOf(document.activeElement),X=A.key==="Home"?0:A.key==="End"?O.length-1:T<0?0:(T+(A.key==="ArrowDown"?1:O.length-1))%O.length;(L=O[X])==null||L.focus()};if(!e)return null;const j=D.side==="left";return r.jsxs(Kn.div,{ref:m,className:"fixed z-[1400] flex w-[268px] flex-col overflow-hidden rounded-[20px] border border-[var(--color-border-default)] bg-[var(--color-default)] shadow-[var(--shadow-modal-lg)]",style:{left:D.left,top:D.top,maxHeight:Math.max(240,Math.min(f.h-lr*2,ay)),transformOrigin:j?"right center":"left center"},initial:{opacity:0,scale:.96,x:j?4:-4},animate:{opacity:1,scale:1,x:0},transition:{duration:.14,ease:[.22,1,.36,1]},onPointerDown:A=>A.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center gap-[var(--spacing-8)] border-b border-[var(--color-border-default)] py-[var(--spacing-12)] pl-[var(--spacing-16)] pr-[var(--spacing-12)]",children:[r.jsx(At,{name:"lightbulb",size:16,className:"shrink-0 text-[var(--color-icon-default-muted)]"}),r.jsx("span",{className:"flex-1 text-sm font-medium text-[var(--color-text-default)]",children:"Concepts"}),r.jsx(st,{type:"button",variant:"ghostMuted",size:"icon-2xs",leadIcon:"close","aria-label":"Close concepts",onClick:h})]}),r.jsxs("div",{"data-canvas-scroll":!0,className:"flex min-h-0 flex-1 flex-col gap-[var(--spacing-8)] overflow-y-auto p-[var(--spacing-8)]",onKeyDown:R,children:[t?r.jsx(r.Fragment,{children:Array.from({length:3}).map((A,O)=>r.jsxs("div",{className:"flex flex-col gap-[var(--spacing-8)] rounded-[14px] border border-[var(--color-border-default)] p-[var(--spacing-8)]",children:[r.jsx("div",{className:`h-[112px] w-full rounded-[10px] ${hr.shimmer}`}),r.jsxs("div",{className:"flex flex-col gap-[var(--spacing-6)] px-0.5 pb-0.5",children:[r.jsx("div",{className:`h-3 rounded-[4px] ${hr.shimmer}`,style:{width:`${72-O%3*14}%`}}),r.jsx("div",{className:`h-2.5 w-4/5 rounded-[4px] ${hr.shimmer}`})]})]},O))}):o?r.jsxs("div",{className:"flex flex-col items-start gap-[var(--spacing-8)] px-[var(--spacing-8)] py-[var(--spacing-12)]",children:[r.jsx("p",{className:"text-xs leading-relaxed text-[var(--color-text-muted)]",children:o}),r.jsx(st,{type:"button",variant:"secondary",size:"xs",leadIcon:"loop-right",onClick:p,children:"Try again"})]}):n.length===0?r.jsx("p",{className:"px-[var(--spacing-8)] py-[var(--spacing-12)] text-xs leading-relaxed text-[var(--color-text-subtle)]",children:"Nothing to propose here â the slide is full. Clear some space and ask again."}):n.map((A,O)=>r.jsx(fy,{cardRef:T=>{g.current[O]=T},concept:A,strongest:O===0,picking:a===O,busy:a!=null,onPick:()=>d(A,O)},`${A.archetypeId}-${O}`)),u&&c&&!t&&!o?r.jsx("button",{type:"button",disabled:l||a!=null,onClick:c,className:"mt-[var(--spacing-4)] shrink-0 rounded-[10px] border border-[var(--color-border-default)] px-[var(--spacing-12)] py-[var(--spacing-8)] text-[13px] text-[var(--color-text-subtle)] transition-colors hover:bg-[var(--color-subtle)] disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-state-primary)]",children:l?"Thinkingâ¦":"Show me more"}):null]})]})}function fy({cardRef:e,concept:t,strongest:n,picking:o,busy:i,onPick:a}){const l=na(t.archetypeId),u=Math.round(Math.min(cy,Math.max(ly,Hc/((l==null?void 0:l.aspect)??16/9)))),c=t.labels.join("�"),d=s.useMemo(()=>{try{return du(t.archetypeId,t.labels,{width:Hc,height:u})}catch{return""}},[t.archetypeId,c,u]),p="group flex flex-col gap-[var(--spacing-8)] rounded-[14px] border p-[var(--spacing-8)] text-left transition-colors hover:bg-[var(--color-subtle)] focu
3s-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-state-primary)]",h=n?"border-[var(--color-state-primary)]":"border-[var(--color-border-default)]";return r.jsxs("button",{ref:e,type:"button",title:l==null?void 0:l.name,disabled:i,"aria-busy":o,onClick:a,className:`${p} ${h} ${i&&!o?"opacity-40":""} ${o?"bg-[var(--color-subtle)]":""}`,children:[r.jsx("span",{className:"block w-full overflow-hidden rounded-[10px] bg-[var(--color-subtle)] [&>svg]:block [&>svg]:h-full [&>svg]:w-full",style:{height:u},"aria-hidden":!0,dangerouslySetInnerHTML:{__html:d}}),r.jsxs("span",{className:"flex flex-col gap-[var(--spacing-4)] px-0.5 pb-0.5",children:[r.jsxs("span",{className:"flex items-start gap-[var(--spacing-6)]",children:[r.jsx("span",{className:"min-w-0 flex-1 text-[14px] font-medium leading-5 text-[var(--color-text-default)]",children:t.title}),n?r.jsx("span",{className:"mt-0.5 shrink-0 rounded-full bg-[color-mix(in_srgb,var(--color-state-primary)_14%,transparent)] px-1.5 py-0.5 text-[10px] font-medium leading-4 text-[var(--color-state-primary)]",children:"Strongest here"}):null]}),t.why?r.jsx("span",{className:"line-clamp-2 text-[12px] leading-4 text-[var(--color-text-muted)]",children:t.why}):null]})]})}const hy=({status:e})=>e==="complete"?r.jsx("span",{className:Qt.batchIcon,children:r.jsx(At,{name:"check",size:12})}):e==="active"?r.jsx("span",{className:Qt.batchIcon,children:r.jsx("span",{className:Qt.progressSpinnerSm,"aria-hidden":!0})}):r.jsx("span",{className:Qt.batchIcon,children:r.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",fill:"none","aria-hidden":!0,xmlns:"http://www.w3.org/2000/svg",children:r.jsx("circle",{cx:"7",cy:"7",r:"5.5",stroke:"#27272C33",strokeWidth:"1.2",strokeDasharray:"2.5 2.5",fill:"none"})})});function ki({state:e,persisted:t=!1}){var y;const{slideLabel:n,status:o,summary:i,note:a}=e,l=o==="running",u=(y=e.steps)!=null&&y.length?e.steps:(e.changes??[]).map(f=>({label:f,status:"complete"})),c=u.filter(f=>f.status==="complete").length,[d,p]=s.useState(!t),h=e.kind==="generate",m=l?`${h?"Generating":"Editing"} ${n}${c>0?` â ${c} done`:""}`:o==="done"?h?`Generated ${n}`:`Updated ${n} â ${c} change${c===1?"":"s"}`:o==="empty"?`No change to ${n}`:`Couldn't ${h?"generate":"edit"} ${n}`,g=u.length>0,k=o==="done"?"success":l?"informative":"muted";return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:Qt.card,"data-status":l?"loading":"default",children:[r.jsxs("button",{type:"button",className:Qt.header,"data-clickable":g,"data-has-body":g&&d,onClick:()=>g&&p(f=>!f),children:[r.jsxs("div",{className:Qt.headerLeft,children:[r.jsx("span",{className:Qt.icon,"data-color":k,children:r.jsx(At,{name:"canvas-text",size:15})}),r.jsx("span",{className:Qt.label,"data-shimmer":l?"true":void 0,children:m})]}),r.jsxs("div",{className:Qt.headerRight,children:[l?r.jsx("span",{className:Qt.progressSpinner,"aria-hidden":!0}):null,g?r.jsx("span",{className:Qt.chevron,children:r.jsx(At,{name:d?"arrow-up-s":"arrow-down-s",size:16})}):null]})]}),a?r.jsx("div",{className:Qt.batchBody,children:r.jsx("div",{className:Qt.batchRow,children:r.jsx("span",{className:Qt.batchName,"data-status":"pending",children:a})})}):null,r.jsx(Gm,{open:u.length>0&&d,className:Qt.batchBodyExpanded,children:r.jsx("div",{className:Qt.batchBody,children:u.map((f,I)=>r.jsxs("div",{className:Qt.batchRow,children:[r.jsx(hy,{status:f.status}),r.jsx("span",{className:Qt.batchName,"data-status":f.status==="complete"?"complete":f.status==="active"?"active":"pending",children:f.label})]},I))})})]}),i&&!l?i.split(` 4`).map((f,I)=>r.jsx("p",{style:{margin:I===0?"10px 0 0":"4px 0 0",fontFamily:"var(--font-body, Inter, ui-sans-serif, system-ui, sans-serif)",fontSize:"var(--text-sm, 14px)",lineHeight:"var(--leading-5, 20px)",letterSpacing:"-0.006em",maxWidth:480},children:f},I)):null]})}const py={position:"fixed",left:0,top:0,width:1,height:1,overflow:"hidden",opacity:0,pointerEvents:"none",zIndex:-1},my={width:Ke,height:Je,border:0,display:"block",pointerEvents:"none"},gy=900,xy=4e3;let Ui=!1;const mo=[];function Uc(){if(Ui)return;const e=mo.shift();e&&(Ui=!0,e())}function yy(e){let t="waiting";const n=()=>{t="held",e()};return mo.push(n),Uc(),{release:()=>{if(t!=="done"){if(t==="waiting"){const o=mo.indexOf(n);o>=0&&mo.splice(o,1),t="done";return}t="done",Ui=!1,Uc()}}}}const Xc=2;function by({targets:e,onBaked:t,onProgress:n,onGaveUp:o}){const i=s.useMemo(()=>{const u=Array.from({length:Xc},()=>[]);return e.forEach((c,d)=>u[d%Xc].push(c)),u},[e]),a=s.useRef([]),l=s.useRef(n);return l.current=n,r.jsx(r.Fragment,{children:i.map((u,c)=>r.jsx(wy,{targets:u,onBaked:t,onGaveUp:o,onProgress:n?(d,p)=>{var g;a.current[c]={done:d,total:p};let h=0,m=0;for(const k of a.current)k&&(h+=k.done,m+=k.total);(g=l.current)==null||g.call(l,h,m)}:void 0},c))})}function wy({targets:e,onBaked:t,onProgress:n,onGaveUp:o}){const i=s.useRef(t);i.current=t;const a=s.useRef(n);a.current=n;const l=s.useRef(o);l.current=o;const u=s.useRef(e);u.current=e;const c=s.useRef(new Map),[d,p]=s.useState(0),[h,m]=s.useState(null),[g,k]=s.useState(null),y=s.useRef(null),f=h?`${h.id}:${h.attempt}:${d}`:null,[I,w]=s.useState(null),x=s.useRef(null);s.useEffect(()=>{if(f==null)return;const R=yy(()=>w(f));return x.current=R,()=>{R.release(),x.current=null,w(null)}},[f]);const D=s.useCallback(R=>{c.current.set(R.id,R.html),p(j=>j+1),m(null),k(null)},[]);return s.useEffect(()=>{if(h)return;const R=window.innerWidth/2,j=window.innerHeight/2;let S=null,A=Number.POSITIVE_INFINITY;for(const O of e){if(c.current.get(O.id)===O.html)continue;
4const T=document.querySelector(`[data-slide-id="${O.id}"]`);let X=Number.MAX_SAFE_INTEGER;if(T){const L=T.getBoundingClientRect();X=Math.hypot(L.left+L.width/2-R,L.top+L.height/2-j)}X<A&&(A=X,S=O)}S&&m({id:S.id,html:S.html,attempt:0})},[e,h]),s.useEffect(()=>{var j;if(!a.current)return;let R=0;for(const S of e)c.current.get(S.id)!==S.html&&R++;(j=a.current)==null||j.call(a,d,d+R)},[e,d]),s.useEffect(()=>{if(!h||g==null||g!==f)return;let R=null;const j=window.setTimeout(()=>{R=Hd({id:h.id,getWindow:()=>{var S;return(S=y.current)==null?void 0:S.contentWindow},getPriority:()=>1,onDone:S=>{var O;if(!u.current.some(T=>T.id===h.id&&T.html===h.html)){D(h);return}S.ok&&S.html!=null?(S.fontHrefs&&bo(S.fontHrefs),i.current(h.id,S.html),D(h)):h.attempt===0?(k(null),m({id:h.id,html:h.html,attempt:1})):((O=l.current)==null||O.call(l,h.id,h.html),D(h))}})},gy);return()=>{window.clearTimeout(j),R==null||R()}},[h,f,g,D]),s.useEffect(()=>{if(!h||I!==f||g===f)return;const R=window.setTimeout(()=>{var j;(j=l.current)==null||j.call(l,h.id,h.html),D(h)},xy);return()=>window.clearTimeout(R)},[h,f,I,g,D]),!h||f==null||I!==f?null:r.jsx("div",{style:py,"aria-hidden":!0,"data-doc-bake-warmer":!0,children:r.jsx("iframe",{ref:y,srcDoc:Vn(h.html),sandbox:"allow-scripts",title:"Artifact bake warmer",tabIndex:-1,style:my,onLoad:()=>{var R;(R=x.current)==null||R.release(),k(f)}},f)})}function vy(e){const t=/data-bds-fonts="([^"]*)"/.exec(e);if(!t)return[];try{const n=t[1].replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),o=JSON.parse(n);return Array.isArray(o)?o.filter(i=>typeof i=="string"):[]}catch{return[]}}const Si=1920,hs=1080,Yc=56,ky=[{value:"left",icon:"align-left"},{value:"center",icon:"align-center"},{value:"right",icon:"align-right"},{value:"justify",icon:"align-justify"}];function Sy(e){return e==="start"?"left":e==="end"?"right":e||"left"}const Kc=40,Iy=400;function Cy(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.__bds_editing===1&&typeof t.on=="boolean"}function Ey(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.__bds_text===1&&Array.isArray(t.path)&&typeof t.html=="string"}function Ry(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.__bds_picked===1&&Array.isArray(t.path)&&typeof t.rect=="object"&&t.rect!==null&&typeof t.styles=="object"&&t.styles!==null}function My(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.__bds_overflow===1&&typeof t.bottom=="number"}const Vc=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]);function jy({html:e,title:t,onSource:n,onClose:o,stageInsetEdge:i=0,stageInsetRight:a=0,isAgentOpen:l=!1,onToggleAgent:u,onPresent:c}){const d=s.useRef(null),p=s.useRef(null),[h,m]=s.useState(null),g=s.useRef(null);g.current=h;const[k,y]=s.useState(null),[f,I]=s.useState(null),w=s.useRef(null);w.current=f;const x=s.useRef(e),D=s.useRef(Vn(e)),[R,j]=s.useState(0);s.useEffect(()=>(Km(),rg(()=>{D.current=Vn(x.current),j(_=>_+1)})),[]);const S=s.useRef([]),A=s.useRef([]),[O,T]=s.useState(0),[X,L]=s.useState(!1),[W,H]=s.useState(0),ae=s.useCallback(()=>{var _;(_=navigator.clipboard)==null||_.writeText(x.current).then(()=>{H(N=>N+1),window.setTimeout(()=>H(0),1400)})},[]),ge=s.useCallback(_=>{var N,Z;(Z=(N=d.current)==null?void 0:N.contentWindow)==null||Z.postMessage(_,"*")},[]),[J,ce]=s.useState(.4),we=s.useRef(J);we.current=J;const ve=s.useCallback(_=>_*we.current,[]);s.useLayoutEffect(()=>{const _=()=>{const Z=p.current;if(!Z)return;const Q=Z.getBoundingClientRect(),G=Math.min((Q.width-Yc*2)/Si,(Q.height-Yc*2)/hs);ce(Math.max(.05,Math.min(1,G)))};_();const N=typeof ResizeObserver<"u"?new ResizeObserver(_):null;return N&&p.current&&N.observe(p.current),window.addEventListener("resize",_),()=>{N==null||N.disconnect(),window.removeEventListener("resize",_)}},[]);const oe=s.useRef(n);oe.current=n;const pe=s.useRef(null),K=s.useRef(null),fe=s.useCallback((_,N)=>{S.current.push(x.current),S.current.length>60&&S.current.shift(),A.current=[],x.current=_,T(Z=>Z+1),oe.current(_,N)},[]),ie=s.useCallback(()=>{K.current!==null&&(clearTimeout(K.current),K.current=null);const _=pe.current;if(pe.current=null,!_)return;const N=mm(x.current,_.path,_.prop,_.value);N&&N!==x.current&&fe(N,gm(_.prop,_.value))},[fe]),Y=s.useCallback(_=>{const N=pe.current;N&&(N.prop!==_.prop||!Vc(N.path,_.path))&&ie(),pe.current=_,K.current!==null&&clearTimeout(K.current),K.current=setTimeout(()=>{K.current=null,ie()},Iy)},[ie]);s.useEffect(()=>{const _=N=>{var Q;if(N.source!==((Q=d.current)==null?void 0:Q.contentWindow))return;const Z=N.data;if(Ry(Z)){ie(),m({path:Z.path,tag:Z.tag,text:Z.text,fontSize:Z.fontSize,re
4ct:Z.rect,styles:Z.styles});return}if(Cy(Z)){I(Z.on?Z.path:null);return}if(Ey(Z)){const G=bm(x.current,Z.path,Z.html),se=g.current,ne=se&&Vc(se.path,Z.path)?se.tag:"";G&&G!==x.current&&fe(G,wm(ne,Z.text));return}My(Z)&&(y(Z.bottom),Z.rect&&m(G=>G&&{...G,rect:Z.rect}))};return window.addEventListener("message",_),()=>window.removeEventListener("message",_)},[ie]),s.useEffect(()=>()=>{ge({__bds_pick:{on:!1}}),ie()},[ge,ie]);const re=(_,N,Z)=>{const Q=h;Q&&(ge({__bds_style:{path:Q.path,prop:_,value:N}}),m({...Q,styles:{...Q.styles,...Z},...Z.fontSize!==void 0?{fontSize:Z.fontSize}:{}}),Y({path:Q.path,prop:_,value:N}))},le=_=>re("font-size",`${_}px`,{fontSize:_}),b=s.useCallback(()=>{const _=g.current;if(!_)return;ie();const N=xm(x.current,_.path);N&&(ge({__bds_remove:{path:_.path}}),m(null),fe(N,ym(_.tag,_.text)))},[fe,ie,ge]),C=s.useCallback(()=>{const _=g.current;_&&(ie(),ge({__bds_edit:{path:_.path,on:!0}}))},[ie,ge]),z=s.useCallback(()=>{const _=g.current;!_||_.path.length<=1||(ie(),ge({__bds_select:{path:_.path.slice(0,-1)}}))},[ie,ge]),B=s.useCallback(_=>{x.current=_,D.current=Vn(_),m(null),y(null),j(N=>N+1),T(N=>N+1)},[]),M=s.useCallback(()=>{ie();const _=S.current.pop();_!==void 0&&(A.current.push(x.current),B(_),oe.current(_,"undo"))},[ie,B]),q=s.useCallback(()=>{ie();const _=A.current.pop();_!==void 0&&(S.current.push(x.current),B(_),oe.current(_,"redo"))},[ie,B]);s.useEffect(()=>{const _=N=>{if(N.key==="Escape"){N.stopPropagation(),o();return}const Z=N.target,Q=Z==null?void 0:Z.tagName;if(Q==="INPUT"||Q==="TEXTAREA"||Z!=null&&Z.isContentEditable||w.current)return;const G=N.metaKey||N.ctrlKey;if(G&&(N.key==="z"||N.key==="Z")){N.preventDefault(),N.stopPropagation(),N.shiftKey?q():M();return}if(G&&(N.key==="y"||N.key==="Y")){N.preventDefault(),N.stopPropagation(),q();return}if(N.key==="Enter"){if(!g.current)return;N.preventDefault(),N.stopPropagation(),C();return}if(N.key==="Delete"||N.key==="Backspace"){if(!g.current)return;N.preventDefault(),N.stopPropagation(),b()}};return window.addEventListener("keydown",_,{capture:!0}),()=>window.removeEventListener("keydown",_,{capture:!0})},[o,M,q,b,C]);const ue=k!=null?Math.round(k-hs):0,ye=S.current.length>0,ee=A.current.length>0,U=h&&h.text.length>Kc?`${h.text.slice(0,Kc).trimEnd()}â¦`:(h==null?void 0:h.text)??"";return r.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":t?`Editing ${t}`:"Editing artifact",className:"fixed z-[3000] flex flex-col overflow-hidden bg-default",style:{top:i,left:i,bottom:i,right:a,borderRadius:i>0?"var(--radius-lg)":0,border:i>0?"1px solid var(--color-border-default)":void 0},onPointerDown:_=>_.stopPropagation(),onDoubleClick:_=>_.stopPropagation(),children:[r.jsxs("div",{className:"flex h-[56px] shrink-0 items-center gap-[var(--spacing-8)] border-b border-[var(--color-border-default)] bg-default px-[var(--spacing-16)]",children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"close",onClick:o,"aria-label":"Back to canvas",title:"Back to canvas",className:"pointer-events-auto"}),r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"undo",onClick:M,disabled:!ye,"aria-label":"Undo",title:"Undo (âZ)"}),r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"redo",onClick:q,disabled:!ee,"aria-label":"Redo",title:"Redo (ââ§Z)"}),r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-[var(--color-text-default)]",children:t||"Artifact"}),r.jsxs("div",{className:"flex shrink-0 items-center gap-[var(--spacing-8)]",children:[r.jsx(st,{variant:X?"secondary":"ghost",size:"sm",onClick:()=>L(_=>!_),"aria-pressed":X,title:"Inspect the artifact's source",children:"Code"}),r.jsx(st,{variant:"ghost",size:"sm",leadIcon:"share-2",children:"Share"}),c?r.jsx(st,{variant:"default",size:"sm",leadIcon:"play",onClick:c,children:"Present"}):null,u?r.jsx(st,{variant:"ghost",size:"sm",leadIcon:l?"chat-1-fill":"chat-1",onClick:u,"aria-label":"Toggle Agent",children:"Agent"}):null]})]}),r.jsxs("div",{className:"flex min-h-0 flex-1",children:[r.jsx("div",{ref:p,className:"relative flex min-w-0 flex-1 items-center justify-center",onPointerDown:_=>{_.target===_.currentTarget&&m(null)},children:r.jsxs("div",{className:"relative shrink-0 overflow-hidden rounded-[8px] bg-white shadow-[0_24px_80px_rgba(0,0,0,0.12)]",style:{width:Si*J,height:hs*J},children:[r.jsx("iframe",{ref:d,title:t||"Artifact",srcDoc:D.current,sandbox:"allow-scripts",onLoad:()=>ge({__bds_pick:{on:!0}}),style:{position:"absolute",left:0,top:0,width:Si,height:hs,border:0,display:"block",transform:`scale(${J})`,transformOrigin:"0 0",pointerEvents:"auto"}}
4,R),h?r.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute",style:{left:ve(h.rect.x),top:ve(h.rect.y),width:ve(h.rect.w),height:ve(h.rect.h),boxShadow:"0 0 0 2px var(--color-state-primary)",borderRadius:2},children:r.jsxs("span",{className:"absolute left-0 max-w-full truncate rounded-[4px] px-[6px] py-[2px] text-[11px] leading-[16px] text-white",style:{bottom:ve(h.rect.y)>22?"100%":void 0,top:ve(h.rect.y)>22?void 0:0,marginBottom:ve(h.rect.y)>22?4:void 0,background:"var(--color-state-primary)"},children:[h.tag.toLowerCase(),U?` ${U}`:""]})}):null]})}),X?r.jsxs("div",{className:"pointer-events-auto z-[210] flex h-full w-[480px] shrink-0 flex-col border-l border-[var(--color-border-default)] bg-default",children:[r.jsxs("div",{className:"flex h-[40px] shrink-0 items-center gap-[var(--spacing-8)] border-b border-[var(--color-border-default)] px-[var(--spacing-12)]",children:[r.jsx("span",{className:"text-sm font-medium text-[var(--color-text-default)]",children:"Source"}),r.jsxs("span",{className:"text-xs text-[var(--color-text-tertiary)]",children:[x.current.length.toLocaleString()," chars"]}),r.jsx("span",{className:"flex-1"}),r.jsx(st,{variant:"ghost",size:"sm",onClick:ae,children:W?"Copied":"Copy"})]}),r.jsx("pre",{className:"m-0 min-h-0 flex-1 overflow-auto whitespace-pre p-[var(--spacing-12)] font-mono text-[11px] leading-[17px] text-[var(--color-text-default)]",children:x.current})]}):null,r.jsx("aside",{className:"pointer-events-auto relative z-[210] flex h-full w-[240px] shrink-0 flex-col items-stretch gap-3 overflow-y-auto border-l border-[var(--color-border-default)] bg-default [&_.toolbar-panel-root]:!justify-start",children:r.jsxs("div",{className:og.panel,children:[h?r.jsxs(r.Fragment,{children:[r.jsx(cs,{label:"Selection",children:r.jsxs("div",{className:"flex items-center gap-[var(--spacing-8)]",children:[r.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-[12px] text-[var(--color-text-muted)]",children:[h.tag.toLowerCase(),U?` ${U}`:""]}),r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"text",onClick:C,"aria-label":"Edit text",title:"Edit text (Enter, or double-click it)"}),r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"arrow-up",onClick:z,disabled:h.path.length<=1,"aria-label":"Select parent element",title:"Select the element around this one"}),r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"delete-bin-6",onClick:b,"aria-label":"Delete element",title:"Delete element (Del)"})]})}),r.jsxs(cs,{label:"Typography",children:[r.jsx(Ir,{mode:"stepped",size:"md",values:jc,selectedIndex:eg(h.styles.fontSize),onChange:_=>le(jc[_]),label:"Size",ariaLabel:"Font size"}),r.jsx(Dp,{value:String(h.styles.fontWeight),options:tg,onChange:_=>re("font-weight",String(Number(_)),{fontWeight:Number(_)}),ariaLabel:"Font weight"}),r.jsx(Ir,{mode:"continuous",min:.8,max:3,step:.05,value:h.styles.lineHeight??1.2,mixed:h.styles.lineHeight===null,onChange:_=>re("line-height",String(_),{lineHeight:_}),label:"Line height",ariaLabel:"Line height"}),r.jsx(Ir,{mode:"continuous",min:-5,max:20,step:.5,value:h.styles.letterSpacing,onChange:_=>re("letter-spacing",`${_}px`,{letterSpacing:_}),label:"Letter spacing",ariaLabel:"Letter spacing"}),r.jsx(ng,{items:ky,value:Sy(h.styles.textAlign),onChange:_=>re("text-align",_,{textAlign:_}),"aria-label":"Text align"})]}),r.jsxs(cs,{label:"Appearance",children:[r.jsx(Tp,{label:"Color",showGradient:!1,hex:ri(h.styles.color).hex,opacity:ri(h.styles.color).opacity,onColorChange:_=>re("color",Ap(_,ri(h.styles.color).opacity),{color:_})}),r.jsx(Ir,{mode:"continuous",min:0,max:100,step:1,value:Math.round(h.styles.opacity*100),onChange:_=>re("opacity",String(_/100),{opacity:_/100}),label:"Opacity",unit:"%",ariaLabel:"Opacity"})]})]}):r.jsx(cs,{label:"Text",children:r.jsx("p",{className:"text-[13px] leading-[18px] text-[var(--color-text-muted)]",children:"Click any text in the slide to edit it. Delete removes it, and undo is âZ."})}),ue>0?r.jsx(cs,{label:"Overflow",muted:!0,children:r.jsxs("p",{className:"text-[13px] leading-[18px] text-[var(--color-text-muted)]",children:["Content runs ",ue,"px past the bottom of the slide. The slide is ",hs,"px tall, so that part will not show."]})}):null]})})]})]})}function pu(e){var l,u,c;const t=e.match(/<div[^>]*\bdata-el=["']chart["'][^>]*>([\s\S]*?)<\/div>/i);if(!t)return null;const n=t[1].replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();if(!n)return null;const o=(((l=t[0].match(/data-chart-type=["']([^"']*)["']/i))==null?void 0:l[1])||"").trim(),i=Number((u=t[0].match(/width:\s*(\d+(?:\.\d+)?)/i))==null?void 0:u[1])||640,a=Number((c=t[0].match(/height:\s*(\d+(?:\.\d+)?)/i))==null?void 0:c[1])||400;return{dataText:n,chartType:o,w:i,h:a}}const Ny={bar:"column",column:"column",line:"line",area:"areaStacked",donut:"donut",pie:"pie"};function Dy(e){const t=e.match(/(-?\d[\d,]*\.?\d*)\s*([kmb])?/i);if(!t)return null;const n=Number(t[1].replace(/,/g,""));if(!Number.isFinite(n))return null;const o=(t[2]||"").toLowerCase();return o==="k"?n*1e3:o==="m"?n*1e6:o==="b"?n*1e9:n}function mu(e){const t=[];for(const n of e.split(/[.;]\s+|,\s+/)){const o=n.trim().replace(/[.;]+$/,"").trim();if(!o)continue;const i=o.match(/^(.+?)[:\s]\s*([$â¬Â£]?-?\d[\d,]*\.?\d*\s*[kmb]?%?)\s*$/i);if(!i)continue;const a=i[1].replace(/[:\s]+$/,"").trim(),l=Dy(i[2].replace(/[$â¬Â£%]/g,""));a&&a.length<=48&&l!=null&&t.push({label:a,value:l})}return t}function Ty(e){if(!e||/[ââ]/.test(e))return null;const t=mu(e);return t.length>=2?t:null}function Ay(e){if(!e||!/[ââ]/.test(e))return null;const t=[];for(const o of e.split(/\.\s+/)){const i=o.trim().match(/^(.{1,60}?)\s*[ââ]\s*(.+)$/);if(!i)continue;const a=mu(i[2]);a.length>=2&&t.push({name:i[1].trim(),rows:a})}if(t.length<2)return null;const n=t[0].rows.map(o=>o.label);
4for(const o of t)if(o.rows.length!==n.length||o.rows.some((i,a)=>i.label!==n[a]))return null;return{names:t.map(o=>o.name),labels:n,values:t.map(o=>o.rows.map(i=>i.value))}}function $y(e){if(!e)return[];const t=e.roles??{},n=new Set([t.background,t.surface].filter(a=>!!a).map(a=>a.trim().toLowerCase())),o=[],i=new Set;for(const a of[t.accent,...e.palette??[]]){const l=a==null?void 0:a.trim();if(!l||!/^#[0-9a-f]{6}$/i.test(l))continue;const u=l.toLowerCase();n.has(u)||i.has(u)||(i.add(u),o.push(l))}return o}function Py(e,t){if(e.length===0||t<=0)return;const n={};for(let o=0;o<Math.min(t,20);o++)n[`series${o+1}`]={customColor:e[o%e.length]};return Object.keys(n).length>0?n:void 0}function da(e,t,n,o){const i=Ny[(t||"").trim().toLowerCase()]??"column",a=Ty(e);if(a)return{type:i,data:{columns:[{key:"category",label:"Category"},{key:"value",label:"Value"}],rows:a.map(u=>({category:u.label,value:u.value}))},...qc(o,a.length)};const l=Ay(e);return!l||i==="donut"||i==="pie"?null:{type:i,data:{columns:[{key:"category",label:"Category"},...l.names.map((u,c)=>({key:`s${c}`,label:u}))],rows:l.labels.map((u,c)=>({category:u,...Object.fromEntries(l.names.map((d,p)=>[`s${p}`,l.values[p][c]]))}))},_unstable_mapping:{x:"category",y:l.names.map((u,c)=>({columnKey:`s${c}`}))},...qc(o,l.names.length)}}function qc(e,t){const n=Py(e??[],t);return n?{appearance:{seriesStyles:n}}:{}}function Ly({getState:e,onHydrate:t,requestSave:n,isEmpty:o,slides:i,docs:a,notes:l,images:u,webs:c,wires:d,title:p,designSystems:h,activeDesignSystemId:m,paused:g=!1}){const k=s.useRef({past:[],present:null,future:[]}),y=s.useRef(null),f=s.useCallback(()=>{const D=e(),R=JSON.stringify(D),j=k.current;R!==j.present&&(o(D)&&j.present===null||(j.present!==null&&(j.past.push(j.present),j.past.length>100&&j.past.shift()),j.present=R,j.future=[]))},[e,o]),I=s.useCallback(D=>{try{t(JSON.parse(D),{frame:!1}),n()}catch{}},[t,n]),w=s.useCallback(()=>{y.current&&(window.clearTimeout(y.current),y.current=null),f();const D=k.current,R=D.past.pop();R!=null&&(D.present!==null&&D.future.push(D.present),D.present=R,I(R))},[f,I]),x=s.useCallback(()=>{y.current&&(window.clearTimeout(y.current),y.current=null);const D=k.current,R=D.future.pop();R!=null&&(D.present!==null&&D.past.push(D.present),D.present=R,I(R))},[I]);s.useEffect(()=>(y.current&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{y.current=null,f()},400),()=>{y.current&&window.clearTimeout(y.current)}),[i,a,l,u,c,d,p,h,m,f]),s.useEffect(()=>{if(g)return;const D=R=>{if(!(R.metaKey||R.ctrlKey)||R.altKey)return;const j=R.key.toLowerCase();if(j!=="z"&&j!=="y")return;const S=R.target;S&&(S.tagName==="INPUT"||S.tagName==="TEXTAREA"||S.isContentEditable)||(R.preventDefault(),j==="y"||j==="z"&&R.shiftKey?x():w())};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[w,x,g])}function zy({progress:e,visible:t}){const n=Math.max(6,Math.round(e*100));return r.jsxs("div",{style:{position:"fixed",inset:0,zIndex:3e3,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:34,backgroundColor:"#f4f4f5",opacity:t?1:0,pointerEvents:t?"auto":"none",transition:"opacity 360ms cubic-bezier(0.22, 1, 0.36, 1)"},children:[r.jsx("span",{role:"img","aria-label":"Deck is loading",style:{fontFamily:"'Inter', sans-serif",fontWeight:700,fontSize:52,lineHeight:1,letterSpacing:"-0.04em",color:"#111115",userSelect:"none"},children:"Deck"}),r.jsx("div",{style:{width:340,height:4,borderRadius:999,backgroundColor:"rgba(24, 24, 27, 0.10)",overflow:"hidden"},children:r.jsx("div",{style:{height:"100%",width:`${n}%`,backgroundColor:"#18181b",borderRadius:999,transition:"width 300ms cubic-bezier(0.22, 1, 0.36, 1)"}})})]})}function dr(e,t){return(e==null?void 0:e.snap)??t}const Wt=140,kr=4,ys=12,Ht=45;function Xr(e,t){return Math.abs(e.y-t.y)>Je/2?e.y-t.y:e.x-t.x}function gu(e,t){return e.filter(n=>n.groupId===t).sort(Xr)}function _y(e,t){return new Set([t,...e.filter(n=>n.parentId===t).map(n=>n.id)])}function ua(e,t,n){const o=_y(t,n);return e.filter(i=>i.groupId!=null&&o.has(i.groupId)).sort(Xr)}function Xi(e,t,n,o){const i=gu(e,t);if(i.length<2)return e;const a=Math.min(...i.map(c=>c.x)),l=Math.min(...i.map(c=>c.y)),u=new Map;
4return i.forEach((c,d)=>{u.set(c.id,{x:a+d%n*(Ke+o),y:l+Math.floor(d/n)*(Je+o)})}),e.map(c=>{const d=u.get(c.id);return d&&(c.x!==d.x||c.y!==d.y)?{...c,x:d.x,y:d.y}:c})}function Oy(e){return{width:Math.max(1,...e.map(t=>t.width)),height:Math.max(1,...e.map(t=>t.height))}}function By(e,t,n,o){if(!e.length)return[];const i=[...e].sort(Xr),a=Math.min(...i.map(u=>u.x)),l=Math.min(...i.map(u=>u.y));return i.map((u,c)=>({x:a+c%t*(o.width+n),y:l+Math.floor(c/t)*(o.height+n),width:o.width,height:o.height}))}function Fy(e){return[...e].sort(Xr).map(t=>({x:t.x,y:t.y,width:t.width,height:t.height}))}function xu(e,t,n,o,i){const a=e.find(h=>Ye(h.kind,h.id)===t);if(!a||i.length<2||e.length<2)return[...e].sort(Xr);const l=e.filter(h=>Ye(h.kind,h.id)!==t).sort(Xr),u=n+a.width/2,c=o+a.height/2;let d=0,p=1/0;return i.forEach((h,m)=>{const g=(h.x+h.width/2-u)**2+(h.y+h.height/2-c)**2;g<p&&(p=g,d=m)}),[...l.slice(0,d),a,...l.slice(d)]}function Gy(e,t,n,o,i){const a=new Map;return i.length<2||e.length<2||xu(e,t,n,o,i).forEach((u,c)=>{c>=i.length||a.set(Ye(u.kind,u.id),{x:Math.round(i[c].x+(i[c].width-u.width)/2),y:Math.round(i[c].y+(i[c].height-u.height)/2)})}),a}const Ye=(e,t)=>`${e}:${t}`,bs=e=>{const t=e.indexOf(":");return{kind:e.slice(0,t),id:Number(e.slice(t+1))}};function cn(e){if(!e.length)return null;let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const a of e)t=Math.min(t,a.x),n=Math.min(n,a.y),o=Math.max(o,a.x+a.width),i=Math.max(i,a.y+a.height);return{x:t-Ht,y:n-Ht,width:o-t+Ht*2,height:i-n+Ht*2}}function Wy(e){return e.x!=null&&e.y!=null&&e.width!=null&&e.height!=null?{x:e.x,y:e.y,width:e.width,height:e.height}:null}function Hy(e,t,n){if(!t.length)return[];const o=new Map;for(const u of t)if(u.parentId!=null){const c=o.get(u.parentId);c?c.push(u):o.set(u.parentId,[u])}const i=(u,c)=>{const d=gu(e,u.id),p=n.filter(w=>w.groupId===u.id),h=d.length+p.length+c.length;if(h<2)return null;const m=d.map(w=>({kind:"slide",id:w.id,x:w.x,y:w.y,width:Ke,height:Je,groupId:u.id})),g=[...m,...p],k=[...g,...c.map(w=>({x:w.frame.x,y:w.frame.y-Wt,width:w.frame.width,height:w.frame.height+Wt}))],y=cn(k);if(!y)return null;const f=(u.collapsed??!1)&&d.length>0,I=f?cn(m)??y:Wy(u)??y;return{id:u.id,title:u.title,members:d,frame:I,memberCount:h,slidesOnly:p.length===0&&c.length===0&&d.length>0,memberRects:g,contentBounds:y,hiddenCount:p.length,collapsed:f,canCollapse:d.length>0&&p.length>0,parentId:u.parentId??null,isParent:c.length>0,allItemKeys:[...g.map(w=>Ye(w.kind,w.id)),...c.flatMap(w=>w.allItemKeys)]}},a=new Map;for(const u of t){if(o.has(u.id))continue;const c=i(u,[]);c&&a.set(u.id,c)}const l=[];for(const u of t){if(!o.has(u.id))continue;const c=(o.get(u.id)??[]).map(p=>a.get(p.id)).filter(p=>!!p),d=i(u,c);d&&l.push(d)}return l.push(...a.values()),l}function Uy(e){const t=new Set;for(const n of e)if(n.collapsed)for(const o of n.memberRects)o.kind!=="slide"&&t.add(Ye(o.kind,o.id));return t}const Xy={topLeft:{left:!0,top:!0},topRight:{right:!0,top:!0},bottomLeft:{left:!0,bottom:!0},bottomRight:{right:!0,bottom:!0},top:{top:!0},bottom:{bottom:!0},left:{left:!0},right:{right:!0}};function Jc(e,t,n,o,i){const a=Xy[n];let l=e.x+(a.left?o:0),u=e.y+(a.top?i:0),c=e.x+e.width+(a.right?o:0),d=e.y+e.height+(a.bottom?i:0);return l=Math.min(l,t.x),u=Math.min(u,t.y),c=Math.max(c,t.x+t.width),d=Math.max(d,t.y+t.height),{x:l,y:u,width:c-l,height:d-u}}function Yy(e,t){if(!t)return e;const n=Math.min(e.x,t.x),o=Math.min(e.y,t.y),i=Math.max(e.x+e.width,t.x+t.width),a=Math.max(e.y+e.height,t.y+t.height);return{x:Math.round(n),y:Math.round(o),width:Math.round(i-n),height:Math.round(a-o)}}function an(e,t){return{...e,x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}}function yu(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function bu(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function wu(e,t){var l;const n=new Map;if(!e.length||!t.length)return n;const o=new Set(t.map(u=>Ye(u.kind,u.id))),i=new Map;for(const u of e)i.set(u.id,u.allItemKeys.every(c=>o.has(c)));const a=[...e].sort((u,c)=>Number(u.isParent)-Number(c.isParent));for(const u of t){const c=u.groupId??null;if(c!=null&&i.get(c))continue;const d=u.x+u.width/2,p=u.y+u.height/2;let h,m=c==null;if(c!=null){const g=(l=e.find(k=>k.id===c))==null?void 0:l.frame;g&&!yu(g,u)&&(h=null,m=!0)}if(m){for(const g of a)if(g.id!==c&&bu(g.frame,d,p)){h=g.id;break}}h!==void 0&&h!==c&&n.set(Ye(u.kind,u.id),h)}return n}function Ky(e,t,n){var u;const o=e.find(c=>c.id===t);if(!o)return;const i=o.parentId??null;let a,l=i==null;if(i!=null){const c=(u=e.find(d=>d.id===i))==null?void 0:u.frame;c&&!yu(c,n)&&(a=null,l=!0)}if(l&&!o.isParent){const c=n.x+n.width/2,d=n.y+n.height/2;
4for(const p of e)if(!(p.id===t||p.id===i)&&p.parentId==null&&bu(p.frame,c,d)){a=p.id;break}}return a!==void 0&&a!==i?a:void 0}function Vy(e){const{count:t,docIndices:n,styleSizes:o,baseX:i,baseY:a,cols:l,gap:u}=e,c=Ht,d=a,p=o.length?Math.max(...o.map(x=>x.width)):0,h=[];let m=d;for(const x of o)h.push({id:x.id,x:i,y:m}),m+=x.height+c;const g=i+(p?p+c*2:0),k=[],y=new Map,f=new Map;if(n.size>0){let x=g;for(let D=0;D<t;D++)if(n.has(D)){y.set(D,{x,y:d});const R=x+En+c;k.push({x:R,y:d,clustered:!0});const j={x:x-c,y:d-c,width:En+c+Ke+c*2,height:Math.max(Je,Cn)+c*2};f.set(D,j),x=j.x+j.width+c*2}else k.push({x,y:d,clustered:!1}),x+=Ke+c*2}else for(let x=0;x<t;x++)k.push({x:g+x%l*(Ke+u),y:d+Math.floor(x/l)*(Je+u),clustered:!1});return{parentRect:cn([...o.map((x,D)=>({x:h[D].x,y:h[D].y,width:x.width,height:x.height})),...k.filter(x=>!x.clustered).map(x=>({x:x.x,y:x.y,width:Ke,height:Je})),...[...f.values()].map(x=>({x:x.x,y:x.y-Wt,width:x.width,height:x.height+Wt}))])??{x:i,y:a,width:Ke,height:Je},contentTop:d,slides:k,docs:y,clusters:f,styles:h,styleColX:i,styleColBottom:m}}function vu(e,t,n){const o=new Map,i=(h,m)=>h.y-m.y||h.x-m.x,a=[...e.filter(h=>h.kind==="doc").sort(i),...e.filter(h=>h.kind==="slide").sort(i)],l=e.filter(h=>h.kind!=="doc"&&h.kind!=="slide").sort(i);let u=t,c=0;for(const h of a)o.set(Ye(h.kind,h.id),{x:Math.round(u),y:Math.round(n)}),u+=h.width+Ht,c=Math.max(c,h.height);let d=t;const p=n+(a.length?c+Ht:0);for(const h of l)o.set(Ye(h.kind,h.id),{x:Math.round(d),y:Math.round(p)}),d+=h.width+Ht;return o}function vo(e,t,n,o,i=fa,a=ha){const l=new Map,u=Math.max(1,Math.round(o));let c=n;for(let d=0;d<e.length;d+=u){const p=e.slice(d,d+u);if(!p.length)break;const h=Math.max(...p.map(g=>g.height));let m=t;for(const g of p)l.set(Ye(g.kind,g.id),{x:Math.round(m),y:Math.round(c+(h-g.height)/2)}),m+=g.width+i;c+=h+a}return l}function ku(e,t,n,o){const i=new Map,a=Math.max(1,Math.round(t));let l=n,u=o,c=0;return e.forEach((d,p)=>{p>0&&p%a===0&&(u+=c+Ht,l=n,c=0);const h=d.labelBand?Wt:0;i.set(d.key,{x:Math.round(l),y:Math.round(u+h)}),l+=d.width+Ht,c=Math.max(c,d.height+h)}),i}const Yi=e=>e.y-(e.labelBand?Wt:0);function Ki(e,t){const n=Yi(e),o=Yi(t);return Math.abs(n-o)>Je/2?n-o:e.x-t.x}function Su(e){return[...e].sort(Ki)}function qy(e){return Su(e).map(t=>({x:t.x,y:Yi(t),width:t.width,height:t.height+(t.labelBand?Wt:0)}))}function Zc(e,t,n,o,i){const a=e.find(m=>m.key===t);if(!a||i.length<2||e.length<2)return[...e].sort(Ki);const l=e.filter(m=>m.key!==t).sort(Ki),u=a.labelBand?Wt:0,c=n+a.width/2,d=o+(a.height+u)/2;let p=0,h=1/0;return i.forEach((m,g)=>{const k=(m.x+m.width/2-c)**2+(m.y+m.height/2-d)**2;k<h&&(h=k,p=g)}),[...l.slice(0,p),a,...l.slice(p)]}const fa=80,ha=120;function Jy(e,t){const n=new Map;for(const c of t)c!=null&&n.set(c,(n.get(c)??0)+1);const o=new Map(e.map(c=>[c.id,c])),i=new Map;for(const c of e)if(c.parentId!=null&&o.has(c.parentId)){const d=i.get(c.parentId);d?d.push(c):i.set(c.parentId,[c])}const a=new Set,l=new Map;for(const c of e)i.has(c.id)||(n.get(c.id)??0)>=2&&a.add(c.id);for(const c of e){const d=i.get(c.id);if(!d)continue;let p=n.get(c.id)??0;for(const h of d)a.has(h.id)?p+=1:p+=n.get(h.id)??0;p>=2&&a.add(c.id)}for(const c of e)a.has(c.id)||l.set(c.id,c.parentId!=null&&a.has(c.parentId)?c.parentId:null);const u=new Set(e.filter(c=>a.has(c.id)&&c.parentId!=null&&!a.has(c.parentId)).map(c=>c.id));return{keep:a,remap:l,clearParent:u,changed:a.size!==e.length||u.size>0}}const Iu=(e,t)=>[...e.map(n=>({kind:"cluster",id:n.id,key:`cluster:${n.id}`,x:n.frame.x,y:n.frame.y,width:n.frame.width,height:n.frame.height,labelBand:!0})),...t.map(n=>({kind:"slide",id:n.id,key:`slide:${n.id}`,x:n.x,y:n.y,width:Ke,height:Je,labelBand:!1}))];function Zy(e,t,n,o){const i=(c,d)=>c.x<d.x+d.width&&c.x+c.w>d.x&&c.y<d.y+d.height&&c.y+c.h>d.y,a=n*Ke+(n-1)*In,l=[...o.slides.map(c=>({x:c.x,y:c.y,width:Ke,height:Je})),...o.docs.map(c=>({x:c.x,y:c.y,width:c.width,height:c.height})),...o.notes.map(c=>({x:c.x,y:c.y,width:c.width,height:c.height})),...o.images.map(c=>({x:c.x,y:c.y,width:c.width,height:c.height})),...o.webs.map(c=>({x:c.x,y:c.y,width:c.width,height:c.height}))];let u=t;for(let c=0;c<24;c++){const d={x:e,y:u,w:a,h:Je};if(!l.some(p=>i(d,p)))return u;u+=Je+In}return u}function Qy(e,t,n,o){if(!e.length)return[];const i=new Set(e),a=new Set;for(const u of t)u.to.kind==="slide"&&u.from.kind==="doc"&&i.has(u.from.id)&&a.add(u.to.id);const l=new Set(n.filter(u=>i.has(u.id)&&u.groupId!=null).map(u=>u.groupId));if(l.size)for(const u of o)u.groupId!=null&&l.has(u.groupId)&&a.add(u.id);return[...a]}function eb({store:e,wires:t,rectForRef:n,setWireDropMenu:o}){const{setSlides:i,setWires:a,idRef:l,requestSave:u}=e,c=s.useCallback(m=>{a(g=>g.filter(k=>k.id!==m)),u()},[u]),d=s.useCallback((m,g,k)=>{a(y=>y.some(f=>f.from.kind===m.kind&&f.from.id===m.id&&f.to.kind===g.kind&&f.to.id===g.id)?y:[...y,{id:l.current++,from:m,to:g,mode:k,...k==="style"?{styleStrength:100}:{}}]),u()},[u]),p=s.useCallback((m,g,k)=>{const y=l.current++,f=Math.round(g.x),I=Math.round(g.y-Je/2);i(x=>[...x,{id:y,x:f,y:I,status:"empty",prompt:""}]);const w=m.kind==="image"?k??"image":"standard";a(x=>[...x,{id:l.current++,from:m,to:{kind:"slide",id:y},mode:w,...w==="style"?{styleStrength:100}:{}}]),o(null),u()},[u]),h=s.useCallback(m=>{const g=n(m);if(!g)return["right"];const k=new Set(["right"]);for(const y of t){const f=y.from.kind===m.kind&&y.from.id===m.id,I=y.to.kind===m.kind&&y.to.id===m.id;if(!f&&!I)continue;const w=n(f?y.to:y.from);if(!w)continue;const x=f?Pi(g,w):Pi(w,g);k.add(f?x.fromSide:x.toSide)}return[...k]},[t,n]);return{deleteWire:c,commitWireMode:d,createSlideFromWire:p,portSidesFor:h}}function tb(e,t){if(e.kind==="slide"){const o=t.slides.find(i=>i.id===e.id);return o?{x:o.x,y:o.y,width:Ke,height:Je}:null}if(e.kind==="note"){const o=t.notes.find(i=>i.id===e.id);return o?{x:o.x,y:o.y,width:o.width,height:o.height}:null}if(e.kind==="image"){const o=t.images.find(i=>i.id===e.id);return o?{x:o.x,y:o.y,width:o.width,height:o.height}:null}if(e.kind==="web"){const o=t.webs.find(i=>i.id===e.id);return o?{x:o.x,y:o.y,width:o.width,height:o.height}:null}const n=t.docs.find(o=>o.id===e.id);return n?{x:n.x,y:n.y,width:n.width,height:n.height}:null}function nb({pan:e,zoom:t,viewportRef:n,worldRef:o,overlayRef:i,marqueeRectRef:a,glDrawRef:l,fitAllRef:u,focusRectRef:c,slides:d,slidesRef:p,docsRef:h,notesRef:m,imagesRef:g,websRef:k,setLiveDocIds:y,liveDocIdsRef:f,liveZoomOnRef:I,liveSyncTimerRef:w,zoomSettleRef:x,setZoomPct:D,setLod:R,hoverClearRef:j,setHoveredId:S,setHoveredDocId:A,setHoveredNoteId:O,setHoveredImageId:T,setHoveredWebId:X,hoveredId:L,hoveredDocId:W,hoveredNoteId:H,hoveredImageId:ae,hoveredWebId:ge,setHoveredGroupId:J,groupViewsRef:ce,itemDragRef:we}){const ve=s.useCallback(()=>
4{if(!Br())return;const G=n.current;if(!G)return;const se=t.current;!I.current&&se>=Mx?I.current=!0:I.current&&se<jx&&(I.current=!1);let ne=[];if(I.current){const de=G.clientWidth,F=G.clientHeight,$=de*_c,P=F*_c,me=de/2,he=F/2,Me=[];for(const He of p.current){if(!He.docHtml||!He.docBaked)continue;const Ee=He.x*se+e.current.x,qe=He.y*se+e.current.y,Ae=Ke*se,jt=Je*se;Ee+Ae<-$||qe+jt<-P||Ee>de+$||qe>F+P||Me.push({id:He.id,d:(Ee+Ae/2-me)**2+(qe+jt/2-he)**2})}Me.sort((He,Ee)=>He.d-Ee.d),ne=Me.slice(0,Nx).map(He=>He.id)}y(de=>{if(de.size===ne.length&&ne.every($=>de.has($)))return de;const F=new Set(ne);return f.current=F,F})},[]),oe=s.useCallback(()=>{w.current&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{w.current=null,ve()},160)},[ve]),pe=s.useCallback(()=>{oe();const G=o.current;G&&(G.style.transform=`translate(${e.current.x}px, ${e.current.y}px) scale(${t.current})`,G.style.setProperty("--sel-scale",String(1/Math.max(t.current,.25))),G.style.setProperty("--port-scale",String(1/t.current))),l.current();const se=i.current,ne=a.current;se&&se.dataset.active==="1"&&ne&&(se.style.left=`${ne.x*t.current+e.current.x}px`,se.style.top=`${ne.y*t.current+e.current.y}px`,se.style.width=`${ne.w*t.current}px`,se.style.height=`${ne.h*t.current}px`)},[oe]);s.useEffect(()=>{pe()},[pe]),s.useEffect(()=>{oe()},[d,oe]);const K=s.useCallback((G,se)=>{const ne=n.current;if(!ne)return{x:0,y:0};const de=ne.getBoundingClientRect();return{x:(G-de.left-e.current.x)/t.current,y:(se-de.top-e.current.y)/t.current}},[]),fe=s.useCallback(()=>{x.current&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{x.current=null,D(t.current*100)},120)},[]),ie=s.useRef(null),Y=s.useCallback(()=>{ie.current&&window.clearTimeout(ie.current),ie.current=window.setTimeout(()=>{ie.current=null,R(t.current*100<fr)},160)},[]),re=s.useRef(null),le=s.useCallback(()=>{ec(!0),re.current&&window.clearTimeout(re.current),re.current=window.setTimeout(()=>ec(!1),220)},[]),b=s.useCallback(()=>{j.current&&(window.clearTimeout(j.current),j.current=null)},[]),C=s.useCallback((G,se)=>{b(),S(G==="slide"?se:null),A(G==="doc"?se:null),O(G==="note"?se:null),T(G==="image"?se:null),X(G==="web"?se:null)},[b]),z=s.useCallback(()=>{j.current&&(window.clearTimeout(j.current),j.current=null),S(null),A(null),O(null),T(null),X(null)},[]),B=s.useCallback(()=>{j.current&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{j.current=null,S(null),A(null),O(null),T(null),X(null)},120)},[]),M=s.useRef(null),q=s.useRef(null),ue=s.useRef(null),ye=s.useCallback(()=>{if(!q.current)return;const G=M.current;if(!G)return;const se=document.elementFromPoint(G.x,G.y),ne=se==null?void 0:se.closest("[data-ports-for]");if(ne){const[F,$]=(ne.dataset.portsFor??"").split(":"),P=Number($);if(Number.isFinite(P)&&(F==="slide"||F==="doc"||F==="note"||F==="image"||F==="web")){C(F,P);return}}const de=se==null?void 0:se.closest("[data-slide-id], [data-doc-id], [data-note-id], [data-image-id], [data-web-id]");if(!de){B();return}de.dataset.slideId?C("slide",Number(de.dataset.slideId)):de.dataset.docId?C("doc",Number(de.dataset.docId)):de.dataset.noteId?C("note",Number(de.dataset.noteId)):de.dataset.imageId?C("image",Number(de.dataset.imageId)):de.dataset.webId&&C("web",Number(de.dataset.webId))},[C,B]),ee=s.useCallback(()=>{ue.current&&window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>{ue.current=null,ye()},150)},[ye]);s.useEffect(()=>{q.current=L!=null?{kind:"slide",id:L}:W!=null?{kind:"doc",id:W}:H!=null?{kind:"note",id:H}:ae!=null?{kind:"image",id:ae}:ge!=null?{kind:"web",id:ge}:null},[L,W,H,ae,ge]);const U=s.useCallback(G=>{if(G.kind==="slide"){const de=p.current.find(F=>F.id===G.id);return de?{x:de.x,y:de.y,width:Ke,height:Je}:null}const ne=(G.kind==="doc"?h.current:G.kind==="note"?m.current:G.kind==="image"?g.current:k.current).find(de=>de.id===G.id);return ne?{x:ne.x,y:ne.y,width:ne.width,height:ne.height}:null},[]);s.useEffect(()=>()=>{ue.current&&window.clearTimeout(ue.current),j.current&&window.clearTimeout(j.current)},[]),s.useEffect(()=>{const G=se=>{if(M.current={x:se.clientX,y:se.clientY},we.current)return;const ne=K(se.clientX,se.clientY),de=q.current;if(de){const me=U(de),he=Math.max(t.current,.25),Me=24/he,He=32/he;if(me&&(ne.x<me.x-Me||ne.x>me.x+me.width+Me||ne.y<me.y-He||ne.y>me.y+me.height+Me)){const Ee=document.elementFromPoint(se.clientX,se.clientY);Ee!=null&&Ee.closest("[data-ports-for], [data-item-chrome]")||z()}}const F=ce.current;if(!F.length){J(me=>me==null?me:null);return}const $=90/Math.max(t.current,.25);let P=null;for(const me of[...F].sort((he,Me)=>Number(he.isParent)-Number(Me.isParent))){const he=me.frame;if(ne.x>=he.x&&ne.x<=he.x+he.width&&ne.y>=he.y-$&&ne.y<=he.y+he.height){P=me.id;break}}J(me=>me===P?me:P)};return window.addEventListener("pointermove",G),()=>window.removeEventListener("pointermove",G)},[K,z,U]);const _=s.useCallback(G=>{const se=n.current;if(!se)return;const ne=G??p.current;if(ne.length===0){t.current=.3,e.current={x:120,y:120},pe(),D(30),R(!1);return}const de=Math.min(...ne.map(He=>He.x)),F=Math.min(...ne.map(He=>He.y)),$=Math.max(...ne.map(He=>He.x+Ke)),P=Math.max(...ne.map(He=>He.y+Je)),me=$-de,he=P-F,Me=qn(Math.min(se.clientWidth/me,se.clientHeight/he)*.85,gs,1);t.current=Me,e.current.x=se.clientWidth/2-(de+me/2)*Me,e.current.y=se.clientHeight/2-(F+he/2)*Me,pe(),D(Me*100),R(Me*100<fr)},[pe]);u.current=_;const N=s.useCallback(G=>{const se=n.current;if(!se)return;const ne=qn(G,gs,6),de=se.clientWidth/2,F=se.clientHeight/2;e.current.x=de-(de-e.current.x)*(ne/t.current),e.current.y=F-(F-e.current.y)*(ne/t.current),t.current=ne,pe(),D(ne*100),R(ne*100<fr)},[pe]),Z=s.useRef(null),Q=s.useCallback((G,se=.62)=>{var $;const ne=n.current;if(!ne||G.w<=0||G.h<=0)return;($=Z.current)==null||$.call(Z);const de=qn(Math.min(ne.clientWidth/G.w,ne.clientHeight/G.h)*se,gs,1),F={x:ne.clientWidth/2-(G.x+G.w
4/2)*de,y:ne.clientHeight/2-(G.y+G.h/2)*de};Z.current=Rd({fromPan:{x:e.current.x,y:e.current.y},fromZoom:t.current,toPan:F,toZoom:de,onUpdate:(P,me)=>{e.current=P,t.current=me,pe()},onComplete:()=>{Z.current=null,D(t.current*100),R(t.current*100<fr)}})},[pe]);return c.current=Q,{apply:pe,clientToWorld:K,syncZoomPct:fe,scheduleLodSync:Y,pauseRasterDuringGesture:le,fitAll:_,zoomToCenter:N,focusRect:Q,focusCancelRef:Z,hover:C,hoverKeep:b,hoverClearSoon:B,resyncHoverSoon:ee}}const Cu="#3b82f6",rb="#8b5cf6",Qc=4,so=20,sb=12;function ed(e){return e.mode==="style"?rb:Cu}function Eu(e,t,n,o){const i=Pp(e,n),a=ic(t),l=ic(o);return`M ${e.x} ${e.y} C ${e.x+a.x*i} ${e.y+a.y*i}, ${n.x+l.x*i} ${n.y+l.y*i}, ${n.x} ${n.y}`}function Ru(e,t){const n=Pi(e,t);return Eu(n.from,n.fromSide,n.to,n.toSide)}function ob(e,t){const n={x:e.x+e.width/2,y:e.y+e.height/2},o=oc(n,t),i=$p(e,o),a=oc(t,i);return Eu(i,o,t,a)}function ib({wires:e,rectFor:t,onDeleteWire:n}){const[o,i]=s.useState(null),a=s.useRef(null),l=(d,p,h)=>{const m=d.ownerSVGElement,g=m==null?void 0:m.getScreenCTM();if(!m||!g)return null;const k=m.createSVGPoint();k.x=p,k.y=h;const y=k.matrixTransform(g.inverse());let f;try{f=d.getTotalLength()}catch{return null}if(!f)return null;let I=0,w=0,x=1/0;const D=60;for(let j=0;j<=D;j++){const S=d.getPointAtLength(f*j/D),A=S.x-y.x,O=S.y-y.y,T=A*A+O*O;T<x&&(x=T,I=S.x,w=S.y)}const R=Math.hypot(g.a,g.b)||1;return{x:I,y:w,screenDist:Math.sqrt(x)*R}},u=(d,p,h,m)=>{a.current={id:d,el:p};const g=l(p,h,m);g&&i({id:d,x:g.x,y:g.y})};s.useEffect(()=>{const p=h=>{const m=a.current;if(!m)return;const g=l(m.el,h.clientX,h.clientY);if(!g||g.screenDist>18){a.current=null,i(k=>(k==null?void 0:k.id)===m.id?null:k);return}i({id:m.id,x:g.x,y:g.y})};return window.addEventListener("pointermove",p),()=>window.removeEventListener("pointermove",p)},[]);const c=o?e.find(d=>d.id===o.id):void 0;return r.jsxs(r.Fragment,{children:[r.jsxs("svg",{"data-birtvy-wire-layer":!0,style:{position:"absolute",left:0,top:0,width:1,height:1,overflow:"visible",pointerEvents:"none",zIndex:0},children:[e.map(d=>{const p=t(d.from),h=t(d.to);if(!p||!h)return null;const m=Ru(p,h);return r.jsxs("g",{children:[r.jsx("path",{"data-wire-id":d.id,d:m,fill:"none",stroke:ed(d),strokeWidth:Qc,strokeLinecap:"round",opacity:(o==null?void 0:o.id)===d.id?1:.5,vectorEffect:"non-scaling-stroke"}),r.jsx("path",{d:m,fill:"none",stroke:"transparent",strokeWidth:28,vectorEffect:"non-scaling-stroke",style:{pointerEvents:"stroke",cursor:"pointer"},onPointerEnter:g=>u(d.id,g.currentTarget,g.clientX,g.clientY)})]},d.id)}),r.jsx("path",{"data-wire-preview":!0,fill:"none",stroke:Cu,strokeWidth:Qc,strokeLinecap:"round",opacity:.8,vectorEffect:"non-scaling-stroke",style:{display:"none"}})]}),o&&c?r.jsx("button",{type:"button","aria-label":"Remove connection",className:"absolute flex items-center justify-center rounded-full text-white shadow-[0_2px_8px_rgba(9,9,11,0.2)] transition-[filter] hover:brightness-110",style:{left:o.x-so/2,top:o.y-so/2,width:so,height:so,backgroundColor:ed(c),transform:"scale(var(--sel-scale, 1))",transformOrigin:"center",zIndex:1010},onPointerDown:d=>d.stopPropagation(),onClick:()=>{a.current=null,i(null),n(c.id)},children:r.jsx(At,{name:"close",size:sb,className:"text-white"})},`del-${c.id}`):null]})}function Mu(e){const t=s.useRef(null);return s.useEffect(()=>{const n=l=>{(!t.current||!t.current.contains(l.target))&&e()},o=()=>e(),i=l=>{l.key==="Escape"&&e()},a=window.setTimeout(()=>{window.addEventListener("pointerdown",n,!0),window.addEventListener("wheel",o,{passive:!0}),window.addEventListener("blur",o)},0);return window.addEventListener("keydown",i),()=>{window.clearTimeout(a),window.removeEventListener("pointerdown",n,!0),window.removeEventListener("wheel",o),window.removeEventListener("blur",o),window.removeEventListener("keydown",i)}},[e]),t}function ab({client:e,onPick:t,onClose:n}){const o=Mu(n),i=[{key:"style",label:"Reference style to slide",icon:"color-wheel"},{key:"image",label:"Reference image to slide",icon:"image"}],a=Math.min(e.x,window.innerWidth-300),l=Math.min(e.y,window.innerHeight-120);return r.jsx("div",{ref:o,className:"fixed z-[1500] min-w-[260px] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-card)] p-1.5 shadow-[var(--shadow-modal-md)]",style:{left:a,top:l,transformOrigin:"top left"},onPointerDown:u=>u.stopPropagation(),onContextMenu:u=>u.preventDefault(),children:i.map(u=>r.jsxs("button",{type:"button",className:"flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm font-medium text-[var(--color-text-default)] transition-colors hover:bg-[var(--color-subtle)]",onClick:()=>{t(u.key),n()},children:[r.jsx(At,{name:u.icon,size:18,className:"shrink-0 text-[var(--color-icon-default-muted)]"}),u.label]},u.key))})}function lb({sourceKind:e,client:t,onCreate:n,onClose:o}){const i=Mu(o),a=e==="image"?[{key:"style",label:"Reference style to slide",icon:"color-wheel",mode:"style"},{key:"image",label:"Reference image to slide",icon:"image",mode:"image"}]:[{key:"slide",label:"New slide",icon:"canvas"}],l=Math.min(t.x,window.innerWidth-300),u=Math.min(t.y,window.innerHeight-120);return r.jsx("div",{ref:i,className:"fixed z-[1500] min-w-[240px] overflow-hidden rounded-xl border border-[var(--color-border-default)] bg-[var(--color-card)] p-1.5 shadow-[var(--shadow-modal-md)]",style:{left:l,top:u,transformOrigin:"top left"},onPointerDown:c=>c.stopPropagation(),onContextMenu:c=>c.preventDefault(),children:a.map(c=>r.jsxs("button",{type:"button",className:"flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm font-medium text-[var(--color-text-default)] transition-colors hover:bg-[var(--color-subtle)]",onClick:()=>{n(c.mode),o()},children:[r.jsx(At,{name:c.icon,size:18,className:"shrink-0 text-[var(--color-icon-default-muted)]"}),c.label]},c.key))})}function td(e,t,n,o,i,a,l,u,c){if(a)return Gy(e,t,n,o,i);const d=xu(e,t,n,o,i),p=c?Ht:fa,h=c?Ht:ha;return vo(d,l.x,l.y,u??d.length,p,h)}function cb({store:e,itemDragRef:t,snapSessionRef:n,snapVGuideRef:o,snapHGuideRef:i,worldRef:a,groupViewsRef:l,selectedGroupIdsRef:u,setDraggingGroupId:c,rectForRef:d,placeClones:p,itemsForIds:h,arrangeDeckRows:m,glActiveRef:g,glQuadIdsRef:k,glDragQuadsRef:y}){const{setSlides:f,slidesRef:I,setDocs:w,docsRef:x,setNotes:D,notesRef:
4R,setImages:j,imagesRef:S,setWebs:A,websRef:O,setGroups:T,groupsRef:X,wiresRef:L,setSelectedIds:W,selectedIdsRef:H,setSelectedDocIds:ae,selectedDocIdsRef:ge,setSelectedNoteIds:J,selectedNoteIdsRef:ce,setSelectedImageIds:we,selectedImageIdsRef:ve,setSelectedWebIds:oe,selectedWebIdsRef:pe,pan:K,zoom:fe,viewportRef:ie,bringToFront:Y,requestSave:re}=e,le=s.useCallback((ee,U)=>{W(_=>{const N=new Set(_);return U?N.has(ee)?N.delete(ee):N.add(ee):(N.clear(),N.add(ee)),N})},[]),b=s.useCallback((ee,U,_)=>{var se,ne,de,F,$,P;n.current=Yn;const N=ee==="slide"?H.current.has(U):ee==="doc"?ge.current.has(U):ee==="note"?ce.current.has(U):ee==="image"?ve.current.has(U):pe.current.has(U),Z=N&&u.current.size>0;if(N&&!Z)t.current={ids:{slide:new Set(H.current),doc:new Set(ge.current),note:new Set(ce.current),image:new Set(ve.current),web:new Set(pe.current)},startX:_.clientX,startY:_.clientY,moved:!1,alt:_.altKey};else{W(ee==="slide"?new Set([U]):new Set),ae(ee==="doc"?new Set([U]):new Set),J(ee==="note"?new Set([U]):new Set),we(ee==="image"?new Set([U]):new Set),oe(ee==="web"?new Set([U]):new Set);const me=he=>new Set(ee===he?[U]:[]);t.current={ids:{slide:me("slide"),doc:me("doc"),note:me("note"),image:me("image"),web:me("web")},startX:_.clientX,startY:_.clientY,moved:!1,alt:_.altKey}}const Q=t.current,G=Q?Q.ids.slide.size+Q.ids.doc.size+Q.ids.note.size+Q.ids.image.size+Q.ids.web.size:0;if(Q&&Q.groupId==null&&G===1){const me=ee==="web"?void 0:ee==="slide"?(se=I.current.find(Me=>Me.id===U))==null?void 0:se.groupId:ee==="doc"?(ne=x.current.find(Me=>Me.id===U))==null?void 0:ne.groupId:ee==="note"?(de=R.current.find(Me=>Me.id===U))==null?void 0:de.groupId:(F=S.current.find(Me=>Me.id===U))==null?void 0:F.groupId,he=me!=null?l.current.find(Me=>Me.id===me):void 0;if(ee!=="web"&&me!=null&&he&&he.memberRects.length>=2&&dr(X.current.find(Me=>Me.id===me),he.slidesOnly)){const Me=(($=X.current.find(He=>He.id===me))==null?void 0:$.cols)??kr;Q.reorderGroupId=me,Q.reorderKey=Ye(ee,U),Q.reorderMembers=he.memberRects,Q.reorderSlidesOnly=he.slidesOnly,Q.reorderIsCluster=he.parentId!=null,Q.reorderOrigin={x:he.frame.x+Ht,y:he.frame.y+Ht},Q.reorderFrame=he.frame,Q.reorderCols=(P=X.current.find(He=>He.id===me))==null?void 0:P.cols,Q.reorderSlots=he.slidesOnly?By(he.memberRects,Me,In,Oy(he.memberRects)):Fy(he.memberRects),c(me)}}},[]),C=s.useCallback((ee,U)=>{ee(_=>{const N=new Set(_);return N.has(U)?N.delete(U):N.add(U),N})},[]),z=s.useCallback((ee,U)=>{if(U.button===0){if(U.stopPropagation(),U.shiftKey){le(ee,!0);return}b("slide",ee,U)}},[le,b]),B=s.useCallback((ee,U)=>{if(U.button===0){if(U.stopPropagation(),U.shiftKey){C(ae,ee);return}b("doc",ee,U)}},[b,C]),M=s.useCallback((ee,U)=>{if(U.button===0){if(U.stopPropagation(),U.shiftKey){C(J,ee);return}b("note",ee,U)}},[b,C]),q=s.useCallback((ee,U)=>{if(U.button===0){if(U.stopPropagation(),U.shiftKey){C(we,ee);return}b("image",ee,U)}},[b,C]),ue=s.useCallback((ee,U)=>{if(U.button===0){if(U.stopPropagation(),U.shiftKey){C(oe,ee);return}b("web",ee,U)}},[b,C]),ye=s.useCallback((ee,U)=>{var $;if(U.button!==0)return;U.stopPropagation();const _=new Set([ee,...X.current.filter(P=>P.parentId===ee).map(P=>P.id)]),N=I.current.filter(P=>P.groupId!=null&&_.has(P.groupId)).map(P=>P.id),Z=x.current.filter(P=>P.groupId!=null&&_.has(P.groupId)).map(P=>P.id),Q=R.current.filter(P=>P.groupId!=null&&_.has(P.groupId)).map(P=>P.id),G=S.current.filter(P=>P.groupId!=null&&_.has(P.groupId)).map(P=>P.id);if(!N.length&&!Z.length&&!Q.length&&!G.length)return;if(U.shiftKey||U.metaKey||U.ctrlKey){const P=(Me,He)=>He.every(Ee=>Me.has(Ee)),me=P(H.current,N)&&P(ge.current,Z)&&P(ce.current,Q)&&P(ve.current,G),he=(Me,He)=>{const Ee=new Set(Me);for(const qe of He)me?Ee.delete(qe):Ee.add(qe);return Ee};W(Me=>he(Me,N)),ae(Me=>he(Me,Z)),J(Me=>he(Me,Q)),we(Me=>he(Me,G));return}if(c(ee),W(new Set(N)),ae(new Set(Z)),J(new Set(Q)),we(new Set(G)),n.current=Yn,t.current={ids:{slide:new Set(N),doc:new Set(Z),note:new Set(Q),image:new Set(G),web:new Set},startX:U.clientX,startY:U.clientY,moved:!1,alt:U.altKey,groupId:ee,frameGids:[..._]},U.altKey)return;const se=($=X.current.find(P=>P.id===ee))==null?void 0:$.parentId,ne=se!=null?X.current.find(P=>P.id===se):void 0;if(!ne||!dr(ne,!1))return;const de=Iu(l.current.filter(P=>P.parentId===ne.id),I.current.filter(P=>P.groupId===ne.id));if(de.length<2||!de.some(P=>P.key===`cluster:${ee}`))return;const F=t.current;F&&(F.deckReorderParentId=ne.id,F.deckReorderKey=`cluster:${ee}`,F.deckReorderItems=de,F.deckReorderSlots=qy(de),F.deckReorderOrigin={x:Math.min(...de.map(P=>P.x)),y:Math.min(...de.map(P=>P.y-(P.labelBand?Wt:0)))},F.deckReorderCols=ne.cols??kr)},[]);return s.useEffect(()=>{const ee=(F,$)=>{var P;return(P=a.current)==null?void 0:P.querySelector(`[data-${F}-id="${$}"]`)},U=F=>{var $;return($=a.current)==null?void 0:$.querySelectorAll(`[data-gen-overlay="${F}"]`)},_=F=>{var $;return($=a.current)==null?void 0:$.querySelectorAll(`[data-web-label="${F}"]`)},N=(F,$)=>{var P;return(P=a.current)==null?void 0:P.querySelectorAll(`[data-item-bar="${F}:${$}"]`)},Z=["slide","doc","note","image","web"],Q=F=>{let $=1/0,P=1/0,me=-1/0,he=-1/0;for(const Me of Z)for(const He of F[Me]){const Ee=d({kind:Me,id:He});Ee&&($=Math.min($,Ee.x),P=Math.min(P,Ee.y),me=Math.max(me,Ee.x+Ee.width),he=Math.max(he,Ee.y+Ee.height))}return $===1/0?null:{x:$,y:P,width:me-$,height:he-P}},G=F=>{const $=ie.current,P=fe.current,me=-K.current.x/P,he=-K.current.y/P,Me=(($==null?void 0:$.clientWidth)??0)/P,He=(($==null?void 0:$.clientHeight)??0)/P,Ee=[],qe=Ae=>{Ae.x<me+Me&&Ae.x+Ae.width>me&&Ae.y<he+He&&Ae.y+Ae.height>he&&Ee.push(Ae)};for(const Ae of I.current)F.slide.has(Ae.id)||qe({x:Ae.x,y:Ae.y,width:Ke,height:Je});for(const Ae of x.current)F.doc.has(Ae.id)||qe({x:Ae.x,y:Ae.y,width:Ae.width,height:Ae.height});for(const Ae of R.current)F.note.has(Ae.id)||qe({x:Ae.x,y:Ae.y,width:Ae.width,height:Ae.height});for(const Ae of S.current)F.image.has(Ae.id)||qe({x:Ae.x,y:Ae.y,width:Ae.width,height:Ae.height});for(const Ae of O.current)F.web.has(Ae.id)||qe({x:Ae.x,y:Ae.y,width:Ae.width,height:Ae.height});return Ee},se=(F,$)=>{const P=o.current,me=i.current;P&&(F?(P.style.display="block",P.style.left=`${F.x}px`,P.style.top=`${F.y1}px`,P.style.height=`${F.y2-F.y1}px`):P.style.display="none"),me&&($?(me.style.display="block",me.style.top=`${$.y}px`,me.style.left=`${$.x1}px`,me.style.width=`${$.x2-$.x1}px`):me.style.display="none")},ne=F=>{var Ee,qe,Ae,jt,kt,Ge,Qe,ht,xt;const $=t.current;if(!$)return;const P=(F.clientX-$.startX)/fe.current,me=(F.clientY-$.startY)/fe.current;if(!$.moved&&(Math.abs(F.clientX-$.startX)>3||Math.abs(F.clientY-$.startY)>3)){if($.moved=!0,$.alt){const Ue=p(h($.ids),0,0);if($.ids={slide:new Set(Ue.slide),doc:new Set(Ue.doc),note:new Set(Ue.note),image:new Set(Ue.image),web:new Set(Ue.web)},$.groupId!=null){const _e=Ue.groups.get($.groupId);$.groupId=_e,c(_e??null)}$.alt=!1}const Xe=[];for(const Ue of Z)for(const _e of $.ids[Ue])Xe.push(`${Ue}:${_e}`);Y(Xe)}let he=P,Me=me;if($.moved&&$.reorderGroupId==null&&$.deckReorderParentId==null&&!(F.metaKey||F.ctrlKey)){if($.snapBox||($.snapBox=Q($.ids)),$.snapBox){const Xe=hg($.snapBox,P,me,G($.ids),fe.current,n.current);n.current=Xe.session,he=Xe.dx,Me=Xe.dy,se(Xe.v,Xe.h)}}else $.moved&&(n.current=Yn,se(null,null));$.lastDx=he,$.lastDy=Me;for(const Xe of Z)for(const Ue of $.ids[Xe]){const _e=ee(Xe,Ue);_e&&(_e.style.transform=`translate(${he}px, ${Me}px)`),(Ee=N(Xe,Ue))==null||Ee.forEach(yt=>{yt.style.transform=`translate(${he}px, ${Me}px)`})}if($.groupId!=null)for(const Xe of $.frameGids??[$.groupId])(qe=a.current)==null||qe.querySelectorAll(`[data-group-frame="${Xe}"]`).forEach(Ue=>{Ue.style.transform=`translate(${he}px, ${Me}px)`});for(const Xe of $.ids.slide)(Ae=U(Xe))==null||Ae.forEach(Ue=>{Ue.style.transform=`translate(${he}px, ${Me}px)`});for(const Xe of $.ids.web)(jt=_(Xe))==null||jt.forEach(Ue=>{Ue.style.transform=`translate(${he}px, ${Me}px)`});if($.reorderGroupId!=null&&$.reorderSlots&&$.reorderMembers&&$.reorderKey){const Xe=$.reorderMembers,Ue=Xe.find(Nt=>Ye(Nt.kind,Nt.id)===$.reorderKey),_e=$.reorderFrame,yt=Ue?Ue.x+he+Ue.width/2:0,bt=Ue?Ue.y+Me+Ue.height/2:0,Rt=!_e||yt>=_e.x&&yt<=_e.x+_e.width&&bt>=_e.y&&bt<=_e.y+_e.height;if(Ue&&Xe.length>=2&&!Rt)for(const Nt of $.glidingIds??[]){const{kind:vt,id:je}=bs(Nt),Oe=ee(vt,je);Oe&&(Oe.style.transition=to,Oe.style.transform="translate(0px, 0px)")}else if(Ue&&Xe.length>=2){const Nt=td(Xe,$.reorderKey,Ue.x+he,Ue.y+Me,$.reorderSlots,$.reorderSlidesOnly??!0,$.reorderOrigin??{x:0,y:0},$.reorderCols,$.reorderIsCluster??!1),vt=$.glidingIds??($.glidingIds=new Set);for(const je of Xe){const Oe=Ye(je.kind,je.id);if(Oe===$.reorderKey)continue;const tt=ee(je.kind,je.id),ot=Nt.get(Oe);!tt||!ot||(tt.style.transition=to,tt.style.transform=`translate(${ot.x-je.x}px, ${ot.y-je.y}px)`,vt.add(Oe))}}}if($.deckReorderParentId!=null&&$.deckReorderItems&&$.deckReorderSlots&&$.deckReorderKey&&$.deckReorderOrigin){const Xe=$.deckReorderItems,Ue=Xe.find(_e=>_e.key===$.deckReorderKey);if(Ue&&Xe.length>=2){const _e=Ue.labelBand?Wt:0,yt=Zc(Xe,$.deckReorderKey,Ue.x+he,Ue.y-_e+Me,$.deckReorderSlots),bt=ku(yt,$.deckReorderCols??kr,$.deckReorderOrigin.x,$.deckReorderOrigin.y),Rt=$.deckGlidingKeys??($.deckGlidingKeys=new Set),Nt=$.deckGlidingGids??($.deckGlidingGids=new Set);for(const vt of Xe){if(vt.key===$.deckReorderKey)continue;const je=bt.get(vt.key);if(!je)continue;const Oe=`translate(${je.x-vt.x}px, ${je.y-vt.y}
4px)`,tt=(ot,mt)=>{const dt=ee(ot,mt);dt&&(dt.style.transition=to,dt.style.transform=Oe,Rt.add(Ye(ot,mt)))};if(vt.kind==="slide"){tt("slide",vt.id);continue}for(const ot of((kt=l.current.find(mt=>mt.id===vt.id))==null?void 0:kt.memberRects)??[])tt(ot.kind,ot.id);(Ge=a.current)==null||Ge.querySelectorAll(`[data-group-frame="${vt.id}"]`).forEach(ot=>{ot.style.transition=to,ot.style.transform=Oe}),Nt.add(vt.id)}}}(Qe=a.current)==null||Qe.querySelectorAll("[data-ports-for]").forEach(Xe=>{const[Ue,_e]=(Xe.dataset.portsFor??"").split(":");(Ue==="slide"||Ue==="doc"||Ue==="note"||Ue==="image"||Ue==="web")&&$.ids[Ue].has(Number(_e))&&(Xe.style.display="none")});const He=Xe=>$.ids[Xe.kind].has(Xe.id);for(const Xe of L.current){const Ue=He(Xe.from),_e=He(Xe.to);if(!Ue&&!_e)continue;const yt=d(Xe.from),bt=d(Xe.to);if(!yt||!bt)continue;const Rt=Ue?{...yt,x:yt.x+he,y:yt.y+Me}:yt,Nt=_e?{...bt,x:bt.x+he,y:bt.y+Me}:bt;(xt=(ht=a.current)==null?void 0:ht.querySelector(`[data-wire-id="${Xe.id}"]`))==null||xt.setAttribute("d",Ru(Rt,Nt))}if(g.current&&($.ids.slide.size>0||$.ids.image.size>0)){const Xe=k.current,Ue=new Map;for(let _e=0;_e<Xe.length;_e++){const yt=Xe[_e];(yt.kind==="slide"?$.ids.slide.has(yt.id):$.ids.image.has(yt.id))&&Ue.set(_e,{dx:he,dy:Me})}Ue.size>0&&y.current(Ue)}},de=F=>{var He,Ee,qe,Ae,jt,kt;const $=t.current;if(!$)return;t.current=null;const P=$.lastDx??(F.clientX-$.startX)/fe.current,me=$.lastDy??(F.clientY-$.startY)/fe.current;se(null,null),n.current=Yn;for(const Ge of Z)for(const Qe of $.ids[Ge]){const ht=ee(Ge,Qe);ht&&(ht.style.transform=""),(He=N(Ge,Qe))==null||He.forEach(xt=>{xt.style.transform=""})}if($.groupId!=null){for(const Ge of $.frameGids??[$.groupId])(Ee=a.current)==null||Ee.querySelectorAll(`[data-group-frame="${Ge}"]`).forEach(Qe=>{Qe.style.transform=""});c(null)}for(const Ge of $.ids.slide)(qe=U(Ge))==null||qe.forEach(Qe=>{Qe.style.transform=""});for(const Ge of $.ids.web)(Ae=_(Ge))==null||Ae.forEach(Qe=>{Qe.style.transform=""});if($.glidingIds)for(const Ge of $.glidingIds){const{kind:Qe,id:ht}=bs(Ge),xt=ee(Qe,ht);xt&&(xt.style.transition="",xt.style.transform="")}let he=!1;const Me=()=>{var Ge;for(const Qe of $.deckGlidingKeys??[]){const{kind:ht,id:xt}=bs(Qe),Xe=ee(ht,xt);Xe&&(Xe.style.transition="",Xe.style.transform="")}for(const Qe of $.deckGlidingGids??[])(Ge=a.current)==null||Ge.querySelectorAll(`[data-group-frame="${Qe}"]`).forEach(ht=>{ht.style.transition="",ht.style.transform=""})};if($.reorderGroupId!=null&&c(null),(jt=a.current)==null||jt.querySelectorAll("[data-ports-for]").forEach(Ge=>{Ge.style.transform="",Ge.style.display=""}),$.moved){const Ge=l.current,Qe=new Set([...[...$.ids.slide].map(Re=>Ye("slide",Re)),...[...$.ids.doc].map(Re=>Ye("doc",Re)),...[...$.ids.note].map(Re=>Ye("note",Re)),...[...$.ids.image].map(Re=>Ye("image",Re))]);let ht=new Map;if($.groupId==null){const Re=[...I.current.filter(Ne=>$.ids.slide.has(Ne.id)).map(Ne=>({kind:"slide",id:Ne.id,x:Ne.x+P,y:Ne.y+me,width:Ke,height:Je,groupId:Ne.groupId})),...x.current.filter(Ne=>$.ids.doc.has(Ne.id)).map(Ne=>({kind:"doc",id:Ne.id,x:Ne.x+P,y:Ne.y+me,width:Ne.width,height:Ne.height,groupId:Ne.groupId})),...R.current.filter(Ne=>$.ids.note.has(Ne.id)).map(Ne=>({kind:"note",id:Ne.id,x:Ne.x+P,y:Ne.y+me,width:Ne.width,height:Ne.height,groupId:Ne.groupId})),...S.current.filter(Ne=>$.ids.image.has(Ne.id)).map(Ne=>({kind:"image",id:Ne.id,x:Ne.x+P,y:Ne.y+me,width:Ne.width,height:Ne.height,groupId:Ne.groupId}))];if(ht=wu(Ge,Re),$.reorderGroupId!=null&&$.reorderKey){const Ne=$.reorderFrame,Be=Re.find(Ve=>Ye(Ve.kind,Ve.id)===$.reorderKey),ct=Be?Be.x+Be.width/2:0,De=Be?Be.y+Be.height/2:0;(!Ne||!Be||ct>=Ne.x&&ct<=Ne.x+Ne.width&&De>=Ne.y&&De<=Ne.y+Ne.height)&&ht.delete($.reorderKey)}}let xt=$.ids.doc.size?x.current.map(Re=>{if(!$.ids.doc.has(Re.id))return Re;const Ne=ht.get(Ye("doc",Re.id));return{...Re,x:Re.x+P,y:Re.y+me,...Ne!==void 0?{groupId:Ne}:{}}}):x.current,Xe=$.ids.note.size?R.current.map(Re=>{if(!$.ids.note.has(Re.id))return Re;const Ne=ht.get(Ye("note",Re.id));return{...Re,x:Re.x+P,y:Re.y+me,...Ne!==void 0?{groupId:Ne}:{}}}):R.current,Ue=$.ids.image.size?S.current.map(Re=>{if(!$.ids.image.has(Re.id))return Re;const Ne=ht.get(Ye("image",Re.id));return{...Re,x:Re.x+P,y:Re.y+me,...Ne!==void 0?{groupId:Ne}:{}}}):S.current;const _e=$.ids.web.size?O.current.map(Re=>$.ids.web.has(Re.id)?{...Re,x:Re.x+P,y:Re.y+me}:Re):O.current,yt=Re=>xt.some(Ne=>Ne.groupId===Re)||Xe.some(Ne=>Ne.groupId===Re)||Ue.some(Ne=>Ne.groupId===Re),bt=Re=>{var Ne;return dr(X.current.find(Be=>Be.id===Re),((Ne=Ge.find(Be=>Be.id===Re))==null?void 0:Ne.slidesOnly)??!1)},Rt=$.reorderGroupId,Nt=$.reorderKey!=null?ht.get($.reorderKey):void 0,vt=$.groupId==null&&Rt!=null&&$.reorderKey!=null&&$.reorderSlots!=null&&bt(Rt)&&(Nt===void 0||Nt===Rt);let je=!1,Oe=I.current;if($.ids.slide.size){const Re=$.ids.slide;if($.reorderGroupId,$.reorderSlots,Re.size===1&&[...Re][0],Oe=Oe.map(Ne=>{if(!Re.has(Ne.id))return Ne;const Be=$.groupId==null?ht.get(Ye("slide",Ne.id)):void 0;return{...Ne,x:Ne.x+P,y:Ne.y+me,...Be!==void 0?{groupId:Be}:{}}}),$.groupId==null){const Ne=ct=>{var De;return((De=X.current.find(Ve=>Ve.id===ct))==null?void 0:De.cols)??kr},Be=new Set;for(const ct of I.current)Re.has(ct.id)&&ct.groupId!=null&&Be.add(ct.groupId);for(const ct of Oe)Re.has(ct.id)&&ct.groupId!=null&&Be.add(ct.groupId);for(const ct of Be)vt&&ct===Rt||yt(ct)||bt(ct)&&(Oe=Xi(Oe,ct,Ne(ct),In))}}if(vt&&Rt!=null&&$.reorderSlots&&$.reorderKey){const Re=[...Oe.filter(Be=>Be.groupId===Rt).map(Be=>({kind:"slide",id:Be.id,x:Be.x,y:Be.y,width:Ke,height:Je,groupId:Be.groupId})),...xt.filter(Be=>Be.groupId===Rt).map(Be=>({kind:"doc",id:Be.id,x:Be.x,y:Be.y,width:Be.width,height:Be.height,groupId:Be.groupId})),...Xe.filter(Be=>Be.groupId===Rt).map(Be=>({kind:"note",id:Be.id,x:Be.x,y:Be.y,width:Be.width,height:Be.height,groupId:Be.groupId})),...Ue.filter(Be=>Be.groupId===Rt).map(Be=>({kind:"image",id:Be.id,x:Be.x,y:Be.y,width:Be.width,height:Be.height,groupId:Be.groupId}))],Ne=Re.find(Be=>
4Ye(Be.kind,Be.id)===$.reorderKey);if(Ne){const Be=td(Re,$.reorderKey,Ne.x,Ne.y,$.reorderSlots,$.reorderSlidesOnly??!0,$.reorderOrigin??{x:0,y:0},$.reorderCols,$.reorderIsCluster??!1),ct=(De,Ve)=>Be.get(Ye(De,Ve));Oe=Oe.map(De=>{const Ve=ct("slide",De.id);return Ve?{...De,x:Ve.x,y:Ve.y}:De}),xt=xt.map(De=>{const Ve=ct("doc",De.id);return Ve?{...De,x:Ve.x,y:Ve.y}:De}),Xe=Xe.map(De=>{const Ve=ct("note",De.id);return Ve?{...De,x:Ve.x,y:Ve.y}:De}),Ue=Ue.map(De=>{const Ve=ct("image",De.id);return Ve?{...De,x:Ve.x,y:Ve.y}:De}),je=!0}}const tt=new Set([...ht.values()].filter(Re=>Re!=null)),ot=new Set(Ge.filter(Re=>Re.allItemKeys.length>0&&Re.allItemKeys.every(Ne=>Qe.has(Ne))).map(Re=>Re.id)),mt=new Set,dt=new Set;if($.groupId==null)for(const Re of X.current){if(!Re.snap||ot.has(Re.id))continue;if(X.current.some(Ve=>Ve.parentId===Re.id)){dr(Re,!1)&&dt.add(Re.id);continue}if(vt&&Re.id===Rt)continue;const Ne=[...ht.values()].includes(Re.id),Be=Ge.find(Ve=>Ve.id===Re.id),ct=!!(Be!=null&&Be.memberRects.some(Ve=>{const Ct=Ye(Ve.kind,Ve.id);return Qe.has(Ct)&&(ht.get(Ct)??Re.id)===Re.id})),De=!!(Be!=null&&Be.memberRects.some(Ve=>{const Ct=Ye(Ve.kind,Ve.id),Mt=ht.get(Ct);return Qe.has(Ct)&&Mt!==void 0&&Mt!==Re.id}));(Ne||ct||De)&&mt.add(Re.id)}const $e=new Map;let lt;const it=new Set;if($.groupId!=null){const Re=Ge.find(De=>De.id===$.groupId),Ne=Re?Ky(Ge,$.groupId,{x:Re.frame.x+P,y:Re.frame.y+me,width:Re.frame.width,height:Re.frame.height}):void 0,Be=((kt=X.current.find(De=>De.id===$.groupId))==null?void 0:kt.parentId)??null;Ne!==void 0&&(lt={gid:$.groupId,parentId:Ne},Be!=null&&it.add(Be),Ne!=null&&it.add(Ne));for(const De of new Set([Be,Ne??Be])){if(De==null)continue;const Ve=X.current.find(Ct=>Ct.id===De);Ve&&dr(Ve,!1)&&dt.add(Ve.id)}const ct=Be!=null?X.current.find(De=>De.id===Be):void 0;if(ct&&Ne===void 0&&dr(ct,!1)&&$.deckReorderParentId===ct.id&&$.deckReorderItems&&$.deckReorderSlots&&$.deckReorderKey&&$.deckReorderOrigin){const De=$.deckReorderItems.find(Ve=>Ve.key===$.deckReorderKey);if(De){const Ve=De.labelBand?Wt:0,Ct=Zc($.deckReorderItems,$.deckReorderKey,De.x+P,De.y-Ve+me,$.deckReorderSlots);$e.set(ct.id,{order:Ct.map(Mt=>Mt.key),origin:$.deckReorderOrigin})}}}for(const Re of mt){const Ne=X.current.find(Te=>Te.id===Re),Be=Ge.find(Te=>Te.id===Re);if(!Ne||!Be)continue;const ct=[...Oe.filter(Te=>Te.groupId===Re).map(Te=>({kind:"slide",id:Te.id,x:Te.x,y:Te.y,width:Ke,height:Je})),...xt.filter(Te=>Te.groupId===Re).map(Te=>({kind:"doc",id:Te.id,x:Te.x,y:Te.y,width:Te.width,height:Te.height})),...Xe.filter(Te=>Te.groupId===Re).map(Te=>({kind:"note",id:Te.id,x:Te.x,y:Te.y,width:Te.width,height:Te.height})),...Ue.filter(Te=>Te.groupId===Re).map(Te=>({kind:"image",id:Te.id,x:Te.x,y:Te.y,width:Te.width,height:Te.height}))],De=Be.frame.x+Ht,Ve=Be.frame.y+Ht;let Ct;if(Ne.parentId!=null)Ct=vu(ct,De,Ve);else{const Te=(Tt,$t)=>Tt.y-$t.y||Tt.x-$t.x,ut=[...ct].sort(Te);Ct=vo(ut,De,Ve,Ne.cols??ut.length)}const Mt=(Te,ut)=>Te.map(Tt=>{if(Tt.groupId!==Re)return Tt;const $t=Ct.get(Ye(ut,Tt.id));return $t&&(Tt.x!==$t.x||Tt.y!==$t.y)?{...Tt,x:$t.x,y:$t.y}:Tt});Oe=Mt(Oe,"slide"),xt=Mt(xt,"doc"),Xe=Mt(Xe,"note"),Ue=Mt(Ue,"image")}let Dt=!1;const en=Re=>[...Oe.filter(Ne=>Ne.groupId===Re).map(Ne=>({x:Ne.x,y:Ne.y,width:Ke,height:Je})),...xt.filter(Ne=>Ne.groupId===Re),...Xe.filter(Ne=>Ne.groupId===Re),...Ue.filter(Ne=>Ne.groupId===Re)],Bt=lt?X.current.map(Re=>Re.id===lt.gid?{...Re,parentId:lt.parentId}:Re):X.current;lt&&(Dt=!0);const tn=Re=>Bt.some(Ne=>Ne.parentId===Re),sn=Bt.map(Re=>{if(ot.has(Re.id)&&Re.x!=null&&Re.y!=null)return Dt=!0,{...Re,x:Math.round(Re.x+P),y:Math.round(Re.y+me)};if((tt.has(Re.id)||mt.has(Re.id)||je&&Re.id===Rt)&&!tn(Re.id)){const Be=cn(en(Re.id));if(Be)return Dt=!0,an(Re,Be)}return Re}),dn=new Set([...Bt.filter(Re=>Re.parentId!=null&&(tt.has(Re.id)||mt.has(Re.id))).map(Re=>Re.parentId),...it]),Jt=sn.map(Re=>{const Ne=sn.filter(De=>De.parentId===Re.id);if(!Ne.length||ot.has(Re.id)||!tt.has(Re.id)&&!dn.has(Re.id))return Re;const Be=Ne.map(De=>De.x!=null&&De.y!=null&&De.width!=null&&De.height!=null?{x:De.x,y:De.y,width:De.width,height:De.height}:cn(en(De.id))).filter(De=>!!De).map(De=>({x:De.x,y:De.y-Wt,width:De.width,height:De.height+Wt})),ct=cn([...en(Re.id),...Be]);return ct?(Dt=!0,an(Re,ct)):Re});if(($.ids.slide.size||mt.size||je)&&f(Oe),($.ids.doc.size||mt.size||je)&&w(xt),($.ids.note.size||mt.size||je)&&D(Xe),($.ids.image.size||mt.size||je)&&j(Ue),$.ids.web.size&&A(_e),Dt&&T(Jt),dt.size){const Re=[...dt];he=!0,setTimeout(()=>{var Ne;for(const Be of Re)m(Be,((Ne=X.current.find(ct=>ct.id===Be))==null?void 0:Ne.cols)??kr,$e.get(Be));Me()})}re()}he||Me()};return window.addEventListener("pointermove",ne),window.addEventListener("pointerup",de),()=>{window.removeEventListener("pointermove",ne),window.removeEventListener("pointerup",de)}},[re,d,p,h,Y,m]),{armItemDrag:b,onCardPointerDown:z,onDocPointerDown:B,onNotePointerDown:M,onImagePointerDown:q,onWebPointerDown:ue,onGroupHeaderPointerDown:ye}}function db({store:e,demoRef:t,spaceRef:n,overlayRef:o,marqueeRectRef:i,marqueeSessionRef:a,setMarqueeActive:l,hiddenMemberKeysRef:u,lodRef:c,setLod:d,apply:p,syncZoomPct:h,scheduleLodSync:m,pauseRasterDuringGesture:g,resyncHoverSoon:k}){const{viewportRef:y,pan:f,zoom:I,clientToWorld:w,slidesRef:x,docsRef:D,notesRef:
4R,imagesRef:j,websRef:S,selectedIdsRef:A,selectedDocIdsRef:O,selectedNoteIdsRef:T,selectedImageIdsRef:X,selectedWebIdsRef:L,setSelectedIds:W,setSelectedDocIds:H,setSelectedNoteIds:ae,setSelectedImageIds:ge,setSelectedWebIds:J,clearSelection:ce}=e;s.useEffect(()=>{const we=y.current;if(!we)return;const ve=oe=>{var Y;const pe=oe.ctrlKey||oe.metaKey;if(t.current&&!pe)return;const K=oe.target;if((Y=K==null?void 0:K.closest)!=null&&Y.call(K,"[data-canvas-scroll], [data-webcard-scroll]"))return;for(let re=K;re&&re!==we;re=re.parentElement){const le=getComputedStyle(re).overflowY;if((le==="auto"||le==="scroll")&&re.scrollHeight>re.clientHeight+1)return}oe.preventDefault(),g();let fe=oe.deltaY,ie=oe.deltaX;if(oe.deltaMode===1?(fe*=16,ie*=16):oe.deltaMode===2&&(fe*=100,ie*=100),oe.ctrlKey||oe.metaKey){const re=we.getBoundingClientRect(),le=oe.clientX-re.left,b=oe.clientY-re.top,C=qn(Math.exp(-fe*.015),.4,2.5),z=qn(I.current*C,gs,6);f.current.x=le-(le-f.current.x)*(z/I.current),f.current.y=b-(b-f.current.y)*(z/I.current),I.current=z,h(),z*100<fr&&!c.current&&d(!0),m()}else f.current.x-=ie,f.current.y-=fe;p(),k()};return we.addEventListener("wheel",ve,{passive:!1}),()=>we.removeEventListener("wheel",ve)},[p,h,g,m,k]),s.useEffect(()=>{const we=y.current;if(!we)return;let ve=!1,oe=0,pe=0;const K=Y=>{const re=Y.target;if(!(re!=null&&re.dataset)||!("birtvyBg"in re.dataset)||Y.button!==0)return;if(n.current){ve=!0,oe=Y.clientX,pe=Y.clientY,we.setPointerCapture(Y.pointerId),we.style.cursor="grabbing";return}const le=w(Y.clientX,Y.clientY);a.current={startX:le.x,startY:le.y,pointerId:Y.pointerId,additive:Y.shiftKey,base:Y.shiftKey?new Set(A.current):new Set,baseDocs:Y.shiftKey?new Set(O.current):new Set,baseNotes:Y.shiftKey?new Set(T.current):new Set,baseImages:Y.shiftKey?new Set(X.current):new Set,baseWebs:Y.shiftKey?new Set(L.current):new Set},i.current={x:le.x,y:le.y,w:0,h:0},l(!0),we.setPointerCapture(Y.pointerId)},fe=Y=>{if(ve){f.current.x+=Y.clientX-oe,f.current.y+=Y.clientY-pe,oe=Y.clientX,pe=Y.clientY,p();return}const re=a.current;if(re&&re.pointerId===Y.pointerId){const le=w(Y.clientX,Y.clientY),b=Math.min(re.startX,le.x),C=Math.min(re.startY,le.y),z=Math.abs(le.x-re.startX),B=Math.abs(le.y-re.startY);i.current={x:b,y:C,w:z,h:B};const M=o.current;M&&(M.style.left=`${b*I.current+f.current.x}px`,M.style.top=`${C*I.current+f.current.y}px`,M.style.width=`${z*I.current}px`,M.style.height=`${B*I.current}px`);
4const q=6/I.current,ue=z<q&&B<q,ye=ue?[]:x.current.filter(G=>G.x<b+z&&G.x+Ke>b&&G.y<C+B&&G.y+Je>C).map(G=>G.id),ee=u.current,U=ue?[]:D.current.filter(G=>!ee.has(Ye("doc",G.id))&&G.x<b+z&&G.x+G.width>b&&G.y<C+B&&G.y+G.height>C).map(G=>G.id),_=ue?[]:R.current.filter(G=>!ee.has(Ye("note",G.id))&&G.x<b+z&&G.x+G.width>b&&G.y<C+B&&G.y+G.height>C).map(G=>G.id),N=ue?[]:j.current.filter(G=>!ee.has(Ye("image",G.id))&&G.x<b+z&&G.x+G.width>b&&G.y<C+B&&G.y+G.height>C).map(G=>G.id),Z=ue?[]:S.current.filter(G=>G.x<b+z&&G.x+G.width>b&&G.y<C+B&&G.y+G.height>C).map(G=>G.id),Q=(G,se,ne)=>G(de=>{const F=new Set(se);if(ne.forEach($=>F.add($)),F.size===de.size){let $=!0;for(const P of F)if(!de.has(P)){$=!1;break}if($)return de}return F});Q(W,re.base,ye),Q(H,re.baseDocs,U),Q(ae,re.baseNotes,_),Q(ge,re.baseImages,N),Q(J,re.baseWebs,Z)}},ie=Y=>{if(ve){ve=!1,we.style.cursor=n.current?"grab":"default";try{we.releasePointerCapture(Y.pointerId)}catch{}return}const re=a.current;if(!re||re.pointerId!==Y.pointerId)return;a.current=null,i.current=null,l(!1);try{we.releasePointerCapture(Y.pointerId)}catch{}const le=w(Y.clientX,Y.clientY),b=Math.min(re.startX,le.x),C=Math.min(re.startY,le.y),z=Math.abs(le.x-re.startX),B=Math.abs(le.y-re.startY),M=6/I.current;if(z<M&&B<M){re.additive||ce();return}const q=x.current.filter(N=>N.x<b+z&&N.x+Ke>b&&N.y<C+B&&N.y+Je>C).map(N=>N.id);W(N=>{const Z=re.additive?new Set(N):new Set;return q.forEach(Q=>Z.add(Q)),Z});const ue=u.current,ye=D.current.filter(N=>!ue.has(Ye("doc",N.id))&&N.x<b+z&&N.x+N.width>b&&N.y<C+B&&N.y+N.height>C).map(N=>N.id);H(N=>{const Z=re.additive?new Set(N):new Set;return ye.forEach(Q=>Z.add(Q)),Z});const ee=R.current.filter(N=>!ue.has(Ye("note",N.id))&&N.x<b+z&&N.x+N.width>b&&N.y<C+B&&N.y+N.height>C).map(N=>N.id);ae(N=>{const Z=re.additive?new Set(N):new Set;return ee.forEach(Q=>Z.add(Q)),Z});const U=j.current.filter(N=>!ue.has(Ye("image",N.id))&&N.x<b+z&&N.x+N.width>b&&N.y<C+B&&N.y+N.height>C).map(N=>N.id);ge(N=>{const Z=re.additive?new Set(N):new Set;return U.forEach(Q=>Z.add(Q)),Z});const _=S.current.filter(N=>N.x<b+z&&N.x+N.width>b&&N.y<C+B&&N.y+N.height>C).map(N=>N.id);J(N=>{const Z=re.additive?new Set(N):new Set;return _.forEach(Q=>Z.add(Q)),Z})};return we.addEventListener("pointerdown",K),we.addEventListener("pointermove",fe),we.addEventListener("pointerup",ie),()=>{we.removeEventListener("pointerdown",K),we.removeEventListener("pointermove",fe),we.removeEventListener("pointerup",ie)}},[p,w,ce])}function ub({store:e,worldRef:t,spaceRef:n,marqueeSessionRef:o,openIdRef:i,openDocIdRef:a,editingSystemIdRef:l,rectForRef:u,setWireDropMenu:c,setWireModeMenu:d,clipboardRef:p,copySelection:h,pasteClipboard:m,duplicateSelection:g,selectAll:k,deleteSelection:y,groupSelectedSlides:f,ungroupSelectedSlides:I,placeExternalItems:w}){const{slidesRef:x,docsRef:D,notesRef:R,imagesRef:j,websRef:S,setSlides:A,setDocs:O,setNotes:T,setImages:X,setWebs:L,setWires:W,selectedIdsRef:H,selectedDocIdsRef:ae,selectedNoteIdsRef:ge,selectedImageIdsRef:J,selectedWebIdsRef:ce,setSelectedIds:we,setSelectedDocIds:ve,setSelectedNoteIds:oe,setSelectedImageIds:pe,setSelectedWebIds:K,idRef:fe,requestSave:ie,viewportRef:Y,clientToWorld:re,purgeDeletedDocsRef:le}=e,b=s.useRef(null),C=s.useRef(null);s.useEffect(()=>{const q=()=>{const ye=document.activeElement;return!!ye&&(ye.tagName==="INPUT"||ye.tagName==="TEXTAREA"||ye.isContentEditable)},ue=ye=>{if(i.current!=null||a.current!=null||l.current!=null||q())return;const ee=ye.metaKey||ye.ctrlKey,U=ye.key.toLowerCase();ee&&U==="c"?h()&&ye.preventDefault():ee&&U==="d"?(g(),ye.preventDefault()):ee&&U==="a"?(k(),ye.preventDefault()):ee&&U==="g"?(ye.shiftKey?I():f(),ye.preventDefault()):(ye.key==="Delete"||ye.key==="Backspace")&&(y(),ye.preventDefault())};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[h,m,g,k,y,f,I]);const z=s.useCallback(()=>{var ue;const q=(ue=t.current)==null?void 0:ue.querySelector("[data-wire-preview]");q&&(q.style.display="none")},[]),B=s.useCallback((q,ue)=>{ue.stopPropagation(),ue.preventDefault(),b.current={from:q,pointerId:ue.pointerId,startX:ue.clientX,startY:ue.clientY}},[]);s.useEffect(()=>{const q=()=>{var ee;return(ee=t.current)==null?void 0:ee.querySelector("[data-wire-preview]")},ue=ee=>{const U=b.current;if(!U||U.pointerId!==ee.pointerId)return;const _=u(U.from),N=q();if(!_||!N)return;const Z=re(ee.clientX,ee.clientY);N.setAttribute("d",ob(_,Z)),N.style.display=""},ye=ee=>{const U=b.current;if(!U||U.pointerId!==ee.pointerId)return;b.current=null;const _=()=>{const F=q();F&&(F.style.display="none")},N=re(ee.clientX,ee.clientY),Z=[...R.current].reverse().find(F=>N.x>=F.x&&N.x<=F.x+F.width&&N.y>=F.y&&N.y<=F.y+F.height),Q=[...D.current].reverse().find(F=>N.x>=F.x&&N.x<=F.x+F.width&&N.y>=F.y&&N.y<=F.y+F.height),G=[...S.current].reverse().find(F=>N.x>=F.x&&N.x<=F.x+F.width&&N.y>=F.y&&N.y<=F.y+F.height),se=[...j.current].reverse().find(F=>N.x>=F.x&&N.x<=F.x+F.width&&N.y>=F.y&&N.y<=F.y+F.height),ne=[...x.current].reverse().find(F=>N.x>=F.x&&N.x<=F.x+Ke&&N.y>=F.y&&N.y<=F.y+Je),de=G?{kind:"web",id:G.id}:Z?{kind:"note",id:Z.id}:Q?{kind:"doc",id:Q.id}:se?{kind:"image",id:se.id}:ne?{kind:"slide",id:ne.id}:null;if(de&&de.kind===U.from.kind&&de.id===U.from.id){_();return}if(!de){Math.abs(ee.clientX-U.startX)+Math.abs(ee.clientY-U.startY)>6?c({from:U.from,world:N,client:{x:ee.clientX,y:ee.clientY}}):_();return}if(U.from.kind==="image"&&de.kind==="slide"){d({from:U.from,to:de,client:{x:ee.clientX,y:ee.clientY}});return}_(),W(F=>F.some($=>$.from.kind===U.from.kind&&$.from.id===U.from.id&&$.to.kind===de.kind&&$.to.id===de.id)?F:[...F,{id:fe.current++,from:U.from,to:de}]),ie()};return window.addEventListener("pointermove",ue),window.addEventListener("pointerup",ye),()=>{window.removeEventListener("pointermove",ue),window.removeEventListener("pointerup",ye)}},[re,u,ie]);const M=s.useCallback((q,ue,ye)=>{ye.stopPropagation(),ye.preventDefault();const ee=j.current.find(U=>U.id===q);ee&&(C.current={id:q,corner:ue,start:{x:ee.x,y:ee.y,w:ee.width,h:ee.height},startCX:ye.clientX,startCY:ye.clientY}
4,pe(new Set([q])))},[]);return s.useEffect(()=>{const q=ye=>{const ee=C.current;if(!ee)return;const U=re(ee.startCX,ee.startCY),_=re(ye.clientX,ye.clientY),N=_.x-U.x,Z=_.y-U.y,{x:Q,y:G,w:se,h:ne}=ee.start,de=Q+se,F=G+ne,$=ee.corner==="ne"||ee.corner==="se"?1:-1,P=ee.corner==="sw"||ee.corner==="se"?1:-1;let me=Math.max((se+$*N)/se,(ne+P*Z)/ne);me=Math.max(me,48/se,48/ne);const he=Math.round(se*me),Me=Math.round(ne*me),He=ee.corner==="nw"||ee.corner==="sw"?de-he:Q,Ee=ee.corner==="nw"||ee.corner==="ne"?F-Me:G;X(qe=>qe.map(Ae=>Ae.id===ee.id?{...Ae,x:He,y:Ee,width:he,height:Me}:Ae))},ue=()=>{C.current&&(C.current=null,ie())};return window.addEventListener("pointermove",q),window.addEventListener("pointerup",ue),()=>{window.removeEventListener("pointermove",q),window.removeEventListener("pointerup",ue)}},[re,ie]),s.useEffect(()=>{const q=ee=>{const U=ee;return!!U&&(U.tagName==="INPUT"||U.tagName==="TEXTAREA"||U.isContentEditable)},ue=ee=>{if(ee.code==="Space"&&!q(ee.target)&&(n.current=!0,Y.current&&!o.current&&(Y.current.style.cursor="grab")),(ee.key==="Delete"||ee.key==="Backspace")&&i.current==null&&a.current==null&&l.current==null&&(H.current.size>0||ae.current.size>0||ge.current.size>0||J.current.size>0||ce.current.size>0)&&!q(ee.target)){if(ee.preventDefault(),H.current.size>0){const U=H.current;A(_=>_.filter(N=>!U.has(N.id))),we(new Set)}if(ae.current.size>0){const U=ae.current;le.current(D.current.filter(_=>U.has(_.id))),O(_=>_.filter(N=>!U.has(N.id))),ve(new Set)}if(ge.current.size>0){const U=ge.current;T(_=>_.filter(N=>!U.has(N.id))),oe(new Set)}if(J.current.size>0){const U=J.current;X(_=>_.filter(N=>!U.has(N.id))),pe(new Set)}if(ce.current.size>0){const U=ce.current;L(_=>_.filter(N=>!U.has(N.id))),K(new Set)}ie()}},ye=ee=>{ee.code==="Space"&&(n.current=!1,Y.current&&(Y.current.style.cursor="default"))};return window.addEventListener("keydown",ue),window.addEventListener("keyup",ye),()=>{window.removeEventListener("keydown",ue),window.removeEventListener("keyup",ye)}},[ie]),s.useEffect(()=>{const q=ye=>{let ee=ye;ee&&ee.nodeType===Node.TEXT_NODE&&(ee=ee.parentNode);const U=_=>{var N;return!!_&&(_.isContentEditable||!!((N=_.closest)!=null&&N.call(_,'input, textarea, select, [contenteditable="true"], .ProseMirror')))};return U(ee)||U(document.activeElement)},ue=ye=>{if(q(ye.target)||i.current!=null||a.current!=null)return;const ee=ye.clipboardData;if(!ee)return;if((ee.getData("text/plain")??"").startsWith(ou)){ye.preventDefault(),p.current&&m();return}const U=au(ee);if(U.length===0){p.current&&(ye.preventDefault(),m());return}ye.preventDefault(),w(U)};return window.addEventListener("paste",ue),()=>window.removeEventListener("paste",ue)},[w,m]),s.useEffect(()=>{const q=ue=>{ue.defaultPrevented||!ue.dataTransfer||Hi(ue.dataTransfer.types)&&(ue.preventDefault(),ue.type==="dragover"&&(ue.dataTransfer.dropEffect="none"))};return window.addEventListener("dragover",q),window.addEventListener("drop",q),()=>{window.removeEventListener("dragover",q),window.removeEventListener("drop",q)}},[]),{hideWirePreview:z,startWire:B,startImageResize:M}}function fb(){const[e,t]=s.useState(""),n=s.useRef(e);s.useEffect(()=>{n.current=e},[e]);const[o,i]=s.useState(!1);return{docTheme:e,setDocTheme:t,docThemeRef:n,docThemeOpen:o,setDocThemeOpen:i}}function hb(e){const{setSlides:t}=e,n=s.useRef(new Set),o=s.useRef(null),i=s.useCallback(l=>{if(l.type!=="mcp:activity")return;const u=(l.slideIds??[]).map(Number).filter(d=>Number.isFinite(d));l.mode==="idle"?u.forEach(d=>n.current.delete(d)):u.forEach(d=>n.current.add(d)),t(d=>d.map(p=>{const m=n.current.has(p.id)?"generating":p.baked||p.html||p.graphyConfig?"done":"empty";return p.status===m?p:{...p,status:m}})),o.current&&window.clearTimeout(o.current);const c=typeof l.ttlMs=="number"?l.ttlMs:18e4;c>0&&n.current.size>0&&(o.current=window.setTimeout(()=>{n.current.clear(),t(d=>d.map(p=>p.status==="generating"&&!p.baked&&!p.html?{...p,status:"empty"}:p))},c))},[t]),a=s.useCallback(l=>n.current.has(l.id)?l.baked||l.html?(n.current.delete(l.id),!1):!0:!1,[]);return s.useEffect(()=>()=>{o.current&&window.clearTimeout(o.current)},[]),{handleRemoteSignal:i,remoteBusyDone:a}}function pb(e){return s.useCallback(t=>{Hm(t)||e(t)},[e])}function mb(e){return s.useSyncExternalStore(Um,()=>
4Xm(e),()=>!1)}const gb={Display:0,H1:1,H2:2,Body:4,Caption:5},nd=3,rd=8,Ii=60;function xb(e){if(!(e!=null&&e.length))return null;const t=e.filter(n=>n.type==="text"&&typeof n.text=="string"&&ju(n.text)).map(n=>({text:n.text,rank:n.textRole?gb[n.textRole]??nd:nd,size:n.fontSize??0,y:n.y??0}));return t.length?(t.sort((n,o)=>n.rank-o.rank||o.size-n.size||n.y-o.y),bb(t[0].text)):null}function yb(e,t=600){if(!(e!=null&&e.length))return null;const n=e.filter(a=>a.type==="text"&&typeof a.text=="string"&&ju(a.text)).slice().sort((a,l)=>(a.y??0)-(l.y??0)||(a.x??0)-(l.x??0)).map(a=>a.text.replace(/\s+/g," ").trim());if(!n.length)return null;const o=[];let i=0;for(const a of n){if(i+a.length>t)break;o.push(a),i+=a.length+1}return o.length?o.join(` 5`):n[0].slice(0,t)}function ju(e){const t=e.replace(/\s+/g," ").trim();return!(t.length<3||!new RegExp("\\p{L}{2,}","u").test(t))}function bb(e){const n=e.replace(/\s+/g," ").trim().split(" ");let o=n.length>rd,i=n.slice(0,rd).join(" ");if(i.length>Ii){const a=i.slice(0,Ii),l=a.lastIndexOf(" ");i=(l>Ii/2?a.slice(0,l):a).trimEnd(),o=!0}return i=i.replace(/^[\s\p{P}]+/u,"").replace(/[\s,;:.\-ââ]+$/u,""),i?o?`${sd(i)}â¦`:sd(i):null}function sd(e){return e!==e.toUpperCase()||!new RegExp("\\p{Lu}","u").test(e)?e:e.split(" ").map(t=>t.replace(new RegExp("\\p{P}","gu"),"").length<=3?t:t.charAt(0)+t.slice(1).toLowerCase()).join(" ")}function wb({conversationId:e,projectId:t,queryClient:n,titleRef:o,slidesRef:i,setTitle:a,requestSave:l,deckLoaded:u,deckHydrated:c}){const d=s.useCallback(async()=>{var f,I,w;if(!e)return;const h=x=>["","untitled","untitled presentation","untitled deck","birtvy deck"].includes(x.trim().toLowerCase());if(!h(o.current))return;const m=x=>{a(x),l(),n.invalidateQueries({queryKey:["projectDashboard",t]})},g=i.current.find(x=>{var D,R;return(((R=(D=x.baked)==null?void 0:D.elements)==null?void 0:R.length)||x.html)&&x.status!=="generating"}),k=xb((f=g==null?void 0:g.baked)==null?void 0:f.elements),y=((I=g==null?void 0:g.prompt)==null?void 0:I.trim())||yb((w=g==null?void 0:g.baked)==null?void 0:w.elements)||void 0;try{const x=await fetch(`/gen-title-api/${e}`,{method:"POST",credentials:"include",...y?{headers:{"Content-Type":"application/json"},body:JSON.stringify({source:y})}:{}});if(x.ok){const D=await x.json();if(D.title&&!h(D.title)){m(D.title);return}}}catch{}if(!(!k||!h(o.current)))try{(await fetch(`/conversation-rename-api/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({title:k})})).ok&&m(k)}catch{}},[e,t,n,l,a,i,o]);s.useEffect(()=>{!u||!c||d()},[u,c,d]);const p=s.useCallback(h=>{h||d()},[d]);return{runGenTitle:d,handleAgentWorkingChange:p}}function vb(e){return/^1:1\b/i.test(e.trim())}function kb(e){return e.trim().replace(/^1:1[\s:.\-ââ]*/i,"").trim()}const Sb=/^(system-ui|-apple-system|blinkmacsystemfont|segoe ui|georgia|times|times new roman|arial|helvetica|sans-serif|serif|monospace|ui-sans-serif|ui-serif|ui-monospace|inherit|initial)$/i;function Ib(e){const t=new Set,n=/font-family\s*:\s*['"]?([^;"'{}]+)/gi;let o;for(;o=n.exec(e);){const i=o[1].split(",")[0].replace(/["']/g,"").trim();i&&!Sb.test(i)&&t.add(i)}return[...t]}async function Nu(e,t){if(typeof document>"u"||!t)return null;try{const i=await pg(String(e));if(i&&i.length>5e3)return i}catch(i){console.warn("[birtvy-ref] captureSlide failed, trying thumbnail",i)}try{const i=Fr(_n("b",t),t,Ke);if(i){const a=i.toDataURL("image/png");if(a&&a.length>5e3)return a}}catch(i){console.warn("[birtvy-ref] thumb capture failed, trying offscreen render",i)}const n=document.createElement("div");n.setAttribute("aria-hidden","true"),n.style.cssText=`position:fixed;left:-100000px;top:0;width:${Ke}px;height:${Je}px;overflow:hidden;pointer-events:none;background:#ffffff`;const o=document.createElement("div");o.style.cssText=`position:relative;width:${Ke}px;height:${Je}px;overflow:hidden;background:#ffffff`,o.innerHTML=Cb(yg(t)),n.appendChild(o),document.body.appendChild(n);try{const i=Ib(t);for(const u of i)Li(u);i.length&&await new Promise(u=>setTimeout(u,60));const a=await mg([...i,"Inter"]);try{await document.fonts.ready}catch{}const l=await gg(o,{width:Ke,height:Je,pixelRatio:.5,fontEmbedCSS:a,style:{transform:"none",transformOrigin:"top left",margin:"0"}});return l&&l.length>5e3?l:(console.warn("[birtvy-ref] offscreen capture came back blank â no reference sent"),null)}catch(i){return console.warn("[birtvy-ref] reference capture FAILED",i),null}finally{n.remove()}}function Cb(e){const t=typeof window<"u"?window.location.origin:"",n=o=>!/^https?:\/\//i.test(o)||t&&o.startsWith(t)?o:`/deckgen-image-proxy-api?url=${encodeURIComponent(o)}`;return e.replace(/src="(https?:\/\/[^"]+)"/gi,(o,i)=>`src="${n(i)}"`).replace(/url\((['"]?)(https?:\/\/[^)'"]+)\1\)/gi,(o,i,a)=>`url(${i}${n(a)}${i})`)}const Eb=960;async function Rb(e,t,n,o){if(typeof document>"u"||!e||!n)return!1;const i=await Nu(t,n);if(!i)return!1;const a=await Mb(i);if(!a)return!1;try{const l=new FormData;l.append("file",a,"thumbnail.jpg");const u=o!=null&&o.onlyIfEmpty?"?onlyIfEmpty=1":"";return(await fetch(`/conversation-thumbnail-api/${e}${u}`,{method:"POST",body:l,credentials:"include"})).ok}catch{return!1}}async function Mb(e){const t=await jb(e);
5if(!t)return null;const n=t.naturalWidth||1920,o=t.naturalHeight||1080,i=Math.min(Eb,n),a=Math.max(1,Math.round(i*o/n)),l=document.createElement("canvas");l.width=i,l.height=a;const u=l.getContext("2d");return u?(u.fillStyle="#ffffff",u.fillRect(0,0,i,a),u.drawImage(t,0,0,i,a),await new Promise(c=>l.toBlob(d=>c(d),"image/jpeg",.82))):null}function jb(e){return new Promise(t=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>t(null),n.src=e})}function Nb({slidesRef:e,conversationId:t,projectId:n,queryClient:o,showToast:i}){const a=s.useRef(!1),l=s.useCallback(async(u,c)=>{if(!t||c!=null&&c.auto&&a.current)return;const d=e.current.find(m=>m.id===u),p=(d==null?void 0:d.html)||(d!=null&&d.baked?gn(d.baked,u):"");if(!p){c!=null&&c.auto||i({title:"That slide has nothing on it yet.",variant:"error"});return}if(!await Rb(t,u,p,{onlyIfEmpty:c==null?void 0:c.auto})){c!=null&&c.auto||i({title:"Couldn't set the thumbnail â try again.",variant:"error"});return}a.current=!0,o.invalidateQueries({queryKey:["projectDashboard",n]}),c!=null&&c.auto||i({title:"Set as deck thumbnail",variant:"success"})},[t,n,o,i,e]);return{thumbCapturedRef:a,captureThumbnail:l}}const Db=40;function Tb(e){const{slides:t,editingSlideId:n,deckLoaded:o,onDocBaked:i}=e,a=o,l=s.useMemo(()=>{const y=[],f=[];if(a){for(const I of t)I.docHtml&&(I.docBaked&&I.docBaked.includes(Ud)?f.push({id:I.id,baked:I.docBaked}):I.id!==n&&I.status!=="generating"&&y.push({id:I.id,html:I.docHtml}));y.sort((I,w)=>I.id-w.id)}return{targets:y,baked:f}},[t,a,n]),u=s.useRef(l);u.current=l;const c=s.useMemo(()=>l.targets.map(y=>y.id).join(",")+"|"+l.baked.map(y=>`${y.id}.${y.baked.length}`).join(","),[l]),[d,p]=s.useState(()=>new Map),h=s.useCallback((y,f)=>{p(I=>{const w=new Map(I);return w.set(y,f),w})},[]),m=s.useMemo(()=>{const y=new Set;for(const f of l.targets)d.get(f.id)!==f.html&&y.add(f.id);return y},[l,d]),g=s.useCallback((y,f)=>{i(y,f);const I=Hr();if(I==null)return;const w=`<style>${I}</style>${f}`;try{Fr(_n("b",w),w,512,{doc:!0})}catch{}},[i]),k=s.useRef(new Map);return s.useEffect(()=>{if(!a)return;const y=new Set;let f=!1;for(const{id:I,baked:w}of l.baked)if(k.current.get(I)!==w){k.current.set(I,w),f=!0;for(const x of vy(w))y.add(x)}f&&bo([...y])},[l,a]),s.useEffect(()=>{if(!a||l.baked.length===0)return;let y=0,f=0;const I=()=>{const w=Hr();if(w==null){if(++f>Db)return;y=window.setTimeout(I,250);return}for(const{baked:x}of u.current.baked){const D=`<style>${w}</style>${x}`;try{Fr(_n("b",D),D,512,{doc:!0})}catch{}}};return y=window.setTimeout(I,300),()=>window.clearTimeout(y)},[a,c,l.baked.length]),{docWarmActive:a,docSlideSets:l,docWarmHoldIds:m,onDocWarmBaked:g,onDocWarmGaveUp:h}}function Ab(e){const{focusRect:t}=e,[n,o]=s.useState(()=>new Set),i=s.useRef(new Map),a=s.useCallback(u=>{u.length&&(o(c=>{const d=new Set(c);return u.forEach(p=>d.add(p)),d}),u.forEach(c=>{const d=i.current.get(c);d&&window.clearTimeout(d);const p=window.setTimeout(()=>{i.current.delete(c),o(h=>Cr(h,c))},1500);i.current.set(c,p)}))},[]),l=s.useCallback((u,c)=>{u.length&&(t(c,.72),a(u))},[t,a]);return{revealingDocIds:n,revealDocsInPlace:a,revealDocs:l}}function $b({deletedDocIdsRef:e,agentDocsRef:t,docsRef:n,idRef:o,docDirtyRef:i,recentDocEditsRef:a,DOC_EDIT_MEMORY_MS:l,setDocs:u,requestSave:c,showToast:d,revealDocs:p}){const h=s.useCallback(y=>{if(e.current.has(y.id)){console.info(`birtvy: skipping re-accept of deleted document ${y.id}`);return}const f=n.current;if(f.find(R=>R.documentId===y.id))return;const w=f.length?Math.max(...f.map(R=>R.x+R.width))+120:120,x=f.length?Math.min(...f.map(R=>R.y)):120,D=o.current++;u(R=>[...R,{id:D,x:w,y:x,width:En,height:Cn,content:y.content,title:y.title,documentId:y.id}]),c(),p([D],{x:w,y:x,w:En,h:Cn})},[p,c]),m=s.useCallback(y=>{const f=n.current.filter(R=>R.documentId===y.id);if(f.length===0){console.warn("birtvy: documentUpdated for a document not on this canvas",y.id),d({title:`Updated â${y.title}â in the Library. It is not on this canvas.`,variant:"error"});return}const I=f.filter(R=>R.content!==y.content||R.title!==y.title);if(I.length===0)return;const w=new Set(I.map(R=>R.id));{const R=Date.now(),j=a.current;R-j.at>
5l&&(j.ids=new Set),w.forEach(S=>j.ids.add(S)),j.at=R}const x=R=>R.map(j=>w.has(j.id)?{...j,title:y.title,content:y.content}:j);n.current=x(n.current),u(R=>x(R)),I.forEach(R=>i.current.delete(R.id));const D=I[0];p([...w],{x:D.x,y:D.y,w:D.width,h:D.height}),c()},[p,c,d]),g=s.useCallback(y=>{var f;return(f=n.current.find(I=>I.documentId===y))==null?void 0:f.content},[]),k=s.useCallback(y=>{const f=y.map(j=>t.current[`canvas:${j}`]).filter(j=>j!=null&&n.current.some(S=>S.id===j));if(!f.length)return;const I=n.current.filter(j=>f.includes(j.id)),w=Math.min(...I.map(j=>j.x)),x=Math.min(...I.map(j=>j.y)),D=Math.max(...I.map(j=>j.x+j.width)),R=Math.max(...I.map(j=>j.y+j.height));p(f,{x:w,y:x,w:D-w,h:R-x})},[p]);return{placeAgentDoc:h,updateDocByDocumentId:m,getDocumentContent:g,revealChapters:k}}function Pb({store:e,conversationId:t,deckLoaded:n,editingSlideId:o,writeDocSource:i,resolveDocLogos:a}){const{slidesRef:l,setSlides:u,setSelectedIds:c,idRef:d,requestSave:p,patch:h,placeInView:m}=e;s.useEffect(()=>{if(t)return;const y={addDocSlide:(f,I)=>{const{x:w,y:x}=m({width:Ke,height:Je},I),D=d.current++;return u(R=>[...R,{id:D,x:w,y:x,status:"done",prompt:"",docHtml:String(f),docMeta:yo(String(f),{by:"bridge"}),docRev:1,docLog:[{at:Date.now(),by:"bridge",rev:1}]}]),c(new Set([D])),p(),D},setDocSlide:(f,I)=>{const w=l.current.find(x=>x.id===f);return w!=null&&w.docHtml?(i(f,String(I),"bridge"),!0):!1},listDocSlides:()=>l.current.filter(f=>f.docHtml).map(f=>({id:f.id,x:f.x,y:f.y,prompt:f.prompt})),removeDocSlide:f=>{const I=l.current.find(w=>w.id===f);return I!=null&&I.docHtml?(u(w=>w.filter(x=>x.id!==f)),c(w=>Cr(w,f)),p(),!0):!1}};return window.__birtvyOpen=y,()=>{const f=window;f.__birtvyOpen===y&&delete f.__birtvyOpen}},[t,h,m,p,i]);const g=s.useRef(new Map),k=y=>{const f=Fi(y),I=[...f.rejects,...f.flags];return I.length?I:void 0};s.useEffect(()=>{if(t||!n)return;let y=!0;const f=async()=>{var w,x,D,R;try{const j=await fetch("/birtvy-open-inbox.json");if(!j.ok||!y)return;const S=await j.json();if(!y||!Array.isArray(S.slides))return;let A=!1;for(const O of S.slides){if(g.current.get(O.key)===O.mtimeMs)continue;const T=l.current.find(W=>{var H,ae;return W.docHtml&&(((ae=(H=W.docMeta)==null?void 0:H.provenance)==null?void 0:ae.inboxKey)===O.key||W.prompt===`inbox:${O.key}`)}),X=O.targetId!=null?l.current.find(W=>W.id===O.targetId&&W.docHtml):void 0,L=T??X;if(L){if(L.status==="generating"||o===L.id)continue;const W=(w=L.docLog)!=null&&w.length?L.docLog[L.docLog.length-1].at:0,H=W>0&&O.mtimeMs<=W;L.docHtml!==O.html&&!H?(i(L.id,O.html,"inbox",{inboxKey:O.key,flags:k(O.html)}),a(L.id,O.html),A=!0):((D=(x=L.docMeta)==null?void 0:x.provenance)==null?void 0:D.inboxKey)!==O.key&&(h(L.id,{docMeta:{...L.docMeta,provenance:{by:"inbox",...(R=L.docMeta)==null?void 0:R.provenance,inboxKey:O.key}}}),A=!0)}else{const W=O.x!=null&&O.y!=null?{x:O.x,y:O.y}:m({width:Ke,height:Je}),H=d.current++;u(ae=>[...ae,{id:H,x:W.x,y:W.y,status:"done",prompt:"",docHtml:O.html,docMeta:yo(O.html,{by:"inbox",inboxKey:O.key}),docRev:1,docLog:[{at:Date.now(),by:"inbox",rev:1,flags:k(O.html)}]}]),a(H,O.html),A=!0}g.current.set(O.key,O.mtimeMs)}A&&p()}catch{}},I=window.setInterval(()=>void f(),2e3);return f(),()=>{y=!1,window.clearInterval(I)}},[t,n,o,h,m,p,a,i])}function Lb({conversationId:e,docsRef:t,docDirtyRef:n,docsAdoptedRef:o,agentDocsRef:i,setDocs:a,requestSave:l,showToast:u}){const c=s.useCallback(async h=>{if(!e||!n.current.has(h))return;const m=t.current.find(k=>k.id===h);if(!(m!=null&&m.documentId))return;const g=await mc(e,m.documentId,{content:m.content??"",title:null});if(!g){u({title:`Couldnât save â${m.title||"document"}â to the Library. It stays on the canvas.`,variant:"error"});return}n.current.delete(h),g.title&&g.title!==m.title&&(a(k=>k.map(y=>y.id===h?{...y,title:g.title}:y)),l())},[e,l,u]),d=s.useRef(!1),p=s.useCallback(async()=>{if(!e||d.current)return;d.current=!0;const h=await vm(e);if(!h)return;if(!o.current){const f=new Map(h.map(w=>[w.id,w]));let I=0;for(const w of t.current.filter(x=>x.documentId&&(x.content??"").length>0)){const x=f.get(w.documentId);!x||(x.content??"")===w.content||await mc(e,w.documentId,{content:w.content??"",title:null})&&I++}o.current=!0,l(),I>0&&console.info(`birtvy: adopted ${I} document card(s) into the Library`)}const m=new Set(Object.values(i.current)),g=t.current.filter(f=>!f.documentId&&!m.has(f.id)),k=new Map,y=new Set(t.current.map(f=>f.documentId).filter(f=>!!f));for(const f of g){const I=f.content??"",w=I.length>0?h.find(D=>!y.has(D.id)&&(D.content??"")===I):void 0;if(w){y.add(w.id),k.set(f.id,w.id);continue}const x=await $d(e,{title:f.title||void 0,content:I});x&&(y.add(x.id),k.set(f.id,x.id))}k.size>0&&(a(f=>f.map(I=>k.has(I.id)?{...I,documentId:k.get(I.id)}:I)),l(),console.info(`birtvy: linked ${k.size} document card(s) to the Library`))},[e,l]);return{flushDocToLibrary:c,syncDocsWithLibrary:p}}function zb({conversationId:e,demo:t,showToast:n,titleRef:o,slidesRef:i,docThemeRef:a,docsRef:l,n
5otesRef:u,imagesRef:c,websRef:d,wiresRef:p,groupsRef:h,agentDocsRef:m,deletedDocIdsRef:g,designSystemsRef:k,activeDesignSystemIdRef:y,brandKitBindingRef:f,idRef:I,fitAllRef:w,setSlides:x,setDocs:D,setNotes:R,setImages:j,setWebs:S,setWires:A,setGroups:O,setDesignSystems:T,setActiveDesignSystemId:X,setTitle:L,setDocTheme:W,setDeckLoaded:H,remoteBusyDone:ae,handleRemoteSignal:ge}){const J=s.useCallback(()=>({title:o.current,slides:i.current.map(b=>({id:b.id,x:b.x,y:b.y,prompt:b.prompt,html:b.html,baked:b.baked,graphyConfig:b.graphyConfig,groupId:b.groupId,excludedFromPresentation:!!b.excludedFromPresentation,docHtml:b.docHtml,docBaked:b.docBaked,docMeta:b.docMeta,docRev:b.docRev,docLog:b.docLog,docPrevSource:b.docPrevSource})),docTheme:a.current,docs:l.current.map(b=>({...b})),notes:u.current.map(b=>({...b})),images:c.current.map(b=>({...b})),webs:d.current.map(b=>({...b})),wires:p.current.map(b=>({...b})),groups:h.current.map(b=>({...b})),agentDocs:{...m.current},deletedDocIds:[...g.current],designSystems:k.current.map(b=>({...b})),activeDesignSystemId:y.current,brandKitBinding:f.current?{...f.current}:null,docsAdopted:oe.current,recentDocEdits:{ids:[...pe.current.ids],at:pe.current.at}}),[]),ce=s.useCallback((b,C)=>{m.current=b.agentDocs&&typeof b.agentDocs=="object"?{...b.agentDocs}:{},g.current=new Set(Array.isArray(b.deletedDocIds)?b.deletedDocIds.filter(_=>typeof _=="string"):[]);{const _=b.recentDocEdits,N=Array.isArray(_==null?void 0:_.ids)?_.ids.filter(Z=>typeof Z=="number"):[];pe.current={ids:new Set(N),at:typeof(_==null?void 0:_.at)=="number"?_.at:0}}b.docsAdopted===!0&&(oe.current=!0);const z=b.slides.map(_=>({id:_.id,x:_.x,y:_.y,prompt:_.prompt??"",html:_.html??(_.baked?gn(_.baked,_.id):void 0),baked:_.baked,graphyConfig:_.graphyConfig,groupId:_.groupId??null,excludedFromPresentation:!!_.excludedFromPresentation,docHtml:_.docHtml,docBaked:_.docBaked,docMeta:(()=>{var Q,G,se,ne;const N=_.docHtml&&((Q=_.prompt)!=null&&Q.startsWith("inbox:"))?_.prompt.slice(6):void 0,Z=N&&!((se=(G=_.docMeta)==null?void 0:G.provenance)!=null&&se.inboxKey)?{..._.docMeta,provenance:{by:"inbox",...(ne=_.docMeta)==null?void 0:ne.provenance,inboxKey:N}}:_.docMeta;return _.docHtml&&!(Z!=null&&Z.title)&&!(Z!=null&&Z.fonts)?{...yo(_.docHtml,Z==null?void 0:Z.provenance),...Z}:Z})(),docRev:_.docRev,docLog:_.docLog,docPrevSource:_.docPrevSource,status:ae(_)?"generating":_.baked||_.html||_.graphyConfig||_.docHtml?"done":"empty"}));x(z);const B=(Array.isArray(b.docs)?b.docs:[]).map(_=>({..._}));D(B);const M=(Array.isArray(b.notes)?b.notes:[]).map(_=>({..._,color:_.color??"default"}));R(M);const q=(Array.isArray(b.images)?b.images:[]).map(_=>({..._}));j(q);const ue=(Array.isArray(b.webs)?b.webs:[]).map(_=>({..._}));S(ue);const ye=Array.isArray(b.wires)?b.wires:[];A(ye);const ee=Array.isArray(b.groups)?b.groups:[];O(ee);const U=Array.isArray(b.designSystems)?b.designSystems:[];T(U),X(typeof b.activeDesignSystemId=="string"?b.activeDesignSystemId:null);{const _=b.brandKitBinding;f.current=_&&typeof _.kitId=="string"&&_.profile?_:null}b.title&&L(b.title),W(typeof b.docTheme=="string"?b.docTheme:""),I.current=ee.reduce((_,N)=>Math.max(_,N.id+1),ye.reduce((_,N)=>Math.max(_,N.id+1),ue.reduce((_,N)=>Math.max(_,N.id+1),q.reduce((_,N)=>Math.max(_,N.id+1),M.reduce((_,N)=>Math.max(_,N.id+1),B.reduce((_,N)=>Math.max(_,N.id+1),z.reduce((_,N)=>Math.max(_,N.id+1),I.current))))))),(C==null?void 0:C.frame)!==!1&&e&&z.length&&w.current(z)},[e]),we=s.useCallback(()=>i.current.some(b=>b.status==="generating"),[]),ve=s.useCallback(async()=>{if(!e)return;const b=await Ym(e);if(!b){console.warn("birtvy: no deck found for conversation",e);return}ce({title:b.title,slides:b.slides,docs:b.docs,notes:b.notes,images:b.images,wires:b.wires})},[e,ce]),oe=s.useRef(!1),pe=s.useRef({ids:new Set,at:0}),K=s.useRef(null),{requestSave:fe,convId:ie,deckIdRef:Y,isHydrated:re}=Cg({getState:J,onHydrate:ce,isBusy:we,conversationId:e,demo:!!t,importReal:ve,onRemoteSignal:ge,onHydrated:()=>{var b;return(b=K.current)==null?void 0:b.call(K)},onLoaded:()=>H(!0),onLoadError:()=>n({title:"Couldnât load your deck â the backend isnât reachable. Retrying; saving is paused so nothing gets overwritten.",variant:"error"})}),le=s.useCallback(async()=>{we()||Y.current&&re()&&await wg(Y.current,JSON.stringify(J()))},[Y,J,we,re]);return{getState:J,onHydrate:ce,recentDocEditsRef:pe,docsAdoptedRef:oe,onHydratedRef:K,requestSave:fe,convId:ie,deckIdRef:Y,isHydrated:re,flushSave:le}}function _b(e,t){return{id:String(e),title:"",background:t.background,elements:t.elements.filter(n=>n.type!=="group"&&n.type!=="stack").map(n=>({id:n.id,type:n.type,...rn(n)?{isChart:!0}:{},x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,zIndex:n.zIndex,text:n.text,textRole:n.textRole,fontSize:n.fontSize,fontWeight:n.fontWeight,fontFamily:n.fontFamily,lineHeight:n.lineHeight,fontStyle:n.fontStyle,textAlign:n.textAlign,listStyle:n.listStyle,color:n.color,opacity:n.opacity,background:n.background,fillImage:n.fillImage,shapeFillMode:n.shapeFillMode,shapeKind:n.shapeKind,strokeColor:n.strokeColor,strokeWidth:n.strokeWidth,strokeStyle:n.strokeStyle,cornerRadius:n.cornerRadius}))}}function Ob(e,t){const n=(o,i)=>
5typeof o=="string"&&typeof i=="string"?o.trim().toLowerCase()===i.trim().toLowerCase():o===i;switch(e.type){case"UpdateElement":{const o=t.elements.find(i=>i.id===e.elementId);return o?Object.entries(e.patch).every(([i,a])=>n(a,o[i])):!1}case"MoveElement":{const o=t.elements.find(i=>i.id===e.elementId);return!!o&&o.x===e.x&&o.y===e.y}case"UpdateSlideAppearance":return e.patch.background!=null&&n(e.patch.background,t.background)&&e.patch.slideFillMode==null;default:return!1}}function Bb(e){const i=[],a=e.elements.map(l=>{var m;if(l.type==="group"||l.type==="stack")return l;const u=Math.min(l.width,1840),c=Math.min(l.height,1e3),d=Math.min(Math.max(l.x,40),1880-u),p=Math.min(Math.max(l.y,40),1040-c);if(d===l.x&&p===l.y&&u===l.width&&c===l.height)return l;const h=l.type==="text"&&((m=l.text)!=null&&m.trim())?`â${l.text.trim().replace(/\s+/g," ").slice(0,24)}â`:l.type==="text"?"a text block":"a shape";return i.push(`pulled ${h} back inside the slide`),{...l,x:d,y:p,width:u,height:c}});return{baked:i.length?{...e,elements:a}:e,repaired:i}}function Fb(e){if(e.length===0)return"";let t=0,n=0,o=0,i=0,a=0,l=0,u=!1,c=!1,d=!1;for(const k of e)switch(k.type){case"AddElement":k.element.type==="text"?t++:n++;break;case"DeleteElement":o+=1;break;case"DeleteElements":o+=k.elementIds.length;break;case"MoveElement":l++;break;case"UpdateSlideAppearance":u=!0;break;case"SetChart":c=!0;break;case"ReorderElementsZ":d=!0;break;case"UpdateSlideTitle":i++;break;case"UpdateElement":{const y=Object.keys(k.patch);y.includes("text")?i++:y.some(f=>["color","background","strokeColor"].includes(f))?a++:y.some(f=>["x","y","width","height"].includes(f))?l++:a++;break}}const p=(k,y,f=`${y}s`)=>`${k} ${k===1?y:f}`,h=[];u&&h.push("changed the background"),c&&h.push("rebuilt the chart");const m=[];return t&&m.push(p(t,"text block")),n&&m.push(p(n,"shape")),m.length&&h.push(`added ${m.join(" and ")}`),o&&h.push(`removed ${p(o,"element")}`),i&&h.push(`rewrote ${p(i,"text")}`),a&&h.push(`restyled ${p(a,"element")}`),l&&h.push(`repositioned ${p(l,"element")}`),d&&h.push("reordered the layers"),h.length===0?"":`I ${h.length===1?h[0]:`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`}.`}function Gb(e,t){const n=o=>{const i=t.elements.find(a=>a.id===o);if(!i)return"an element";if(i.type==="text"){const a=(i.text??"").trim().replace(/\s+/g," ");return a?`â${a.slice(0,28)}${a.length>28?"â¦":""}â`:"a text block"}return rn(i)?"the chart":i.type==="shape"?"a shape":"an element"};switch(e.type){case"UpdateElement":{const o=Object.keys(e.patch);return`${o.some(a=>a==="text")?"rewrote":o.some(a=>["color","background","strokeColor"].includes(a))?"recoloured":o.some(a=>["fontSize","fontFamily","fontWeight","lineHeight","textAlign"].includes(a))?"restyled the type of":o.some(a=>["width","height"].includes(a))?"resized":o.some(a=>["x","y"].includes(a))?"moved":"adjusted"} ${n(e.elementId)}`}case"MoveElement":return`moved ${n(e.elementId)}`;case"AddElement":return`added ${e.element.type==="text"?"a text block":"a shape"}`;case"DeleteElement":return`removed ${n(e.elementId)}`;case"DeleteElements":return`removed ${e.elementIds.length} elements`;case"ReorderElementsZ":return"reordered the layers";case"UpdateSlideTitle":return"updated the title";case"UpdateSlideAppearance":return"changed the slide background";case"SetChart":return`set the chart to a ${e.chartType} chart`;case"SetImageFill":return"placed an image";default:return"made a change"}}const Pr=e=>e?[{x:e.x,y:e.y,width:e.width,height:e.height,radius:e.cornerRadius??8}]:[];function Wb(e,t,n){const o=(i,a)=>i.elements.find(l=>l.id===a);switch(n.type){case"UpdateElement":case"MoveElement":return Pr(o(t,n.elementId));case"AddElement":return Pr(o(t,n.element.id));case"DeleteElement":return Pr(o(e,n.elementId));case"DeleteElements":return n.elementIds.flatMap(i=>Pr(o(e,i)));case"UpdateSlideTitle":return Pr(Du(t.elements));case"SetChart":return Pr(t.elements.find(rn));case"UpdateSlideAppearance":return[{x:0,y:0,width:1920,height:1080,radius:0}];case"ReorderElementsZ":default:return[]}}function Du(e){const t=e.filter(n=>n.type==="text");return t.find(n=>n.textRole==="Display")??t.find(n=>n.textRole==="H1")??[...t].sort((n,o)=>
5(n.y??0)-(o.y??0))[0]}function Hb(e,t,n){const o=e.elements;switch(t.type){case"UpdateElement":return{...e,elements:o.map(i=>{if(i.id!==t.elementId)return i;const a={...i,...t.patch};return rn(i)&&(t.patch.width!=null||t.patch.height!=null)&&(a.fillImage=void 0,a.shapeFillMode="color"),a})};case"MoveElement":return{...e,elements:o.map(i=>i.id===t.elementId?{...i,x:t.x,y:t.y}:i)};case"AddElement":return{...e,elements:[...o,t.element]};case"DeleteElement":return{...e,elements:o.filter(i=>i.id!==t.elementId)};case"DeleteElements":{const i=new Set(t.elementIds);return{...e,elements:o.filter(a=>!i.has(a.id))}}case"ReorderElementsZ":{const i=t.orderedIdsTopFirst,a=new Map(i.map((u,c)=>[u,i.length-c])),l=o.reduce((u,c)=>Math.max(u,c.zIndex??0),0)+1;return{...e,elements:o.map(u=>a.has(u.id)?{...u,zIndex:l+(a.get(u.id)??0)}:u)}}case"UpdateSlideTitle":{const i=Du(o);return i?{...e,elements:o.map(a=>a.id===i.id?{...a,text:t.title}:a)}:e}case"UpdateSlideAppearance":{if(!t.patch.background)return e;const i={...e,background:t.patch.background};return t.patch.slideFillMode!=="image"&&(i.fillGradient=void 0),i}case"SetChart":{if(n==null)return e;const i=t.target,a=i.kind==="element"?o.find(d=>d.id===i.elementId):void 0,l=i.kind==="newBlock"?{x:i.x,y:i.y,width:i.width,height:i.height}:a?{x:a.x,y:a.y,width:a.width,height:a.height}:null;if(!l)return e;const u=o.filter(d=>!rn(d)&&d.id!==(a==null?void 0:a.id)),c=u.reduce((d,p)=>Math.max(d,p.zIndex??0),0)+1;return{...e,elements:[...u,Zi(n,l,c)]}}case"SetImageFill":return e;default:return e}}function Ub(e){if(!e||typeof e!="object")return[];const t=e.commands;return Array.isArray(t)?t:[]}async function Xb(e,t){const{slideId:n,model:o,signal:i}=e,a=_b(n,e.baked),l=new Set(e.baked.elements.map(w=>w.id)),u=w=>{switch(w.type){case"AddElement":case"UpdateSlideTitle":case"UpdateSlideAppearance":case"SetImageFill":return!0;case"UpdateElement":case"MoveElement":case"DeleteElement":return l.has(w.elementId);case"SetChart":return w.target.kind==="newBlock"||l.has(w.target.elementId);case"DeleteElements":return w.elementIds.every(x=>l.has(x));case"ReorderElementsZ":return w.orderedIdsTopFirst.every(x=>l.has(x));default:return!1}};let c=e.baked,d=0,p=!1;const h=w=>{const x=lg.safeParse(w);if(!x.success)return;const D=x.data;if(D.type==="SetImageFill"){p=!0;return}if(!u(D)||Ob(D,c))return;const R=c;c=Hb(c,D,n),D.type==="AddElement"&&l.add(D.element.id),d+=1,t.onApply(c,D,Wb(R,c,D))},m=await fetch("/deckgen-edit-api",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instruction:e.instruction,slides:[a],model:o,images:e.images??[]}),signal:i});if(!m.ok||!m.body)return{applied:0,skippedImages:!1};const g=m.body.getReader(),k=new TextDecoder;let y="",f=0,I=0;for(;;){const{done:w,value:x}=await g.read();if(w)break;y+=k.decode(x,{stream:!0});const D=Date.now();if(D-I<90)continue;I=D;const{value:R}=await ig(Nc(y)),j=Ub(R);for(let S=f;S<j.length-1;S++)h(j[S]),f=S+1}try{const w=ag.safeParse(JSON.parse(Nc(y)));if(w.success)for(let x=f;x<w.data.commands.length;x++)h(w.data.commands[x]),f=x+1}catch{}return{applied:d,skippedImages:p}}function Yb(e,t={}){const n=(g,k,y=`${k}s`)=>`${g} ${g===1?k:y}`,o=e.elements.filter(g=>g.type==="text"&&!rn(g)).length,i=e.elements.filter(g=>g.shapeFillMode==="image"&&!rn(g)).length,a=e.elements.some(rn),l=e.elements.length-o-i-(a?1:0),u=[];t.refSlides&&u.push(n(t.refSlides,"reference slide")),t.refImages&&u.push(n(t.refImages,"reference image")),t.refDocs&&u.push(t.refDocs===1?"the wired document":`${t.refDocs} wired documents`),t.refNotes&&u.push(t.refNotes===1?"a note":`${t.refNotes} notes`);const c=g=>g.length<=1?g.join(""):`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`,d=[];o&&d.push(n(o,"text block")),l>0&&d.push(n(l,"shape")),i&&d.push(n(i,"image")),a&&d.push("a chart");const p=[];let h=t.updateInPlace?"I updated the slide and kept its design":t.reroll?"I redesigned the slide with a new composition":"I generated the slide";u.length&&(h+=` from ${c(u)}`),p.push(`${h}.`),d.length&&p.push(`It has ${c(d)}.`);const m=[];return t.creativity!=null&&m.push(`creativity ${t.creativity.toFixed(2)}`),t.textDensity&&m.push(`${t.textDensity} text`),m.length&&p.push(`I used ${c(m)}, which you can tweak in the slideâs â settings.`),p.join(` 6`)}function ws(e){const t=o=>
6{const i=o.x+o.width/2,a=o.y+o.height/2,l=i<1920/3?"left":i<1920*2/3?"centre":"right";return`${a<1080/3?"top":a<1080*2/3?"middle":"bottom"}-${l}`},n=[`- background: ${e.background??"#ffffff"}`];for(const o of e.elements.slice(0,14)){const i=`${Math.round(o.width/1920*100)}%Ã${Math.round(o.height/1080*100)}%`;if(rn(o))n.push(`- chart at ${t(o)} (${i})`);else if(o.type==="text"){const a=(o.text??"").trim().replace(/\s+/g," ").slice(0,40);n.push(`- text "${a}" at ${t(o)} (${i}, ${o.fontSize??"?"}px, ${o.color??"inherit"})`)}else n.push(`- ${o.type} at ${t(o)} (${i}${o.background?`, ${o.background}`:""})`)}return e.elements.length>14&&n.push(`- â¦and ${e.elements.length-14} more elements`),n.join(` 7`)}function Kb(e){return/\b(add|generate|create|make|build|design)\s+(?:a|an|another|one)(?:\s+\w+)?\s+slides?\b/i.test(e)}function Vb(e,t){const n=e.toLowerCase();if(!n.trim()||!t.length)return[];const o=/\b(remove|delete|drop|erase|scrap|get rid of|take (?:out|off|away)|without|no longer|swap(?: out)?|replace|switch(?: out)?|substitute)\b/g,i=/\b(add|insert|include|put|place|bring|fetch|keep|with)\b/g,a=/\b(swap(?: out)?|replace|switch(?: out)?|substitute)\b/g,l=/\b(?:all|every|each|both)\b[\s\S]{0,12}?\b(?:logos?|images?|pictures?|brands?|marks?|them|these)\b/,u=g=>{const k=[];let y;for(g.lastIndex=0;y=g.exec(n);)k.push(y.index);return k},c=u(o);if(!c.length)return[];const d=u(i);for(const g of u(a))for(const k of[" for "," with "]){const y=n.indexOf(k,g);y>g&&d.push(y+1)}if(c.some(g=>l.test(n.slice(g,g+60)))&&!t.some(g=>n.includes(g.toLowerCase())))return[...t];const h=g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),m=(g,k)=>g.reduce((y,f)=>f<k&&f>y?f:y,-1);return t.filter(g=>{const k=[g.toLowerCase()],y=g.toLowerCase().split(".")[0];y&&y!==k[0]&&k.push(y);for(const f of k){const I=new RegExp(`\\b${h(f)}\\b`).exec(n);if(!I)continue;const w=m(c,I.index);if(w>=0&&w>m(d,I.index))return!0}return!1})}function qb(e){return/\b(duplicate|copy)\b/i.test(e)||/\b(a|one)\s+(second|2nd|third|3rd|extra|additional|other)\s+(version|take|variation|copy|one)\b/i.test(e)||/\b(second|another)\s+one\b/i.test(e)}function od(e){const t=e.replace(/\breference\s+(images?|photos?|slides?|pictures?)\b/gi,"references").replace(/\bwith\s+(the\s+|those\s+|these\s+)?references?\b/gi,"");return/\b(title|headline|header|heading|subtitle|caption|text|paragraph|bullets?|lists?|charts?|graphs?|images?|photos?|icons?|logos?|shapes?|buttons?|background|colou?rs?|palette|fonts?|typography)\b/i.test(t)?!1:/\banother\s+(version|take|variation|layout|design|look)\b/i.test(t)||/\b(completely|totally|entirely|radically)\s+different\s+(version|take|variation|layout|design|look|slide|composition)\b/i.test(t)}function id(e){const t=(e??"").trim();return!t||t.length>60?!1:/^(can you |could you |please )?(just )?(continue|carry on|keep going|go on|proceed|go ahead|finish( it| them| that)?)\b[\s.!?]*$/i.test(t)}function Ci(e){const t=e??"";return/\b(re-?creat\w*|re-?build\w*|re-?do|re-?done|re-?generat\w*|re-?make|remade|re-?work\w*|re-?design\w*)\b/i.test(t)||/\bfrom\s+scratch\b/i.test(t)||/\bstart\s+over\b/i.test(t)||/\b(much|way|far|significantly)\s+better\b/i.test(t)}function ad(e){const t=e.match(/\b(a couple(?: of)?|two|three|four|[234])\s+(?:more\s+|different\s+|new\s+|other\s+)*(?:types?\s+of\s+)?(?:versions?|options?|variants?|takes?|slides?|designs?|layouts?)\b/i);if(!t)return null;const n=t[1].toLowerCase(),o=n.startsWith("a couple")||n==="two"||n==="2"?2:n==="three"||n==="3"?3:4;return Math.min(4,Math.max(2,o))}function Jb({slidesRef:e,conversationId:t,patch:n,prebakeThumb:o,requestSave:i}){const[a,l]=s.useState(null),[u,c]=s.useState(!1),[d,p]=s.useState([]),[h,m]=s.useState(null),[g,k]=s.useState(null),[y,f]=s.useState(null),[I,w]=s.useState(!1),[x,D]=s.useState(!1),R=s.useRef(new Map),j=s.useCallback((W,H=6)=>{const ae=[];for(const[ge,J]of[...R.current].reverse())if(ge!==W){for(const ce of J)ae.includes(ce)||ae.push(ce);if(ae.length>=H)break}return ae.slice(0,H)},[]),{uploadImageAndGetUrl:S}=Cd(t),A=s.useCallback(W=>{var ae;const H=(((ae=W.baked)==null?void 0:ae.elements)??[]).filter(ge=>ge.type==="text"&&typeof ge.text=="string"&&ge.text.trim()).slice().sort((ge,J)=>(J.fontSize??0)-(ge.fontSize??0)).map(ge=>ge.text.trim());return{slideTitle:H[0]??"",slideText:H.slice(1).join(` 8`)}},[]),O=s.useCallback(async(W,H,ae)=>{const{slideTitle:ge,slideText:J}=A(W),ce=e.current.filter(K=>K.id!==W.id&&K.groupId===W.groupId&&K.baked).slice(0,4).map(K=>
8A(K).slideTitle).filter(Boolean),we=await fetch("/deckgen-concepts-api",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slideTitle:ge,slideText:J,deckGoal:W.prompt??"",neighbourTitles:ce,slideDesign:W.baked?ws(W.baked):"",recentArchetypeIds:j(W.id).filter(K=>!ae.includes(K)),freeRectAspect:H.width/H.height,excludeArchetypeIds:ae,count:6})}),ve=await we.json().catch(()=>null);if(!we.ok)throw new Error((ve==null?void 0:ve.error)||"Could not propose ideas for this slide.");const oe=Lm(ve==null?void 0:ve.concepts),pe=R.current.get(W.id)??[];return R.current.delete(W.id),R.current.set(W.id,[...pe,...oe.map(K=>K.archetypeId)]),oe},[A,j,e]),T=s.useCallback(async W=>{const H=e.current.find(ce=>ce.id===W);if(!H)return;const ae=document.querySelector(`[data-deckgen-slide-surface][data-slide-id="${W}"]`),ge=ae==null?void 0:ae.getBoundingClientRect();k(ge?{x:ge.left,y:ge.top,width:ge.width,height:ge.height}:null),l(W),p([]),m(null),D(!1),R.current.delete(W);const J=di(H.baked);if(!J){m("No free space left on this slide. Move something or clear it, then try again.");return}c(!0);try{p(await O(H,J,[]))}catch(ce){m(ce instanceof Error?ce.message:"Could not propose ideas for this slide.")}finally{c(!1)}},[O,e]),X=s.useCallback(async()=>{const W=a;if(W==null)return;const H=e.current.find(ge=>ge.id===W),ae=H?di(H.baked):null;if(!(!H||!ae)){w(!0),m(null);try{const ge=d.map(ve=>ve.archetypeId),J=await O(H,ae,ge),ce=new Set(ge),we=J.filter(ve=>!ce.has(ve.archetypeId));we.length===0&&D(!0),p(ve=>[...ve,...we])}catch(ge){m(ge instanceof Error?ge.message:"Could not propose more ideas.")}finally{w(!1)}}},[d,a,O,e]),L=s.useCallback(async(W,H)=>{var Y,re,le;const ae=a;if(ae==null)return;const ge=e.current.find(b=>b.id===ae);if(!ge)return;f(H);const J=di(ge.baked);if(!J){m("No free space left on this slide. Move something or clear it, then try again.");return}const ce=zm(J,((Y=na(W.archetypeId))==null?void 0:Y.aspect)??16/9),we=du(W.archetypeId,W.labels,{width:Math.round(ce.width),height:Math.round(ce.height)});let ve;try{const b=new File([we],`concept-${W.archetypeId}.svg`,{type:"image/svg+xml"});ve=await S(b)}catch{ve=_m(we)}const oe=e.current.find(b=>b.id===ae);if(!oe){f(null);return}const pe=(((re=oe.baked)==null?void 0:re.elements)??[]).filter(Om).length,K=Bm(ae,pe,ve,ce),fe={...oe.baked??{elements:[]},elements:[...((le=oe.baked)==null?void 0:le.elements)??[],K]},ie=gn(fe,ae);n(ae,{baked:fe,html:ie}),o(ie),i(),f(null),l(null)},[a,n,o,i,e,S]);return{conceptsSlideId:a,setConceptsSlideId:l,conceptsLoading:u,concepts:d,conceptsError:h,conceptsAnchor:g,conceptPicking:y,conceptsMoreLoading:I,conceptsExhausted:x,openConcepts:T,loadMoreConcepts:X,pickConcept:L}}function Vi(e,t,n){const o=[],i=l=>{t&&e(u=>{const c=u[t]??n(),d={...u,[t]:{...c,...l}},p=Object.keys(d);return p.length<=8?d:Object.fromEntries(p.slice(p.length-8).map(h=>[h,d[h]]))})};return{stepLog:o,reportActivity:i,setStep:(l,u)=>{const c=o.findIndex(d=>d.label===l);c>=0?o[c]={label:l,status:u}:o.push({label:l,status:u}),i({steps:[...o]})}}}function Zb({store:e,openIdRef:t,conversationId:n,chatMessagesRef:o}){const{slidesRef:i,imagesRef:a,selectedIdsRef:l,selectedDocIdsRef:u,selectedNoteIdsRef:c,selectedImageIdsRef:d,clearSelection:p}=e,h=n?`birtvy:editReceipts:${n}`:null,[m,g]=s.useState({}),k=s.useRef({}),[y,f]=s.useState([]);s.useEffect(()=>{if(h)try{const H=window.localStorage.getItem(h);f(H?JSON.parse(H):[])}catch{f([])}},[h]);const I=s.useCallback((H,ae)=>{if(!h)return;const ge=(o.current??[]).find(ce=>ce.id===H),J=(((ge==null?void 0:ge.content)??"").trim().slice(0,120)||k.current[H]||"").trim();J&&f(ce=>{const we=[...ce.filter(ve=>ve.anchor!==J),{anchor:J,state:ae}].slice(-40);try{window.localStorage.setItem(h,JSON.stringify(we))}catch{}return we})}
8,[h]),w=s.useRef(null),x=s.useRef([]),D=s.useRef(new Map),R=s.useRef({slideIds:[],docIds:[],noteIds:[],imageIds:[]}),j=s.useRef([]),S=s.useRef([]),A=s.useRef(null),O=s.useRef([]),T=s.useRef(!1),X=s.useCallback(()=>{const H=[...l.current];if(R.current={slideIds:H,docIds:[...u.current],noteIds:[...c.current],imageIds:[...d.current]},j.current=[],S.current=[],H.length>0&&(O.current=H),H.length===1)w.current=H[0];else if(H.length>1){const ae=H.filter(ge=>{const J=i.current.find(ce=>ce.id===ge);return J&&!J.baked&&!J.html&&J.status!=="generating"});ae.length===1?w.current=ae[0]:t.current!=null&&(w.current=t.current)}else t.current!=null&&(w.current=t.current);x.current=[...d.current].map(ae=>{var ge;return(ge=a.current.find(J=>J.id===ae))==null?void 0:ge.src}).filter(ae=>!!ae),p()},[p]),L=s.useCallback(()=>{const H=ge=>ge!=null&&i.current.some(J=>J.id===ge&&J.baked&&J.status!=="generating");if(H(w.current))return w.current;if(H(t.current))return t.current;const ae=i.current.filter(ge=>ge.baked&&ge.status!=="generating");return ae.length===1?ae[0].id:null},[]);return{turn:s.useMemo(()=>({chatEditRefsRef:R,chatEditTargetRef:w,chatEditStickySlidesRef:O,chatEditStyleImagesRef:x,chatEditAnchorsRef:k,turnPlacedImageIdsRef:j,turnSkippedLogosRef:S,slideEditHistoryRef:D,placeImagesInFlightRef:A,rebuildOwedRef:T}),[R,w,O,x,k,j,S,D,A,T]),handleMessageSent:X,resolveChatEditTarget:L,chatEditActivity:m,setChatEditActivity:g,persistedReceipts:y,persistReceipt:I}}const Qb=new Set(["js","ts","jsx","tsx","py","rb","php","css","html","json","xml","yml","yaml"]),ld=new Set(["next.js","nextjs","next js"]);function ew(e){const t=e.toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0].trim();if(!t)return null;const n=t.includes(".")?t.slice(t.lastIndexOf(".")+1):"",o=/^[a-z0-9.-]+\.[a-z]{2,}$/.test(t)&&!Qb.has(n),i=o?t.slice(0,t.indexOf(".")):t;return{cleaned:t,isDomain:o,label:i,naiveDotCom:o&&t===`${i}.com`,unsupported:ld.has(t)||ld.has(i)}}function xn(e){const t=ew(e);if(!t)return e;const n=t.isDomain?t.label:e;return n.length>1&&n===n.toLowerCase()?n[0].toUpperCase()+n.slice(1):n}const tw=e=>{if(typeof DOMParser>"u"||!/data-el=["']chart["']/.test(e))return null;try{const t=new DOMParser().parseFromString(e,"text/html").querySelector('[data-el="chart"]'),n=((t==null?void 0:t.textContent)||"").replace(/\s+/g," ").trim();return!t||!n?null:{chartType:(t.getAttribute("data-chart-type")||"").trim(),dataText:n}}catch{return null}};function nw({images:e,pickedImages:t,catalog:n,out:o,clusterGidByIndex:i,layout:a,baseX:l,pgid:u,setImages:c,setGroups:d}){var h;const p=e.filter(m=>t.has(String(m.id))&&m.groupId==null);if(p.length){const m=Ht,g=R=>{const j=n.find(A=>A.id===`img${R}`);if(!j)return[];const S=[];return o.forEach((A,O)=>{A&&A.includes(j.url)&&S.push(O)}),S},k=new Map,y=new Map,f=new Map,I=a.contentTop+Math.max(Je,Cn)+m,w=a.styles.length>0;let x=w?a.styleColBottom:a.contentTop;const D=[];for(const R of p){const j=g(R.id);if(j.length===0)continue;const S=j.length===1?i.get(j[0]):void 0;if(j.length===1&&S!=null){const A=a.clusters.get(j[0]);if(!A)continue;const O=f.get(S)??A.x+m;k.set(R.id,{x:O,y:I,groupId:S}),f.set(S,O+R.width+m);const T=y.get(S)??[];T.push({x:O,y:I,width:R.width,height:R.height}),y.set(S,T)}else{const A=w?a.styleColX:l-m*2-R.width;k.set(R.id,{x:A,y:x,groupId:u}),D.push({x:A,y:x,width:R.width,height:R.height}),x+=R.height+m}}if(k.size){c(j=>j.map(S=>{const A=k.get(S.id);return A?{...S,...A}:S}));const R=new Map;for(const[j,S]of y){const A=(h=[...i].find(([,L])=>L===j))==null?void 0:h[0],O=A!=null?a.clusters.get(A):void 0;if(!O)continue;const T={x:O.x+m,y:O.y+m,width:O.width-m*2,height:O.height-m*2},X=cn([T,...S]);X&&R.set(j,X)}d(j=>j.map(S=>{const A=R.get(S.id);if(A)return an(S,A);if(S.id===u){const O=cn([{x:a.parentRect.x+m,y:a.parentRect.y+m,width:a.parentRect.width-m*2,height:a.parentRect.height-m*2},...D,...[...R.values()].map(T=>({x:T.x,y:T.y-Wt,width:T.width,height:T.height+Wt}))]);return O?an(S,O):S}return S}))}}}function rw({store:e,sections:t,planningModel:n,liveModelRef:o,model:i,agentDocsRef:a,titleRef:l,designSystemsRef:u,activeDesignSystemIdRef:c,setActiveDesignSystem:d,brandKitBindingRef:p,deckGenRunning:h,setDeckGenRunning:m,setGenDeckGid:g,setFlowModalOpen:k,flashGroup:y,fillChart:f,startChartPrerender:I,chartPngRef:w,runGraphyForChart:x,generateSlide:D,generateDocSlide:R,editBarImages:j,findClearRowY:S,slideGenCreativity:A}){const{slidesRef:O,docsRef:T,notesRef:X,imagesRef:L,wiresRef:W,setSlides:H,setDocs:ae,setImages:ge,setWires:J,setGroups:ce,setSelectedIds:we,setSelectedDocIds:ve,setSelectedNoteIds:oe,setSelectedImageIds:pe,idRef:K,requestSave:fe,flushSave:ie,focusRectRef:Y,showToast:re}=e,le=s.useCallback(async C=>{var xt,Xe,Ue,_e,yt,bt,Rt,Nt,vt;if(h)return;C.designSystemId!==void 0&&C.designSystemId!==c.current&&d(C.designSystemId);const z=gc(t==null?void 0:t.find(je=>je.sectionType==="GOAL")),B=gc(t==null?void 0:t.find(je=>je.sectionType==="OUTLINE")),M=new Set(C.selected.documents??[]),q=new Set(C.selected.notes??[]),ue=new Set(C.selected.images??[]),ye=[vg({goal:z,outline:B,documents:T.current.filter(je=>M.has(String(je.id))).map(je=>({title:je.title||"Document",content:je.content})),notes:X.current.filter(je=>{var Oe;return q.has(String(je.id))&&((Oe=je.content)==null?void 0:Oe.trim())}).map(je=>({content:je.content})),websites:[]})];C.palette&&!((xt=C.styleImages)!=null&&xt.length)&&ye.push(` 9## Palette 10Use a ${C.palette} colour palette for the deck.`);const ee=_i(t).filter(je=>je.key.startsWith("canvas:")).length;let U=C.slideCount??8;ee>=2&&(U=ee,ye.push(` 11Produce EXACTLY ${U} slides â one per outline section, in the outline's order. Section 1 is the deck's opening/title slide.`));const _=L.current.filter(je=>ue.has(String(je.id))&&/^https?:\/\//i.test(je.src)).map(je=>({id:`img${je.id}`,url:je.src,description:je.label?`The official ${xn(je.label)} logo/image. Use this file ONLY where the deck refers to ${xn(je.label)}, and never next to any other name.`:"Image from the user's canvas â place it where it fits.",naturalWi
11dth:je.width,naturalHeight:je.height})),N=o.current??n,Z=N&&km[N]||i,Q=[...O.current.map(je=>({x:je.x,y:je.y,w:Ke,h:Je})),...T.current.map(je=>({x:je.x,y:je.y,w:je.width,h:je.height})),...X.current.map(je=>({x:je.x,y:je.y,w:je.width,h:je.height})),...L.current.map(je=>({x:je.x,y:je.y,w:je.width,h:je.height}))],G=Object.values(a.current).map(je=>T.current.find(Oe=>Oe.id===je)).filter(je=>!!je).map(je=>je.x),se=G.length?Math.min(...G):Q.length?Math.min(...Q.map(je=>je.x)):0,ne=Q.length?Math.max(...Q.map(je=>je.y+je.h))+In*2:0,de=[];if((Xe=C.styleImages)!=null&&Xe.length){const je=await Promise.all(C.styleImages.map(Oe=>ko(Oe)));C.styleImages.forEach((Oe,tt)=>{const{width:ot,height:mt}=Wr(je[tt].width,je[tt].height);de.push({id:K.current++,width:ot,height:mt,src:Oe})})}const F=ee>=2?_i(t).filter(je=>je.key.startsWith("canvas:")).map(je=>a.current[je.key]):[],$=new Set;F.forEach((je,Oe)=>{je!=null&&Oe<U&&T.current.some(tt=>tt.id===je)&&$.add(Oe)});const P=Vy({count:U,docIndices:$,styleSizes:de,baseX:se,baseY:ne,cols:Od,gap:In}),me=K.current++,he=l.current&&l.current!=="Untitled"?l.current:((Ue=z==null?void 0:z.split(` 12`)[0])==null?void 0:Ue.trim().slice(0,48))||"Presentation",Me=new Map,He=new Map,Ee=[],qe=[];for(const je of $){const Oe=T.current.find($e=>$e.id===F[je]),tt=P.docs.get(je),ot=P.clusters.get(je);if(!Oe||!tt||!ot)continue;const mt=K.current++,dt=K.current++;
12Me.set(je,mt),He.set(je,dt),Ee.push(an({id:mt,title:((_e=Oe.title)==null?void 0:_e.trim())||`Slide ${je+1}`,parentId:me,snap:!0},ot)),qe.push({id:dt,x:tt.x,y:tt.y,width:En,height:Cn,content:Oe.content,title:Oe.title,documentId:Oe.documentId,groupId:mt})}const Ae=[],jt=Array.from({length:U},(je,Oe)=>{const tt=K.current++;Ae.push(tt);const ot=P.slides[Oe];return{id:tt,x:ot.x,y:ot.y,status:"generating",prompt:"",groupId:Me.get(Oe)??me}});ce(je=>[...je,an({id:me,title:he},P.parentRect),...Ee]),H(je=>[...je,...jt]),qe.length&&ae(je=>[...je,...qe]),de.length&&ge(je=>[...je,...de.map((Oe,tt)=>({id:Oe.id,x:P.styles[tt].x,y:P.styles[tt].y,width:Oe.width,height:Oe.height,src:Oe.src,groupId:me}))]);{const je=[];for(const[Oe,tt]of He)je.push({id:K.current++,from:{kind:"doc",id:tt},to:{kind:"slide",id:Ae[Oe]}});!He.has(0)&&a.current.goal!=null&&Ae[0]!=null&&je.push({id:K.current++,from:{kind:"doc",id:a.current.goal},to:{kind:"slide",id:Ae[0]}}),je.length&&J(Oe=>[...Oe,...je])}g(me),y(me),m(!0),k(!1),fe();let kt=null,Ge=null;const Qe=new Set,ht=()=>{if(Ge=null,!kt)return;const je=kt;kt=null,H(Oe=>Oe.map(tt=>{const ot=Ae.indexOf(tt.id);return ot>=0&&je[ot]?{...tt,html:je[ot]}:tt}));for(let Oe=0;Oe<je.length-1;Oe++){const tt=Ae[Oe];if(tt==null||Qe.has(tt))continue;Qe.add(tt);const ot=tw(je[Oe]);ot&&f(tt,ot.dataText,ot.chartType)}for(let Oe=0;Oe<je.length;Oe++){const tt=Ae[Oe];if(tt==null)continue;const ot=pu(je[Oe]);ot&&I(tt,ot.dataText,ot.chartType,ot.w,ot.h)}};try{let je,Oe=null;if((yt=C.styleImages)!=null&&yt.length){const dt=await Eo(C.styleImages,aa(Z)?Z:"gemini-3.5-flash");if(dt){const $e=oa(dt),lt=ra(ia($e,100));lt&&ye.push("",lt),je=Jd($e)}}else{const dt=await sa({activeKit:Co(u.current,C.designSystemId===void 0?c.current:C.designSystemId),binding:p.current,optOut:C.designSystemId===null});(bt=dt.inputs)!=null&&bt.promptBlock&&ye.push("",dt.inputs.promptBlock),je=(Rt=dt.inputs)==null?void 0:Rt.brandStyle,Oe=dt.binding&&dt.binding!==p.current?dt.binding:null}const tt=await Kd(ye.join(` 13`),Z,dt=>{kt=dt,Ge==null&&(Ge=requestAnimationFrame(ht))},{slideCount:U,images:(Nt=C.styleImages)!=null&&Nt.length?C.styleImages:void 0,imageMode:(vt=C.styleImages)!=null&&vt.length?"style":void 0,catalog:_.length?_:void 0,brandStyle:je,creativity:C.creativity,textDensity:C.textDensity});if(Ge!=null&&cancelAnimationFrame(Ge),kt=null,!(tt!=null&&tt.length))throw new Error("Generation returned no slides");Oe&&(p.current=Oe),await Dd(tt.join(` 14`));const ot=await Vd(tt,Xd(p.current)),mt=[];H(dt=>dt.map($e=>{const lt=Ae.indexOf($e.id);if(lt<0)return $e;const it=tt[lt],Dt=ot==null?void 0:ot.slides[lt];if(it&&Dt&&Dt.elements.length>0){const en=Dt.elements.map((tn,sn)=>Nd(tn,`birtvy${$e.id}e${sn}`,sn,{exact:!0})).filter(tn=>tn!==null),Bt=Dt.charts[0];if(Bt){const tn=en.reduce((Jt,Re)=>Math.max(Jt,Re.zIndex??0),0)+1,sn=Zi($e.id,Bt,tn),dn=w.current.get($e.id);if(dn&&dn.w>0){const Jt=Math.max(8,Math.round(sn.width*dn.h/dn.w));Object.assign(sn,{height:Jt,fillImage:dn.png,shapeFillMode:"image",imageFit:"fill"})}en.push(sn),mt.push({slideId:$e.id,dataText:Bt.dataText,chartType:Bt.chartType})}if(en.length>0){const tn={background:Dt.background,fillGradient:Dt.fillGradient,elements:en};return{...$e,html:gn(tn,$e.id),baked:tn,status:"done"}}}return it?{...$e,html:it,status:"done"}:{...$e,status:"empty"}}));for(const dt of mt)Qe.has(dt.slideId)||f(dt.slideId,dt.dataText,dt.chartType);nw({images:L.current,pickedImages:ue,catalog:_,out:tt,clusterGidByIndex:Me,layout:P,baseX:se,pgid:me,setImages:ge,setGroups:ce}),y(me),fe()}catch(je){console.warn("birtvy: deck generation failed",je),re({title:je instanceof qd?"Out of Deck credits â top up or upgrade to keep generating.":"Deck generation failed. Try again.",variant:"error"}),H(Oe=>Oe.map(tt=>Ae.includes(tt.id)?{...tt,status:"empty",html:void 0}:tt)),fe()}finally{m(!1),g(null)}},[h,t,n,i,fe,re,y,x,d]),b=s.useCallback(async(C,z)=>{var se;const B=O.current.find(ne=>ne.id===C);if(!B||B.status==="generating")return;if(B.docHtml){R(C,B.prompt||"Improve this slide. Keep its style.",j!=null&&j.length?{referenceImages:j}:void 0);return}if(z<=1){D(C,i);return}const M=!!(B.baked||B.html),q=M?z:z-1,ue=S(B.x+Ke+In,B.y,q),ye=Array.from({length:q},(ne,de)=>({id:K.current++,x:B.x+(Ke+In)*(de+1),y:ue,status:"empty",prompt:B.prompt}));H(ne=>[...ne,...ye.filter(de=>!ne.some(F=>F.id===de.id))]),O.current=[...O.current,...ye];const ee=W.current.filter(ne=>ne.to.kind==="slide"&&ne.to.id===C),U=[];for(const ne of ye){for(const de of ee)U.push({id:K.current++,from:
14de.from,to:{kind:"slide",id:ne.id},mode:de.mode,styleStrength:de.styleStrength});M&&U.push({id:K.current++,from:{kind:"slide",id:C},to:{kind:"slide",id:ne.id}})}U.length&&(W.current=[...W.current,...U],J(ne=>[...ne,...U.filter(de=>!ne.some(F=>F.id===de.id))])),ie();const _=M?ye.map(ne=>ne.id):[C,...ye.map(ne=>ne.id)];{const ne=[B,...ye].map(me=>({x:me.x,y:me.y,w:Ke,h:Je})),de=Math.min(...ne.map(me=>me.x)),F=Math.min(...ne.map(me=>me.y)),$=Math.max(...ne.map(me=>me.x+me.w)),P=Math.max(...ne.map(me=>me.y+me.h));(se=Y.current)==null||se.call(Y,{x:de,y:F,w:$-de,h:P-F},.86)}const N=Math.max(A[C]??Ur,.85),Z=ne=>[B.prompt||"Generate a slide.",...M&&B.baked?["","The user LIKED this original slide (it stays on the canvas) â match its style language:",ws(B.baked)]:[],"",`This is VARIANT ${ne+1} of ${z}, generated side by side with the others. Make it CLEARLY`,"DISTINCT from the other variants: a different composition, emphasis or background treatment."].join(` 15`),G=(await Promise.all(_.map((ne,de)=>D(ne,i,{promptOverride:Z(de),creativity:N,previewThrottleMs:250}).then(F=>({tid:ne,r:F}))))).filter(ne=>ne.r.ok).map(ne=>ne.tid);G.length&&(we(new Set(G)),ve(new Set),oe(new Set),pe(new Set))},[S,ie,D,i,A]);return{generateDeckFromPlan:le,generateVariantsFromToolbar:b}}function sw({store:e,turn:t,slideGenCreativity:n,slideGenTextDensity:o,designSystemsRef:i,activeDesignSystemIdRef:a,brandKitBindingRef:l,chartPngRef:u,chartPrerenderedRef:c,setChartPrerenderJobs:d,startChartPrerender:p,fillChart:h,runGraphyForChart:m}){const{slidesRef:g,docsRef:k,notesRef:y,imagesRef:f,wiresRef:I,websRef:w,patch:x,requestSave:D,showToast:R}=e,{turnSkippedLogosRef:j}=t,S=s.useRef(new Map),A=s.useCallback(async(T,X,L)=>{var M,q,ue,ye,ee,U,_,N,Z;const W=g.current.find(Q=>Q.id===T);if(!W||W.status==="generating")return{ok:!1};const H=L!=null&&L.keepCurrent?{html:W.html,baked:W.baked,graphyConfig:W.graphyConfig}:null,ae=new AbortController;S.current.set(T,ae),x(T,H?{status:"generating"}:{status:"generating",html:void 0,baked:void 0,graphyConfig:void 0}),c.current.delete(T),u.current.delete(T),d(Q=>Q.filter(G=>G.slideId!==T));const ge=I.current.filter(Q=>Q.to.kind==="slide"&&Q.to.id===T),J=ge.filter(Q=>Q.from.kind==="note").map(Q=>y.current.find(G=>G.id===Q.from.id)).find(Q=>!!Q&&/^\s*build with graphy\b/i.test(Q.content||""));if(J){(M=L==null?void 0:L.onPhase)==null||M.call(L,"chart");const Q=J.content.replace(/^\s*build with graphy\b[:,-]?\s*/i,"").trim();try{const G=await fetch("/birtvy-graphy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:Q}),signal:ae.signal}),se=await G.json();if(!G.ok||!se.config)throw new Error(se.error||"Graphy generation failed");const ne=Em(T,se.title||"",se.caption||"");return x(T,{graphyConfig:se.config,baked:ne,html:gn(ne,T),status:"done"}),D(),{ok:!0,baked:ne}}catch(G){if(!ae.signal.aborted){console.warn("birtvy: graphy generation failed",G);const se=G instanceof Error?G.message:"";R({title:/chartable data/i.test(se)?'No data to chart. Add numbers to the note, e.g. "TAM $10B, SAM $3.5B, SOM $750M".':`Couldn't build the chart${se?`: ${se}`:""}.`,variant:"error"})}x(T,H?{...H,status:"done"}:{status:"empty",graphyConfig:void 0}),D()}finally{S.current.delete(T)}return{ok:!1,aborted:ae.signal.aborted}}const ce=[];let we,ve;const oe=[],pe=[];for(const Q of ge)if(Q.from.kind==="image"){const G=f.current.find(se=>se.id===Q.from.id);if(!G)continue;if(Q.mode==="style"){const se=Q.styleStrength??100;if(se>=50){const ne=G.src.startsWith("data:")?G.src:await vs(G.src,1568);ne?(ce.push(ne),we=Math.max(we??0,se)):console.warn("[birtvy-ref] wired image could not be rasterized to a data URL â skipped")}}else oe.push({id:`img${G.id}`,url:G.src,description:G.label?`The official ${xn(G.label)} logo/image. Use this file ONLY where the slide refers to ${xn(G.label)}, and never next to any other name.`:"Image the user wired into this slide â feature it prominently.",naturalWidth:G.width,naturalHeight:G.height})}else if(Q.from.kind==="web"){const G=w.current.find(ne=>ne.id===Q.from.id);if(!G||(G.kind??"web")!=="web")continue;!ve&&G.brandStyle&&(ve=G.brandStyle);const se=(ue=(q=G.post)==null?void 0:q.text)==null?void 0:ue.trim();se&&pe.push(se)}else if(Q.from.kind==="note"){const G=y.current.find(se=>se.id===Q.from.id);(ye=G==null?void 0:G.content)!=null&&ye.trim()&&pe.push(G.content.trim())}else if(Q.from.kind==="doc"){const G=k.current.find(se=>se.id===Q.from.id);(ee=G==null?void 0:G.content)!=null&&ee.trim()&&pe.push(G.content.trim())}else if(Q.from.kind==="slide"){const G=g.current.find(ne=>ne.id===Q.from.id&&ne.id!==T),se=(G==null?void 0:G.html)??(G!=null&&G.baked?gn(G.baked,G.id):void 0);if(se&&G){const ne=await Nu(G.id,se);ne&&(ce.push(ne),we=Math.max(we??0,100))}}const K=((L==null?void 0:L.promptOverride)??W.prompt).trim(),fe=[K,...pe].find(Q=>vb(Q)),ie=ce.length>0&&!!fe,Y=ie?kb(fe)||"Reconstruct the reference.":["Create exactly ONE slide presenting this content (do not invent extra slides or extra topics):","",K||"Compose a single visually striking slide.",...pe.length?["","Wired context to draw from:",...pe]:[],...oe.length||j.current.length?["","BRAND IMAGES â HARD RULES. Real image files exist ONLY in the image catalog. Never draw,","recreate or approximate a logo or brand mark with shapes, letters or icons; a drawn mark","looks real and is counterfeit. A brand with no catalog file gets NO logo. Do not add","brands, companies or products the brief does not explicitly ask for.",...j.current.length?[`NO IMAGE FILE EXISTS for: ${j.current.map(xn).join(", ")}. Do not put them`,"on the slide in any form, even if the brief above asks for them by name."]:[]]:[]].join(` 16`),re=(L==null?void 0:L.creativity)??n[T]??Ur,le=(L==null?void 0:L.textDensity)??o[T]??Ro;if(ae.signal.aborted)return x(T,H?{...H,status:"done"}:{status:"empty",html:void 0,baked:void 0}),S.current.delete(T),D(),{ok:!1,aborted:!0};let b=null,C=null,z=null;const B=Q=>{if(!Q[0])return;b=Q[0];const G=pu(Q[0]);if(G&&p(T,G.dataText,G.chartType,G.w,G.h),L!=null&&L.previewThrottleMs){z==null&&(z=window.setTimeout(()=>{z=null,b!=null&&x(T,{html:b})},L.previewThrottleMs));return}C==null&&(C=requestAnimationFrame(()=>{C=null,b!=null&&x(T,{html:b})}))};try{let Q,G=Y,se=null;if(ce.length&&!ie){(U=L==null?void 0:L.onPhase)==null||U.call(L,"style");const F=await Eo(ce,aa(X)?X:"gemini-3.5-flash");if(F){const $=oa(F),P=ra(ia($,we??100));P&&(G=`${Y} 17 18${P}`),Q=Jd($,ve)}}else if(ve&&!ie)Q=Eg(ve);else{const F=ie,$=me=>{me&&!F&&(G=`${Y} 19 20${me}`)},P=await sa({activeKit:Co(i.current,a.current),binding:l.current});P.inputs&&($(P.inputs.promptBlock),Q=P.inputs.brandStyle),se=P.binding&&P.binding!==l.current?P.binding:null}(_=ve==null?void 0:ve.fontFaces)!=null&&_.length&&sg(ve.fontFaces),(N=L==null?void 0:L.onPhase)==null||N.call(L,"generate");const ne=await Kd(G,X,B,{slideCount:1,images:ce.length?ce:void 0,imageMode:ie?"reconstruct":ce.length?"style":void 0,styleStrength:we,brandStyle:Q,catalog:oe.length?oe:void 0,creativity:re,textDensity:le,signal:ae.signal}),de=ne==null?void 0:ne[0];if(!de||ae.signal.aborted)return x(T,H?{...H,status:"done"}:{status:"empty"}),D(),{ok:!1,aborted:ae.signal.aborted};se&&(l.current=se),x(T,{html:de});try{(Z=L==null?void 0:L.onPhase)==null||Z.call(L,"bake"),await Dd(de);const F=await Vd([de],Xd(l.current));if(ae.signal.aborted)return x(T,H?{...H,status:"done"}:{status:"empty",html:void 0,baked:void 0}),D(),{ok:!1,aborted:!0};const $=F==null?void 0:F.slides[0];if($&&$.elements.length>0){const P=$.elements.map((he,Me)=>Nd(he,`birtvy${T}e${Me}`,Me,{exact:!0})).filter(he=>he!==null),me=$.charts[0];if(me){const he=P.reduce((Ee,qe)=>Math.max(Ee,qe.zIndex??0),0)+1,Me=Zi(T,me,he),He=u.current.get(T);if(He&&He.w>0){const Ee=Math.max(8,Math.round(Me.width*He.h/He.w));Object.assign(Me,{height:Ee,fillImage:He.png,shapeFillMode:"image",imageFit:"fill"})}P.push(Me)}if(P.length>0){const he={background:$.background,fillGradient:$.fillGradient,elements:P};
20return x(T,{baked:he,html:gn(he,T),status:"done",graphyConfig:void 0}),me&&h(T,me.dataText,me.chartType),D(),{ok:!0,baked:he}}}}catch(F){console.warn("birtvy: bake failed, keeping raw HTML",F)}return ae.signal.aborted?(x(T,H?{...H,status:"done"}:{status:"empty",html:void 0,baked:void 0}),D(),{ok:!1,aborted:!0}):(x(T,H?{status:"done",baked:void 0,graphyConfig:void 0}:{status:"done"}),D(),{ok:!0})}catch(Q){return ae.signal.aborted||console.warn("birtvy: generation failed",Q),Q instanceof qd&&R({title:"Out of Deck credits â top up or upgrade to keep generating.",variant:"error"}),x(T,H?{...H,status:"done"}:{status:"empty",html:void 0,baked:void 0}),D(),{ok:!1,aborted:ae.signal.aborted}}finally{C!=null&&cancelAnimationFrame(C),z!=null&&window.clearTimeout(z),b=null,S.current.delete(T)}},[x,D,n,o,R,m]),O=s.useCallback(T=>{var X;(X=S.current.get(T))==null||X.abort()},[]);return{genAbortRef:S,generateSlide:A,stopGenerate:O}}function ow({deckChartSeries:e}){const t=s.useRef(new Map),n=s.useRef(new Set),o=s.useRef(0),[i,a]=s.useState([]),l=s.useCallback((u,c,d,p,h)=>{if(n.current.has(u))return;const m=da(c,d,void 0,e());if(!m)return;n.current.add(u);const g=++o.current;a(k=>k.some(y=>y.slideId===u)?k:[...k,{key:g,slideId:u,config:m,w:p,h}]),window.setTimeout(()=>{a(k=>k.some(y=>y.key===g)?(n.current.delete(u),k.filter(y=>y.key!==g)):k)},2e4)},[e]);return{chartPngRef:t,chartPrerenderedRef:n,chartPrerenderJobs:i,setChartPrerenderJobs:a,startChartPrerender:l}}const qi=new Map,Ei=new Map;function Tu(e){return[...e].sort().join(" ")}function iw(e){return qi.get(Tu(e))??null}function aw(e){if(e.length===0)return Promise.resolve(null);const t=Tu(e),n=qi.get(t);if(n)return Promise.resolve(n);const o=Ei.get(t);if(o)return o;const i=(async()=>{try{const a=(await Promise.all(e.map(d=>d.startsWith("data:")?Promise.resolve(d):vs(d,768)))).filter(d=>!!d);if(a.length===0)return null;const l=await Eo(a);if(!l)return null;const{title:u,...c}=l;return qi.set(t,c),c}catch{return null}finally{Ei.delete(t)}})();return Ei.set(t,i),i}const Ri=()=>{};function lw({store:e,editingSlideId:t,setEditingSlideId:n,setEditStatus:o,setEditCodeTail:i,setEditStartedAt:a,editTailAtRef:l,docThemeRef:u,designSystemsRef:c,activeDesignSystemIdRef:d,brandKitBindingRef:p,slideGenCreativity:h,slideGenTextDensity:m,slideGenPackages:g,writeDocSource:k,resolveDocLogos:y}){const{slidesRef:f,docsRef:I,notesRef:w,imagesRef:x,wiresRef:D,websRef:R,showToast:j}=e;return{generateDocSlide:s.useCallback(async(A,O,T)=>{var C;const X=O.trim();if(!X||t!=null)return;const L=f.current.find(z=>z.id===A);if(!(L!=null&&L.docHtml)||L.status==="generating")return;n(A),o("Writing the artifact"),i(null),a(Date.now()),l.current=0;const W=L.docHtml===Yd()||L.docHtml.length<320,H=(C=D.current.filter(z=>z.to.kind==="slide"&&z.to.id===A&&z.from.kind==="web").map(z=>R.current.find(B=>B.id===z.from.id)).find(z=>!!z&&(z.kind??"web")==="web"&&!!z.brandStyle))==null?void 0:C.brandStyle,ae=c||d||p?await sa({activeKit:Co((c==null?void 0:c.current)??[],(d==null?void 0:d.current)??null),binding:p==null?void 0:p.current}):null,ge=(ae==null?void 0:ae.kit)??null,J=ae!=null&&ae.binding&&ae.binding!==(p==null?void 0:p.current)?ae.binding:null,ce=D.current.filter(z=>z.to.kind==="slide"&&z.to.id===A&&z.from.kind==="image"&&z.mode==="style"&&(z.styleStrength??100)>=50).map(z=>{var B;return(B=x.current.find(M=>M.id===z.from.id))==null?void 0:B.src}).filter(z=>!!z&&z.trim()!=="");let we=null;ce.length>0&&(we=iw(ce),we||(o("Reading the image style"),we=await aw(ce),o("Writing the artifact")));const ve=$g({wiredWebStyle:H,brandKit:ge,wiredImageProfile:we,wiredImageCount:ce.length,docTheme:u.current}).recipe||void 0,oe=f.current.filter(z=>z.docHtml&&z.id!==A).map(z=>{var M;const B=((M=z.docMeta)==null?void 0:M.title)??qm(z.docHtml);return B?{title:B}:null}).filter(z=>z!==null),pe=D.current.filter(z=>z.to.kind==="slide"&&z.to.id===A&&(z.from.kind==="doc"||z.from.kind==="note"||z.from.kind==="web")).map(z=>{var M,q;if(z.from.kind==="doc"){const ue=I.current.find(ye=>ye.id===z.from.id);return ue!=null&&ue.content.trim()?{title:ue.title||void 0,content:ue.content}:null}if(z.from.kind==="web"){const ue=R.current.find(ee=>ee.id===z.from.id),ye=(q=(M=ue==null?void 0:ue.post)==null?void 0:M.text)==null?void 0:q.trim();return ye?{title:(ue==null?void 0:ue.title)||void 0,content:ye}:null}const B=w.current.find(ue=>ue.id===z.from.id);
20return B!=null&&B.content.trim()?{content:B.content}:null}).filter(z=>z!==null),K=(T==null?void 0:T.creativity)??(h==null?void 0:h[A])??Ur,fe=(T==null?void 0:T.textDensity)??(m==null?void 0:m[A])??Mg,ie=(T==null?void 0:T.packages)??(g==null?void 0:g[A])??[],Y=D.current.filter(z=>z.to.kind==="slide"&&z.to.id===A&&z.from.kind==="image"&&z.mode!=="style").map(z=>{var B;return(B=x.current.find(M=>M.id===z.from.id))==null?void 0:B.src}).filter(z=>!!z&&z.trim()!==""),re=[...(T==null?void 0:T.referenceImages)??[],...Y].filter((z,B,M)=>M.indexOf(z)===B),le={prompt:X,currentHtml:W?void 0:L.docHtml,themeRecipe:ve,siblings:oe.length?oe:void 0,sources:pe.length?pe:void 0,creativity:K,textDensity:fe,packages:ie.length?ie:void 0,referenceImages:re.length?re:void 0};ho.start(A);const b=z=>{ho.push(A,z);const{phase:B,tail:M}=Ag(z);o(B);const q=Date.now();q-l.current>=120&&(l.current=q,i(M||null))};try{let z=await Tc(le,b);Ri(A,`network stream ENDED (${z.length} chars)`);let B=Fi(z);if(B.rejects.length>0){o("Fixing the structure"),i(null),l.current=0;try{const ue=await Tc({...le,violations:bg(B)},b),ye=Fi(ue);ye.rejects.length<B.rejects.length&&(z=ue,B=ye)}catch{}}z=Pg(z,ie).html;const q=[...B.rejects.map(ue=>`contract: ${ue}`),...B.flags];J&&p&&(p.current=J),Ri(A,"writeDocSource COMMIT (document lands on slide)"),k(A,z,"chat",{prompt:X,flags:q.length?q:void 0}),Ri(A,"logo resolution kicked off (async)"),y(A,z)}catch(z){j({title:z instanceof Error?z.message:"Artifact generation failed.",variant:"error"})}finally{ho.end(A),n(null),o(null),i(null),a(null)}},[t,y,j,h,g,m,k])}}function cw({store:e,turn:t,model:n,editingSlideId:o,setEditingSlideId:i,setEditStatus:a,clearEditBarValue:l,designSystemsRef:u,activeDesignSystemIdRef:c,brandKitBindingRef:d,chartPngRef:p,deckChartSeries:h,runGraphyForChart:m,pushEditFlashes:g,setChatEditActivity:k,persistReceipt:y}){const{slidesRef:f,patch:I,requestSave:w,focusRectRef:x}=e,{slideEditHistoryRef:D}=t,[R,j]=s.useState(null),S=s.useRef(new Map);return{editSlide:s.useCallback(async(O,T,X,L)=>{var K;const W=T.trim();if(!W)return;const H=f.current.find(fe=>fe.id===O),ae=H?`Slide ${f.current.findIndex(fe=>fe.id===O)+1}`:"that slide",{stepLog:ge,reportActivity:J,setStep:ce}=Vi(k,X,()=>({slideLabel:ae,status:"running",steps:[]}));if(o!=null){J({status:"error",steps:[],note:"Another edit is still running â try again once it finishes."});return}if(!(H!=null&&H.baked)||H.status==="generating"){J({status:"error",steps:[],note:(H==null?void 0:H.status)==="generating"?"That slide is still generating.":"That slide has nothing to edit yet â generate it first."});return}i(O),X&&(j(O),(K=x.current)==null||K.call(x,{x:H.x,y:H.y,w:Ke,h:Je},.62)),a(X?null:"Thinkingâ¦"),J({slideLabel:ae,status:"running",steps:[]});let we=W;if(L!=null&&L.length){const fe=L.join("|"),ie=S.current.get(fe);ce("Read the reference style",ie?"complete":"active");try{let Y=ie??null;if(!Y){const re=(await Promise.all(L.map(le=>le.startsWith("data:")?le:vs(le,1568)))).filter(le=>!!le);if(re.length){const le=await Eo(re,aa(n)?n:"gemini-3.5-flash");le&&(Y=ra(ia(oa(le),100))??null)}Y&&S.current.set(fe,Y)}ce("Read the reference style","complete"),Y&&(we=[W,"","STYLE REFERENCE â the block below is the visual language to adopt: colours, background,","typography (family, weight, case, scale), spacing and border/corner treatment.","THE USER'S INSTRUCTION ABOVE DEFINES THE SCOPE:","- If they asked only to restyle/recolour, keep every element exactly where it is.","- If they asked to improve or rework the LAYOUT, you SHOULD re-arrange: fix imbalance,"," align to a clear grid, resize and reposition elements so the composition genuinely improves.","HARD RULES either way: keep the MEANING of every text (no rewriting content beyond what the","user asked); never delete content to make styling easier; never replace this slide with the","reference's own content or composition â the reference is a look, not a template.","Make REAL changes: never emit a patch that sets a value an element already has.","",Y].join(` 21`))}catch(Y){console.warn("birtvy: reference-style extraction failed for the chat edit",Y),ce("Read the reference style","complete")}}if(!(L!=null&&L.length)){const ie=Co(u.current,c.current)??(d.current?{profile:d.current.profile}:null);if(ie){const{promptBlock:Y}=Vm(ie);Y&&(we=[we,"","DECK STYLE â this deck has a saved design system; any restyling must stay INSIDE it","(its palette, fonts and treatment below). Improve within this language, never off into a
21new one.","",Y].join(` 22`))}}{const fe=D.current.get(O)??[];fe.length&&(we=[we,"","EARLIER EDITS TO THIS SLIDE (most recent last) â the user has SEEN these results already:",...fe.slice(-3).map((ie,Y)=>`${Y+1}. They asked: "${ie.asked}" â you did: ${ie.did||"nothing visible"}`),"If they are asking again, the previous result was NOT good enough: change something SUBSTANTIVE","this time â do not re-apply the same values or the same idea."].join(` 23`))}let ve=H.baked;const oe=[],pe=[];ce("Work out the changes","active");try{const{applied:fe,skippedImages:ie}=await Xb({slideId:O,baked:H.baked,instruction:we,model:n},{onApply:(Y,re,le)=>{const b=Gb(re,ve);oe.push(b),pe.push(re),ve=Y,ce("Work out the changes","complete"),ce(`${b} (${oe.length})`,"complete");const C={baked:Y,html:gn(Y,O)};if(re.type==="SetChart"){p.current.delete(O);const z=da(re.dataText,re.chartType,void 0,h());C.graphyConfig=z??void 0,z||m(O,`${re.dataText} 24 25Render it as a ${re.chartType} chart.`)}I(O,C),g(O,le.map(z=>({rect:z})))}});if(fe>0){ce("Check the result","active");const Y=f.current.find(le=>le.id===O);if(Y!=null&&Y.baked){const{baked:le,repaired:b}=Bb(Y.baked);b.length&&(I(O,{baked:le,html:gn(le,O)}),b.forEach(C=>ce(C,"complete")))}ce("Check the result","complete"),w(),l(O),a(null);const re=Fb(pe);{const le=D.current.get(O)??[];D.current.set(O,[...le,{asked:W,did:re}].slice(-6))}J({status:"done",steps:[...ge],summary:re}),X&&y(X,{slideLabel:ae,status:"done",steps:[...ge],summary:re})}else ie?(X||a("Adding photos isnât supported here yet"),J({status:"empty",note:"Adding photos isnât supported here yet."})):/\b(chart|graph|graphy|plot)\b/i.test(W)?(X||a("No chart came back â include the numbers, e.g. â2021: 5M. 2022: 9M. 2023: 14M.â"),J({status:"empty",note:"No chart came back â include the numbers, e.g. â2021: 5M. 2022: 9M.â"})):(X||a("No change was made â try rephrasing"),J({status:"empty",note:"Nothing changed â try naming the element or the change more specifically."}))}catch{X||a("Edit failed â try again"),J({status:"error",note:"The edit failed. Try again."})}finally{i(null),X&&j(null)}},[h,o,n,I,y,g,w,m]),chatEditSlideId:R}}function dw({store:e,turn:t,model:n,editingSlideId:o,slideGenCreativity:i,setSlideGenCreativity:a,setSlideGenTextDensity:l,setRedesigningIds:u,setChatEditActivity:c,persistReceipt:d,resolveChatEditTarget:p,editSlide:h,generateSlide:m,findClearRowY:g,slidesFedByDocs:k,openIdRef:y,setOpenId:f,chatMessagesRef:I,recentDocEditsRef:w,DOC_EDIT_MEMORY_MS:x}){const{setSlides:D,slidesRef:R,docsRef:j,notesRef:S,imagesRef:A,setWires:O,wiresRef:T,groupsRef:X,setSelectedIds:L,setSelectedDocIds:W,setSelectedNoteIds:H,setSelectedImageIds:ae,idRef:ge,requestSave:J,flushSave:ce,focusRectRef:we,patch:ve,placeInView:oe,showToast:pe}=e,{chatEditRefsRef:K,chatEditTargetRef:fe,chatEditStickySlidesRef:ie,chatEditStyleImagesRef:Y,chatEditAnchorsRef:re,turnPlacedImageIdsRef:le,turnSkippedLogosRef:b,slideEditHistoryRef:C,placeImagesInFlightRef:z,rebuildOwedRef:B}=t,M=s.useCallback((U,_,N="style",Z=[])=>{const Q={kind:"slide",id:U},G=[],se=ne=>T.current.some(de=>de.from.kind===ne.kind&&de.from.id===ne.id&&de.to.kind==="slide"&&de.to.id===U)||G.some(de=>de.from.kind===ne.kind&&de.from.id===ne.id);for(const ne of _.imageIds){const de={kind:"image",id:ne};!se(de)&&A.current.some(F=>F.id===ne)&&G.push({id:ge.current++,from:de,to:Q,mode:N,...N==="style"?{styleStrength:100}:{}})}for(const ne of Z){const de={kind:"image",id:ne};!se(de)&&A.current.some(F=>F.id===ne)&&G.push({id:ge.current++,from:de,to:Q,mode:"image"})}for(const ne of _.docIds){const de={kind:"doc",id:ne};!se(de)&&j.current.some(F=>F.id===ne)&&G.push({id:ge.current++,from:de,to:Q})}for(const ne of _.noteIds){const de={kind:"note",id:ne};!se(de)&&S.current.some(F=>F.id===ne)&&G.push({id:ge.current++,from:de,to:Q})}for(const ne of _.slideIds){if(ne===U)continue;const de={kind:"slide",id:ne};!se(de)&&R.current.some(F=>F.id===ne&&(F.baked||F.html))&&G.push({id:ge.current++,from:de,to:Q})}return G.length&&(T.current=[...T.current,...G],O(ne=>[...ne,...G.filter(de=>!ne.some(F=>F.id===de.id))]),J()),G.length},[J]),q=s.useCallback(async(U,_)=>{var mt,dt;const N=U.instruction.trim();z.current&&await z.current;const Z=K.current,Q=xc(U),G=od(N),se=qb(N),ne=Math.max(1,Math.min(4,Math.round(U.count??ad(N)??1))),de=Kb(N),F=ne===1&&!de?R.current.find($e=>
25(U.slideIds??[]).includes($e.id)&&$e.status!=="generating"):void 0;let $=F??R.current.find($e=>$e.id===fe.current)??R.current.find($e=>$e.id===y.current);if(ne===1&&$&&($.baked||$.html)&&!G&&!Z.slideIds.includes($.id)&&$.id!==(F==null?void 0:F.id)&&($=void 0),!$){const $e=R.current.filter(lt=>!lt.baked&&!lt.html&<.status!=="generating");$e.length===1?$=$e[0]:R.current.length===1&&(ne>1||G&&ne===1)&&($=R.current[0])}const P=ne>1||se;let me;P&&$&&($.baked||$.html)&&(me=$,$=void 0);let he="a slide";const{stepLog:Me,reportActivity:He,setStep:Ee}=Vi(c,_,()=>({slideLabel:he,kind:"generate",status:"running",steps:[]}));if(($==null?void 0:$.status)==="generating"||(me==null?void 0:me.status)==="generating"){He({status:"error",steps:[],note:"That slide is still generating â ask again when it finishes."});return}if(o!=null){He({status:"error",steps:[],note:"Another edit is still running â ask again once it finishes."});return}if(P){const $e=$?{x:$.x+Ke+In,y:$.y,n:ne-1}:me?{x:me.x+Ke+In,y:me.y,n:ne}:(()=>{const De=oe({width:Ke,height:Je});return{x:De.x,y:De.y,n:ne}})(),lt=g($e.x,$e.y,$e.n),it=Array.from({length:$e.n},(De,Ve)=>({id:ge.current++,x:$e.x+(Ke+In)*Ve,y:lt,status:"empty",prompt:N}));D(De=>[...De,...it.filter(Ve=>!De.some(Ct=>Ct.id===Ve.id))]),R.current=[...R.current,...it];const Dt=[...$?[$.id]:[],...it.map(De=>De.id)];$&&N&&ve($.id,{prompt:N}),he=$e.n===1?"a slide":`${$e.n} slides`;const en=me&&!Z.slideIds.includes(me.id)?{...Z,slideIds:[...Z.slideIds,me.id]}:Z;let Bt=0;for(const De of Dt)Bt+=M(De,en,Q,le.current);Bt&&Ee(`Connected the references to ${$e.n} frame${$e.n===1?"":"s"}`,"complete"),ce(),He({slideLabel:he,status:"running"});{const De=[...me?[me]:[],...Dt.map(Ve=>R.current.find(Ct=>Ct.id===Ve))].filter(Ve=>!!Ve).map(Ve=>({x:Ve.x,y:Ve.y,w:Ke,h:Je}));if(De.length){const Ve=Math.min(...De.map(ut=>ut.x)),Ct=Math.min(...De.map(ut=>ut.y)),Mt=Math.max(...De.map(ut=>ut.x+ut.w)),Te=Math.max(...De.map(ut=>ut.y+ut.h));(mt=we.current)==null||mt.call(we,{x:Ve,y:Ct,w:Mt-Ve,h:Te-Ct},.86)}}const sn=(U.creativity!=null?ui(U.creativity):void 0)??Math.max(i[Dt[0]]??Ur,.85),dn=U.textDensity&&["concise","balanced","detailed"].includes(U.textDensity)?U.textDensity:void 0,Jt=new Map(Dt.map(De=>[De,`Slide ${Math.max(0,R.current.findIndex(Ve=>Ve.id===De))+1}`])),Re=De=>Jt.get(De)??`Slide ${De}`,Ne=De=>[N||"Generate a slide.",...me!=null&&me.baked?["","The user LIKED this original slide (it stays on the canvas) â match its style language:",ws(me.baked)]:[],"",...$e.n===1?["This is a SECOND version sitting beside the original. Make it CLEARLY DISTINCT from it: a different composition, emphasis or background treatment."]:[`This is VARIANT ${De+1} of ${$e.n}, generated side by side with the others. Make it CLEARLY`,"DISTINCT from the other variants: a different composition, emphasis or background treatment."]].join(` 26`);Dt.forEach(De=>Ee(Re(De),"active"));const ct=(await Promise.all(Dt.map((De,Ve)=>m(De,n,{promptOverride:Ne(Ve),creativity:sn,textDensity:dn,previewThrottleMs:250}).then(Ct=>(Ee(Re(De),Ct.ok?"complete":"pending"),{tid:De,r:Ct}))))).filter(De=>De.r.ok).map(De=>De.tid);if(ct.forEach(De=>{const Ve=C.current.get(De)??[];C.current.set(De,[...Ve,{asked:N||"(variants)",did:`generated as one of ${ne} variants`}].slice(-6))}),ct.length&&(L(new Set(ct)),W(new Set),H(new Set),ae(new Set)),fe.current=null,ct.length>0){const De=[ct.length===ne?`I generated ${ne} versions side by side${me?", next to your original":""}.`:`${ct.length} of ${ne} versions finished; the rest stayed empty frames you can retry.`,"Each one takes a different angle on the same brief.","Pick the one you like and I can refine it or make more."].join(` 27`);He({slideLabel:`${ne} slides`,status:"done",steps:[...Me],summary:De}),d(_,{slideLabel:`${ne} slides`,kind:"generate",status:"done",steps:[...Me],summary:De})}else{const De="None of the generations finished. The empty frames are still there, ask again to retry.";He({slideLabel:`${ne} slides`,status:"error",steps:[...Me],note:De}),d(_,{slideLabel:`${ne} slides`,kind:"generate",status:"error",steps:[...Me],note:De})}return}let qe=!1;if(!$){const $e=oe({width:Ke,height:Je}),lt={id:ge.current++,x:$e.x,y:$e.y,status:"empty",prompt:""};D(it=>[...it,...it.some(Dt=>Dt.id===lt.id)?[]:[lt]]),R.current=[...R.current,lt],qe=!0,$=lt}
27const Ae=$.id,jt=qe?"a new slide":`Slide ${Math.max(0,R.current.findIndex($e=>$e.id===Ae))+1}`;he=jt,fe.current=Ae;const kt=!!($.baked||$.html),Ge=kt?{html:$.html,baked:$.baked,graphyConfig:$.graphyConfig,status:$.status}:null,Qe=kt&&(F==null?void 0:F.id)===Ae&&!G,ht=Qe?[...new Set([...T.current.filter($e=>$e.to.kind==="slide"&&$e.to.id===Ae&&$e.from.kind==="image"&&$e.mode!=="style").map($e=>$e.from.id),...Q==="image"?Z.imageIds:[],...le.current].map($e=>{var lt,it;return(it=(lt=A.current.find(Dt=>Dt.id===$e))==null?void 0:lt.label)==null?void 0:it.trim()}).filter($e=>!!$e))]:[],xt=Qe?Vb(N,ht):[],Xe=ht.filter($e=>!xt.includes($e));if(Qe&&b.current.length&&le.current.length===0&&Z.imageIds.length===0&&!xt.length){const $e=b.current,lt=`I left the slide as it is. I couldn't confirm ${$e.map(xn).join(" and ")}, and placing the wrong company's mark or drawing a fake one is worse than waiting. Send the official website${$e.length===1?"":"s"} and I'll fetch the real logo${$e.length===1?"":"s"}.`;He({slideLabel:jt,status:"empty",steps:[],note:lt}),d(_,{slideLabel:jt,kind:"generate",status:"empty",steps:[],note:lt});return}kt&&y.current===Ae&&f(null);let Ue=[];if(xt.length){const $e=new Set(A.current.filter(it=>it.label&&xt.includes(it.label)).map(it=>it.id)),lt=it=>!(it.to.kind==="slide"&&it.to.id===Ae&&it.from.kind==="image"&&$e.has(it.from.id));Ue=T.current.filter(it=>!lt(it)),T.current=T.current.filter(lt),O(it=>it.filter(lt))}let _e=N||$.prompt;if(kt&&$.baked){const $e=$.baked.elements.filter(it=>it.type==="text"&&!rn(it)).map(it=>(it.text??"").trim()).filter(Boolean),lt=C.current.get(Ae)??[];_e=Qe?[N||"Update this slide.","","This slide ALREADY EXISTS and the user approved how it looks. Rebuild it with the SAME design","and apply ONLY the change asked for above. Keep the layout, the background treatment, the type","scale, the palette and the order of the elements. Coming back with a different-looking slide is","a failure even if it is a better slide â the user did not ask for a redesign, and anything they","did not mention must survive untouched.","","CURRENT DESIGN â reproduce this composition:",ws($.baked),...Xe.length?["","IMAGES THAT MUST STILL BE ON THE SLIDE. Every one of these is available in the image","catalog and every one has to appear in the result. Put each next to the text that names","it, never next to a different name:",...Xe.map(it=>`- ${xn(it)}`)]:[],...xt.length?["",`REMOVE from the slide entirely: ${xt.map(xn).join(", ")}. The tile, the name and the image all go. Their files are no longer in the catalog.`]:[],"","CURRENT CONTENT â keep every fact and figure unless the change above replaces it:",...$e.map(it=>`- ${it}`)].join(` 28`):[N||"Design a fresh take on this slide.","","The user has SEEN the current version and asked for ANOTHER one. CURRENT DESIGN â do NOT reproduce","this composition (a result that looks like this list is a failure):",ws($.baked),...lt.length?["","EARLIER VERSIONS of this slide (most recent last) â all already seen:",...lt.slice(-3).map((it,Dt)=>`${Dt+1}. Asked: "${it.asked}"`)]:[],"","Design a STRUCTURALLY DIFFERENT composition: change the arrangement, hierarchy, scale contrast or","background treatment â not just colours. Keep the same content (every fact and figure below) and","stay inside the same style language:",...$e.map(it=>`- ${it}`)].join(` 29`)}He({slideLabel:jt,status:"running",steps:[]});const yt=M(Ae,Z,Q,le.current);if(yt&&Ee(yt===1?"Connected the reference to the slide":`Connected ${yt} references to the slide`,"complete"),Qe&&Ee(`Updating ${jt}, keeping its design`,"complete"),xt.length?Ee(`Removing ${xt.map(xn).join(" and ")} from the slide`,"complete"):qe&&(U.slideIds??[]).length&&Ee("Couldn't find the slide the agent meant, so this is a new one","complete"),b.current.length){const $e=b.current;Ee(`Left out ${$e.map(xn).join(" and ")} â couldn't confirm ${$e.length===1?"that logo":"those logos"}`,"complete")}const bt=U.creativity!=null?ui(U.creativity):void 0,Rt=bt??(kt&&!Qe?Math.max(i[Ae]??Ur,.85):void 0),Nt=U.textDensity&&["concise","balanced","detailed"].includes(U.textDensity)?U.textDensity:void 0;bt!=null?(a($e=>({...$e,[Ae]:bt})),Ee(`Set creativity to ${bt.toFixed(2)}`,"complete")):Rt!=null&&kt&&Ee(`Raised creativity to ${Rt.toFixed(2)} for a fresh take`,"complete"),Nt&&(l($e=>({...$e,[Ae]:Nt})),Ee(`Set text density to ${Nt}`,"complete")),!kt&&N&&ve(Ae,{prompt:N}),(qe||yt)&&ce();{const $e=R.current.find(lt=>lt.id===Ae);$e&&((dt=we.current)==null||dt.call(we,{x:$e.x,y:$e.y,w:Ke,h:Je},.62))}const vt={style:"Read the reference style",generate:"Generate the slide",bake:"Make every element editable",chart:"Build the chart"};let je=null;kt&&u($e=>new Set($e).add(Ae));let Oe;try{Oe=await m(Ae,n,{promptOverride:_e,creativity:Rt,textDensity:Nt,keepCurrent:kt,onPhase:$e=>{je&&Ee(vt[je],"complete"),Ee(vt[$e],"active"),je=$e}})}finally{kt&&u($e=>{const lt=new Set($e);return lt.delete(Ae),lt})}if(je&&Ee(vt[je],Oe.ok?"complete":"pending"),Oe.ok){const $e=Oe.baked?Yb(Oe.baked,{refSlides:Z.slideIds.filter(it=>it!==Ae).length,refImages:Z.imageIds.length,refDocs:Z.docIds.length,refNotes:Z.noteIds.length,creativity:Rt,textDensity:Nt,reroll:kt,updateInPlace:Qe}):Qe?"I updated the slide and kept its design.":kt?"I redesigned the slide with a new composition.":"I generated the slide.",lt=C.current.get(Ae)??[];C.current.set(Ae,[...lt,{asked:N||"(generate)",did:$e}].slice(-6)),L(new Set([Ae])),W(new Set),H(new Set),ae(new Set),He({status:"done",steps:[...Me],summary:$e}),d(_,{slideLabel:jt,kind:"generate",status:"done",steps:[...Me],summary:$e});return}Ge&&(ve(Ae,Ge),J()),Ue.length&&(T.current=[...T.current,...Ue],O($e=>[...$e,...Ue.filter(lt=>!$e.some(it=>it===lt))]),Ee(`Removing ${xt.map(xn).join(" and ")}
29 from the slide`,"pending"));const tt=Oe.aborted?"The generation was stopped":"The generation failed",ot=Ge?`${tt} â your current slide is untouched.`:`${tt} â the empty frame is still there, ask again to retry.`;He({status:"error",steps:[...Me],note:ot}),d(_,{slideLabel:jt,kind:"generate",status:"error",steps:[...Me],note:ot})},[M,o,ce,m,n,ve,d,oe,J,i]),ue=s.useCallback(U=>{const _=de=>de.filter(F=>R.current.some($=>$.id===F));if(U!=null&&U.length){const de=_(U);if(de.length)return de}const N=_(K.current.slideIds.length?K.current.slideIds:ie.current);if(N.length)return N;const Z=w.current;if(Z.ids.size&&Date.now()-Z.at<=x){const de=_(k([...Z.ids]));if(de.length)return de}const Q=new Set(T.current.filter(de=>de.to.kind==="slide"&&de.from.kind==="doc").map(de=>de.to.id));if(!Q.size)return[];const G=de=>{const F=X.current.find($=>$.id===de);return(F==null?void 0:F.parentId)??(F==null?void 0:F.id)??null},se=R.current.filter(de=>Q.has(de.id)),ne=Math.max(...se.map(de=>G(de.groupId)??-1));return ne<0?se.map(de=>de.id):se.filter(de=>G(de.groupId)===ne).map(de=>de.id)},[k]),ye=s.useCallback(async(U,_)=>{var kt;const N=U.instruction.trim();z.current&&await z.current;const Z=K.current,{stepLog:Q,reportActivity:G,setStep:se}=Vi(c,_,()=>({slideLabel:"these slides",kind:"generate",status:"running",steps:[]})),ne=ue(U.slideIds),de=(ne.length?ne:k(Z.docIds??[])).filter(Ge=>{const Qe=R.current.find(ht=>ht.id===Ge);return!!Qe&&Qe.status!=="generating"&&!!(Qe.baked||Qe.html)});if(de.length===0){q(U,_);return}if(o!=null){G({status:"error",steps:[],note:"Another edit is still running â ask again once it finishes."});return}y.current!=null&&de.includes(y.current)&&f(null),B.current=!1;const F=new Map(de.map(Ge=>[Ge,`Slide ${Math.max(0,R.current.findIndex(Qe=>Qe.id===Ge))+1}`])),$=Ge=>F.get(Ge)??`Slide ${Ge}`,P=`${de.length} slides`;G({slideLabel:P,kind:"generate",status:"running"});for(const Ge of de)M(Ge,Z,xc(U),le.current);ce();const me=U.creativity!=null?ui(U.creativity):void 0,he=U.textDensity&&["concise","balanced","detailed"].includes(U.textDensity)?U.textDensity:void 0,Me=[N||"Rebuild this slide.","","Rebuild this slide from its own source document, keeping its subject the same.","Apply the direction above to every slide in this set so they read as one deck."].join(` 30`);de.forEach(Ge=>se($(Ge),"pending"));const He=[];for(const Ge of de){const Qe=R.current.find(xt=>xt.id===Ge);Qe&&((kt=we.current)==null||kt.call(we,{x:Qe.x,y:Qe.y,w:Ke,h:Je},.9)),se($(Ge),"active");const ht=await m(Ge,n,{promptOverride:Me,creativity:me,textDensity:he,keepCurrent:!0});se($(Ge),ht.ok?"complete":"pending"),He.push({tid:Ge,ok:ht.ok})}const Ee=He.filter(Ge=>Ge.ok).map(Ge=>Ge.tid);Ee.forEach(Ge=>{const Qe=C.current.get(Ge)??[];C.current.set(Ge,[...Qe,{asked:N||"(rebuild)",did:"rebuilt from its source document"}].slice(-6))});const qe=de.length-Ee.length,Ae=[Ee.length===de.length?`I rebuilt all ${de.length} slides, each from its own document.`:`${Ee.length} of ${de.length} slides rebuilt.`,...qe>0?[`${qe} kept the design ${qe===1?"it":"they"} already had.`]:[],"They replaced what was there, so undo brings the old ones back."].join(` 31`),jt=Ee.length>0?"done":"error";G({slideLabel:P,status:jt,steps:[...Q],summary:Ae}),d(_,{slideLabel:P,kind:"generate",status:jt,steps:[...Q],summary:Ae}),J()},[M,o,ce,m,n,d,ue,J,k,q]),ee=s.useCallback((U,_)=>{if(_){const ne=(I.current??[]).find(F=>F.id===_),de=((ne==null?void 0:ne.content)??"").trim().slice(0,120);de&&(re.current[_]=de)}const N=ue(U.slideIds);try{const ne={at:new Date().toISOString(),instruction:(U.instruction||"").slice(0,160),scope:U.scope??null,operation:U.operation??null,imageIntent:U.imageIntent??null,namedSlideIds:U.slideIds??null,msgSlides:K.current.slideIds.length,stickySlides:ie.current.length,recentDocCards:w.current.ids.size,resolved:N.length,rebuildAsk:Ci(U.instruction),continuation:id(U.instruction),owed:B.current},de=JSON.parse(window.localStorage.getItem("birtvy:routing")??"[]");window.localStorage.setItem("birtvy:routing",JSON.stringify([...Array.isArray(de)?de:[],ne].slice(-20)))}catch{}const Z=B.current&&N.length>1&&id(U.instruction);if(N.length>1&&Ci(U.instruction)&&(B.current=!0),U.scope==="wired"||Z||N.length>1&&Ci(U.instruction)){ye(U,_);return}if(U.operation==="generate"||od(U.instruction)||ad(U.instruction)!=null){q(U,_);return}const Q=R.current.find(ne=>ne.id===fe.current)??R.current.find(ne=>ne.id===y.current);if(Q&&!Q.baked&&!Q.html&&Q.status!=="generating"){q(U,_);return}const se=(U.slideIds??[]).find(ne=>R.current.some(de=>de.id===ne&&de.baked&&de.status!=="generating"))??p();if(se==null){if(/\b(generate|create|make|build|design)\b[\s\S]{0,80}\bslides?\b/i.test(U.instruction)){q(U,_);return}const ne=N.length>1?`I can only edit one slide at a time. You have ${N.length}
31 selected â pick one, or ask me to recreate them and Iâll rebuild each from its document.`:"I couldnât tell which slide you meant â select one (or open it) and ask again.";pe({title:ne,variant:"error"}),_&&c(de=>({...de,[_]:{slideLabel:"a slide",status:"error",steps:[],note:ne}}));return}fe.current=se,h(se,U.instruction,_,Y.current)},[h,q,ue,ye,p,pe]);return{addChatReferenceWires:M,generateSlideFromChat:q,rebuildSetCandidates:ue,regenerateSetFromChat:ye,handleChatCanvasEdit:ee}}function uw({slidesRef:e,groups:t,hiddenMemberKeys:n,images:o,zoom:i,zoomPct:a,lod:l,glMode:u,glActiveRef:c,glQuadIdsRef:d,farNext:p,renderer:h,liveDocIdsRef:m}){s.useEffect(()=>{typeof window>"u"||(window.__birtvyState=()=>({slides:e.current.length,docSlides:e.current.filter(g=>g.docHtml).length,docBakedCount:e.current.filter(g=>g.docBaked).length,groups:t.length,collapsedHiddenMembers:n.size,images:o.length,zoomLive:i.current,zoomPct:a,lod:l,glMode:u,glActive:c.current,quadCount:d.current.length,farNext:p,renderer:h,liveDocs:[...m.current],docFontCss:(()=>{const g=Hr();return g===null?"NULL (inlining in flight)":`ready (${g.length} chars)`})()}))})}function fw(e){const{setSlides:t,slidesRef:n,setDocs:o,docsRef:i,setNotes:a,notesRef:l,setImages:u,imagesRef:c,setWebs:d,websRef:p,setWires:h,wiresRef:m,setGroups:g,groupsRef:k,setSelectedIds:y,selectedIdsRef:f,setSelectedDocIds:I,selectedDocIdsRef:w,setSelectedNoteIds:x,selectedNoteIdsRef:D,setSelectedImageIds:R,selectedImageIdsRef:j,setSelectedWebIds:S,selectedWebIdsRef:A,clearSelection:O,idRef:T,requestSave:X,flushSave:L,pan:W,zoom:H,viewportRef:ae,clientToWorld:ge,fitAllRef:J,focusRectRef:ce,patch:we,placeInView:ve,bringToFront:oe,purgeDeletedDocsRef:pe,showToast:K}=e;return s.useMemo(()=>({setSlides:t,slidesRef:n,setDocs:o,docsRef:i,setNotes:a,notesRef:l,setImages:u,imagesRef:c,setWebs:d,websRef:p,setWires:h,wiresRef:m,setGroups:g,groupsRef:k,setSelectedIds:y,selectedIdsRef:f,setSelectedDocIds:I,selectedDocIdsRef:w,setSelectedNoteIds:x,selectedNoteIdsRef:D,setSelectedImageIds:R,selectedImageIdsRef:j,setSelectedWebIds:S,selectedWebIdsRef:A,clearSelection:O,idRef:T,requestSave:X,flushSave:L,pan:W,zoom:H,viewportRef:ae,clientToWorld:ge,fitAllRef:J,focusRectRef:ce,patch:we,placeInView:ve,bringToFront:oe,purgeDeletedDocsRef:pe,showToast:K}),[t,n,o,i,a,l,u,c,d,p,h,m,g,k,y,f,I,w,x,D,R,j,S,A,O,T,X,L,W,H,ae,ge,J,ce,we,ve,oe,pe,K])}function hw({store:e,conversationId:t,deletedDocIdsRef:n,setHoveredDocId:o,setOpenDocId:i}){const{setDocs:a,docsRef:l,idRef:u,setSelectedIds:c,setSelectedDocIds:d,requestSave:p,placeInView:h,bringToFront:m,purgeDeletedDocsRef:g,showToast:k}=e,y=s.useCallback(async(j="",S,A,O)=>{let T=S;if(!T&&t){const ae=await $d(t,{content:j});ae?T=ae.id:k({title:"Couldnât add this to the Library. The card is on the canvas but not linked yet.",variant:"error"})}const{x:X,y:L}=h({width:En,height:Cn},A),H={id:u.current++,x:X,y:L,width:En,height:Cn,content:j,title:(O==null?void 0:O.trim())||Bi(j),documentId:T};a(ae=>[...ae,H]),c(new Set),d(new Set),p()},[t,h,p,k]),f=s.useRef(new Set),I=s.useCallback((j,S)=>{a(A=>A.map(O=>O.id===j?{...O,content:S,title:Bi(S)}:O)),f.current.add(j),p()},[p]),w=s.useCallback(j=>{const S=l.current.find(T=>T.id===j);if(!S)return;const A=u.current++,O={...S,id:A,x:S.x+64,y:S.y+64,documentId:void 0};a(T=>[...T,O]),d(new Set([A])),m([`doc:${A}`]),p()},[p,m]),x=s.useCallback(j=>{const S=[...new Set(j.map(A=>A.documentId).filter(A=>!!A))];if(S.length&&(S.forEach(A=>n.current.add(A)),p(),!!t))for(const A of S)Sm(t,A).then(O=>{O?console.info(`birtvy: deleted Library document ${A}`):console.warn(`birtvy: Library delete failed for ${A} (tombstoned, so it still stays gone)`)})},[t,p]);g.current=x;const D=s.useCallback(j=>{const S=l.current.find(T=>T.id===j);if(!S)return;const A=S.documentId?l.current.filter(T=>T.documentId===S.documentId):[S],O=new Set(A.map(T=>T.id));a(T=>T.filter(X=>!O.has(X.id))),d(T=>{if(![...O].some(L=>T.has(L)))return T;const X=new Set(T);return O.forEach(L=>X.delete(L)),X}),o(T=>T!=null&&O.has(T)?null:T),i(T=>T!=null&&O.has(T)?null:T),p(),x(A)},[p,x]),R=s.useCallback(j=>{n.current.add(j),a(S=>S.filter(A=>A.documentId!==j)),p()},[p]);return{placeDoc:y,docDirtyRef:f,updateDoc:I,duplicateDoc:w,purgeDeletedDocs:x,deleteDoc:D,removeDocsByDocumentId:R}}const Or=428,Au=[{key:"default",label:"White",fill:"#ffffff"},{key:"yellow",label:"Yellow",fill:"var(--color-basic-yellow-subtle)"},{key:"orange",label:"Orange",fill:"var(--color-basic-orange-subtle)"},{key:"red",label:"Red",fill:"var(--color-basic-red-subtle)"},{key:"green",label:"Green",fill:"var(--color-basic-green-subtle)"},{key:"blue",label:"Blue",fill:"var(--color-basic-blue-subtle)"},{key:"gray",label:"Gray",fill:"var(--color-basic-gray-subtle)"}];function $u(e){var t;return((t=Au.find(n=>n.key===(e??"default")))==null?void 0:t.fill)??"#ffffff"}function pw({store:e,setHoveredNoteId:t}){const{setNotes:n,notesRef:o,idRef:i,placeInView:a,requestSave:l,bringToFront:u,setSelectedIds:c,setSelectedDocIds:d,setSelectedNoteIds:p}=e,h=s.useCallback((I,w="")=>{const{x,y:D}=a({width:Or,height:Or},I),j={id:i.current++,x,y:D,width:Or,height:Or,content:w,color:"default"};n(S=>[...S,j]),c(new Set),d(new Set),p(new Set),l()},[a,l]),m=s.useCallback((I,w)=>{n(x=>x.map(D=>D.id===I?{...D,content:w}:D)),l()},[l]),g=s.useCallback((I,w)=>{n(x=>x.map(D=>D.id===I?{...D,color:w}:D)),l()},[l]),k=s.useCallback((I,w)=>{n(x=>x.map(D=>D.id===I&&Math.abs(D.height-w)>1?{...D,height:w}:D)),l()},[l]),y=s.useCallback(I=>{const w=o.current.find(R=>R.id===I);if(!w)return;const x=i.current++,D={...w,id:x,x:w.x+64,y:w.y+64};n(R=>[...R,D]),p(new Set([x])),u([`note:${x}`]),l()},[l,u]),f=s.useCallback(I=>{n(w=>w.filter(x=>x.id!==I)),p(w=>Cr(w,I)),t(w=>w===I?null:w),l()},[l]);return{placeNote:h,updateNoteContent:m,updateNoteColor:g,updateNoteHeight:k,duplicateNote:y,deleteNote:f}}function mw({store:e,setHoveredImageId:t}){const{imagesRef:n,setImages:o,setWires:i,setSelectedIds:a,setSelectedDocIds:l,setSelectedNoteIds:u,setSelectedImageIds:c,idRef:
31d,requestSave:p,placeInView:h,bringToFront:m}=e,g=s.useCallback((w,x,D,R,j)=>{const S=Wr(x,D);let A,O;if(R)A=R.x-S.width/2,O=R.y-S.height/2;else{const L=h({width:S.width,height:S.height});A=L.x,O=L.y}const T=d.current++,X={id:T,x:Math.round(A),y:Math.round(O),width:S.width,height:S.height,src:w,label:j};return n.current=[...n.current,X],o(L=>[...L,X]),a(new Set),l(new Set),u(new Set),c(new Set),p(),T},[e]),k=s.useCallback(async(w,x)=>{const D=await ko(w);g(w,D.width,D.height,x)},[g]),y=s.useCallback(w=>{const x=n.current.find(j=>j.id===w);if(!x)return;const D=d.current++,R={...x,id:D,x:x.x+64,y:x.y+64};o(j=>[...j,R]),c(new Set([D])),m([`image:${D}`]),p()},[e]),f=s.useCallback(w=>{o(x=>x.filter(D=>D.id!==w)),c(x=>Cr(x,w)),t(x=>x===w?null:x),p()},[e,t]),I=s.useCallback((w,x)=>{i(D=>D.map(R=>R.from.kind==="image"&&R.from.id===w&&R.mode==="style"?{...R,styleStrength:x}:R)),p()},[e]);return{placeImage:g,placeImageFromSrc:k,duplicateImage:y,deleteImage:f,setImageStyleStrength:I}}function gw({store:e,placeImageFromSrc:t,placeDoc:n,placeNote:o,placeWebFromUrl:i}){const{showToast:a}=e;return{placeExternalItems:s.useCallback(async(u,c)=>{let d=0,p=0;for(const h of u){const m=c?{x:c.x+d*40,y:c.y+d*40}:void 0;try{if(h.kind==="image-file"){if(h.file.size>ux){p++;continue}await t(await Td(h.file),m)}else if(h.kind==="image-url")await t(h.url,m);else if(h.kind==="web-url"){if(i(h.url,m)==null){p++;continue}}else if(h.kind==="text-file"){if(h.file.size>dx){p++;continue}const g=await h.file.text();if(Gr(g)){p++;continue}n(g,void 0,m)}else{const g=h.html?await vx(h.html).catch(()=>null):null,k=wx(h.plain,g);if(!k){p++;continue}k.kind==="note"?o(m,k.content):n(k.content,void 0,m)}d++}catch(g){console.warn("birtvy: external item failed",g),p++}}return d===0&&p>0?a({title:"Couldn't add that to the canvas.",variant:"error"}):p>0&&a({title:`Added ${d}, skipped ${p}.`}),d},[t,n,o,i,a])}}function xw({store:e,groupViewsRef:t,hiddenMemberKeysRef:n,setOpenId:o,setOpenDocId:i,setViewerWebId:a}){const{slidesRef:l,docsRef:u,notesRef:c,imagesRef:d,websRef:p,groupsRef:h,selectedIdsRef:m,selectedDocIdsRef:g,selectedNoteIdsRef:k,selectedImageIdsRef:y,selectedWebIdsRef:f,setSlides:I,setDocs:w,setNotes:x,setImages:D,setWebs:R,setGroups:j,setSelectedIds:S,setSelectedDocIds:A,setSelectedNoteIds:O,setSelectedImageIds:T,setSelectedWebIds:X,clearSelection:L,idRef:W,bringToFront:H,requestSave:ae,purgeDeletedDocsRef:ge}=e,J=s.useRef(null),ce=s.useCallback(()=>({slides:l.current.filter(le=>m.current.has(le.id)),docs:u.current.filter(le=>g.current.has(le.id)),notes:c.current.filter(le=>k.current.has(le.id)),images:d.current.filter(le=>y.current.has(le.id)),webs:p.current.filter(le=>f.current.has(le.id))}),[]),we=s.useCallback((le,b,C)=>{const z=new Set([...le.slides.map(P=>Ye("slide",P.id)),...le.docs.map(P=>Ye("doc",P.id)),...le.notes.map(P=>Ye("note",P.id)),...le.images.map(P=>Ye("image",P.id))]),B=P=>[...l.current.filter(me=>me.groupId===P).map(me=>Ye("slide",me.id)),...u.current.filter(me=>me.groupId===P).map(me=>Ye("doc",me.id)),...c.current.filter(me=>me.groupId===P).map(me=>Ye("note",me.id)),...d.current.filter(me=>me.groupId===P).map(me=>Ye("image",me.id))],M=new Map,q=[];for(const P of h.current){const me=[...B(P.id),...h.current.filter(he=>he.parentId===P.id).flatMap(he=>B(he.id))];me.length>=2&&me.every(he=>z.has(he))&&(M.set(P.id,W.current++),q.push(P))}const ue=q.map(P=>({...P,id:M.get(P.id),parentId:P.parentId!=null?M.get(P.parentId)??P.parentId:P.parentId,...P.x!=null&&P.y!=null?{x:Math.round(P.x+b),y:Math.round(P.y+C)}:{}})),ye=P=>P!=null?M.get(P)??P:null,ee=le.slides.map(P=>{const me=W.current++,he=P.baked?Bd(P.baked,me):void 0;return{...P,id:me,x:Math.round(P.x+b),y:Math.round(P.y+C),baked:he,html:he?gn(he,me):P.html,groupId:ye(P.groupId)}}),U=le.docs.map(P=>({...P,id:W.current++,x:Math.round(P.x+b),y:Math.round(P.y+C),documentId:void 0,groupId:ye(P.groupId)})),_=le.notes.map(P=>({...P,id:W.current++,x:Math.round(P.x+b),y:Math.round(P.y+C),groupId:ye(P.groupId)})),N=le.images.map(P=>({...P,id:W.current++,x:Math.round(P.x+b),y:Math.round(P.y+C),groupId:ye(P.groupId)})),Z=le.webs.map(P=>({...P,id:W.current++,x:Math.round(P.x+b),y:Math.round(P.y+C)})),Q=wu(t.current,[...ee.map(P=>({kind:"slide",id:P.id,x:P.x,y:P.y,width:Ke,height:Je,groupId:P.groupId})),...U.map(P=>({kind:"doc",id:P.id,x:P.x,y:P.y,width:P.width,height:P.height,groupId:P.groupId})),..._.map(P=>({kind:"note",id:P.id,x:P.x,y:P.y,width:P.width,height:P.height,groupId:P.groupId})),...N.map(P=>({kind:"image",id:P.id,x:P.x,y:P.y,width:P.width,height:P.height,groupId:P.groupId}))]),G=(P,me)=>Q.size?P.map(he=>
31{const Me=Q.get(Ye(me,he.id));return Me!==void 0?{...he,groupId:Me}:he}):P,se=G(ee,"slide"),ne=G(U,"doc"),de=G(_,"note"),F=G(N,"image");ue.length&&j(P=>[...P,...ue]),se.length&&I(P=>[...P,...se]),ne.length&&w(P=>[...P,...ne]),de.length&&x(P=>[...P,...de]),F.length&&D(P=>[...P,...F]),Z.length&&R(P=>[...P,...Z]),S(new Set(ee.map(P=>P.id))),A(new Set(U.map(P=>P.id))),O(new Set(_.map(P=>P.id))),T(new Set(N.map(P=>P.id))),X(new Set(Z.map(P=>P.id))),H([...ee.map(P=>`slide:${P.id}`),...U.map(P=>`doc:${P.id}`),..._.map(P=>`note:${P.id}`),...N.map(P=>`image:${P.id}`),...Z.map(P=>`web:${P.id}`)]),ae();const $=new Set;for(const P of[...se,...ne,...de,...F])P.groupId!=null&&!ue.some(me=>me.id===P.groupId)&&$.add(P.groupId);return{slide:ee.map(P=>P.id),doc:U.map(P=>P.id),note:_.map(P=>P.id),image:N.map(P=>P.id),web:Z.map(P=>P.id),groups:M,adopted:$}},[ae,H]),ve=s.useCallback(le=>({slides:l.current.filter(b=>le.slide.has(b.id)),docs:u.current.filter(b=>le.doc.has(b.id)),notes:c.current.filter(b=>le.note.has(b.id)),images:d.current.filter(b=>le.image.has(b.id)),webs:p.current.filter(b=>le.web.has(b.id))}),[]),oe=s.useCallback(()=>{var b,C;const le=ce();return le.slides.length||le.docs.length||le.notes.length||le.images.length||le.webs.length?(J.current={slides:le.slides.map(z=>({...z})),docs:le.docs.map(z=>({...z})),notes:le.notes.map(z=>({...z})),images:le.images.map(z=>({...z})),webs:le.webs.map(z=>({...z}))},(C=(b=navigator.clipboard)==null?void 0:b.writeText)==null||C.call(b,ou).catch(()=>{}),!0):!1},[ce]),pe=s.useCallback(le=>{le.size&&setTimeout(()=>{const b=new Map;for(const C of le){const z=t.current.find(M=>M.id===C);if(!z)continue;const B=cn([...z.memberRects,...t.current.filter(M=>M.parentId===C).map(M=>({x:M.frame.x,y:M.frame.y-Wt,width:M.frame.width,height:M.frame.height+Wt}))]);B&&b.set(C,B)}b.size&&(j(C=>C.map(z=>{const B=b.get(z.id);return B?an(z,B):z})),ae())})},[ae]),K=s.useCallback(le=>{const b=J.current;if(!b)return;const C=[...b.slides.map(M=>({x:M.x,y:M.y,w:Ke,h:Je})),...b.docs.map(M=>({x:M.x,y:M.y,w:M.width,h:M.height})),...b.notes.map(M=>({x:M.x,y:M.y,w:M.width,h:M.height})),...b.images.map(M=>({x:M.x,y:M.y,w:M.width,h:M.height})),...b.webs.map(M=>({x:M.x,y:M.y,w:M.width,h:M.height}))];if(!C.length)return;let z=40,B=40;if(le){const M=Math.min(...C.map(ee=>ee.x)),q=Math.min(...C.map(ee=>ee.y)),ue=Math.max(...C.map(ee=>ee.x+ee.w)),ye=Math.max(...C.map(ee=>ee.y+ee.h));z=le.x-(M+(ue-M)/2),B=le.y-(q+(ye-q)/2)}pe(we(b,z,B).adopted)},[we,pe]),fe=s.useCallback(()=>{const le=ce();(le.slides.length||le.docs.length||le.notes.length||le.images.length||le.webs.length)&&pe(we(le,40,40).adopted)},[ce,we,pe]),ie=s.useCallback(()=>{const le=m.current,b=g.current,C=k.current,z=y.current,B=f.current;(le.size||b.size||C.size||z.size||B.size)&&(le.size&&I(M=>M.filter(q=>!le.has(q.id))),b.size&&ge.current(u.current.filter(M=>b.has(M.id))),b.size&&w(M=>M.filter(q=>!b.has(q.id))),C.size&&x(M=>M.filter(q=>!C.has(q.id))),z.size&&D(M=>M.filter(q=>!z.has(q.id))),B.size&&R(M=>M.filter(q=>!B.has(q.id))),o(M=>M!=null&&le.has(M)?null:M),i(M=>M!=null&&b.has(M)?null:M),a(M=>M!=null&&B.has(M)?null:M),L(),ae())},[L,ae]),Y=s.useCallback(()=>{const le=n.current;S(new Set(l.current.map(b=>b.id))),A(new Set(u.current.filter(b=>!le.has(Ye("doc",b.id))).map(b=>b.id))),O(new Set(c.current.filter(b=>!le.has(Ye("note",b.id))).map(b=>b.id))),T(new Set(d.current.filter(b=>!le.has(Ye("image",b.id))).map(b=>b.id))),X(new Set(p.current.map(b=>b.id)))},[]),re=s.useCallback((le,b)=>{(le==="slide"?m.current.has(b):le==="doc"?g.current.has(b):le==="note"?k.current.has(b):le==="image"?y.current.has(b):f.current.has(b))||(S(le==="slide"?new Set([b]):new Set),A(le==="doc"?new Set([b]):new Set),O(le==="note"?new Set([b]):new Set),T(le==="image"?new Set([b]):new Set),X(le==="web"?new Set([b]):new Set))},[]);return{clipboardRef:J,placeClones:we,itemsForIds:ve,copySelection:oe,pasteClipboard:K,duplicateSelection:fe,deleteSelection:ie,selectAll:Y,selectForContext:re}}function yw(){const e=s.useRef(0),[t,n]=s.useState({}),o=s.useCallback(i=>{i.length&&n(a=>{const l={...a};for(const u of i)l[u]=++e.current;return l})},[]);return{zOrder:t,bringToFront:o}}function bw({store:e,conversationId:t,placeImage:n,flashGroup:o,placedLogoByUrlRef:i,turnPlacedImageIdsRef:a,turnSkippedLogosRef:l}){const{setImages:u,imagesRef:c,groupsRef:d,setGroups:p,idRef:h,placeInView:m,requestSave:g,showToast:k}=e;return{handlePlaceCanvasImages:s.useCallback(async f=>{var L;const I=(f.items??[]).map(W=>
31typeof W=="string"?W.trim():"").filter(Boolean).slice(0,Ax);if(!I.length)return;const w=f.kind!=="photo";if(!t){k({title:"Open a saved deck to add images.",variant:"error"});return}const x=await Promise.all(I.map(async W=>{var H,ae,ge;try{const J=await fetch("/deckgen-image-search-api",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(w?{logoDomain:W}:{query:W})});if(!J.ok)return{item:W,skip:"missing"};const ce=await J.json(),we=(ae=(H=ce==null?void 0:ce.results)==null?void 0:H[0])==null?void 0:ae.url;if(!we){const Y=ce==null?void 0:ce.verdict;return{item:W,skip:Y==="ambiguous"||Y==="unsupported"?"unsure":"missing"}}const ve=i.current.get(we),oe=(ve!=null?c.current.find(Y=>Y.id===ve):void 0)??(w?c.current.find(Y=>Y.label&&xn(Y.label).toLowerCase()===xn(W).toLowerCase()):void 0);if(oe)return oe.label||(c.current=c.current.map(Y=>Y.id===oe.id?{...Y,label:W}:Y),u(Y=>Y.map(re=>re.id===oe.id?{...re,label:W}:re))),{item:W,reuseId:oe.id};const pe=await fetch(`/conversation-images-api/${encodeURIComponent(t)}/from-url`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:we})}),fe=(pe.ok?(ge=await pe.json())==null?void 0:ge.url:void 0)||we,ie=await ko(fe);return{item:W,found:we,src:fe,natural:ie,box:Wr(ie.width,ie.height)}}catch{return{item:W,skip:"missing"}}})),D=x.filter(W=>"src"in W),R=x.flatMap(W=>"reuseId"in W?[W.reuseId]:[]),j=x.flatMap(W=>"skip"in W&&W.skip==="unsure"?[W.item]:[]),S=x.flatMap(W=>"skip"in W&&W.skip==="missing"?[W.item]:[]);if(l.current=[...new Set([...l.current,...j,...S])],!D.length&&!R.length){k({title:j.length?`Couldn't confirm which company ${j.map(xn).join(" and ")} ${j.length===1?"is":"are"} â send the website and I'll fetch the real mark.`:`Couldn't find ${w?"those logos":"those images"}.`,variant:"error"});return}const A=48,O=[],T=[];if(D.length){const W=D.reduce((J,ce)=>J+ce.box.width,0)+A*(D.length-1),H=Math.max(...D.map(J=>J.box.height)),ae=m({width:W,height:H});let ge=ae.x;for(const J of D){const ce={x:ge+J.box.width/2,y:ae.y+H/2},we=n(J.src,J.natural.width,J.natural.height,ce,J.item);O.push(we),i.current.set(J.found,we),T.push({x:Math.round(ce.x-J.box.width/2),y:Math.round(ce.y-J.box.height/2),width:J.box.width,height:J.box.height}),ge+=J.box.width+A}}a.current=[...a.current,...O,...R];const X=(L=f.groupTitle)==null?void 0:L.trim();if(X&&O.length){const W=d.current.find(ve=>ve.title===X),H=(W==null?void 0:W.id)??h.current++,ae=new Set(O);u(ve=>ve.map(oe=>ae.has(oe.id)?{...oe,groupId:H}:oe));const ge=W?c.current.filter(ve=>ve.groupId===H).map(ve=>({x:ve.x,y:ve.y,width:ve.width,height:ve.height})):[],J=cn([...ge,...T]),ce=W?{...W}:{id:H,title:X},we=J?an(ce,J):ce;p(ve=>W?ve.map(oe=>oe.id===H?we:oe):[...ve,we]),o(H)}g()},[t,n,m,o,g,k])}}function ww({store:e,groupViewsRef:t,selectedGroupIdsRef:n,flashGroup:o,itemsForIds:i,placeClones:a}){const{setSlides:l,slidesRef:u,setDocs:c,docsRef:d,setNotes:p,notesRef:h,setImages:m,imagesRef:g,setGroups:k,groupsRef:y,selectedIdsRef:f,selectedDocIdsRef:I,selectedNoteIdsRef:w,selectedImageIdsRef:x,clearSelection:D,idRef:R,requestSave:j,purgeDeletedDocsRef:S,showToast:A}=e,O=s.useCallback((oe,pe,K)=>{var _,N;const fe=t.current.filter(Z=>Z.parentId===oe),ie=u.current.filter(Z=>Z.groupId===oe),Y=Iu(fe,ie);if(!Y.length)return;let re=Su(Y);if(K!=null&&K.order){const Z=new Map(K.order.map((Q,G)=>[Q,G]));re=[...Y].sort((Q,G)=>(Z.get(Q.key)??Number.MAX_SAFE_INTEGER)-(Z.get(G.key)??Number.MAX_SAFE_INTEGER))}const le=((_=K==null?void 0:K.origin)==null?void 0:_.x)??Math.min(...Y.map(Z=>Z.x)),b=((N=K==null?void 0:K.origin)==null?void 0:N.y)??Math.min(...Y.map(Z=>Z.y-(Z.labelBand?Wt:0))),C=ku(re,pe,le,b),z=new Map,B=new Map;for(const Z of Y){const Q=C.get(Z.key);if(!Q)continue;const G=Q.x-Z.x,se=Q.y-Z.y;Z.kind==="slide"?z.set(Z.id,{dx:G,dy:se}):(G||se)&&B.set(Z.id,{dx:G,dy:se})}const M=Z=>Z!=null?B.get(Z):void 0;l(Z=>Z.map(Q=>{const G=z.get(Q.id);if(G)return{...Q,x:Q.x+G.dx,y:Q.y+G.dy};const se=M(Q.groupId);return se?{...Q,x:Q.x+se.dx,y:Q.y+se.dy}:Q})),c(Z=>Z.map(Q=>{const G=M(Q.groupId);return G?{...Q,x:Q.x+G.dx,y:Q.y+G.dy}:Q})),p(Z=>Z.map(Q=>{const G=M(Q.groupId);return G?{...Q,x:Q.x+G.dx,y:Q.y+G.dy}:Q})),m(Z=>Z.map(Q=>{const G=M(Q.groupId);return G?{...Q,x:Q.x+G.dx,y:Q.y+G.dy}:Q}));const q=new Map;for(const Z of fe){const Q=B.get(Z.id);
31q.set(Z.id,Q?{x:Z.frame.x+Q.dx,y:Z.frame.y+Q.dy,width:Z.frame.width,height:Z.frame.height}:Z.frame)}const ue=t.current.find(Z=>Z.id===oe),ye=((ue==null?void 0:ue.memberRects)??[]).filter(Z=>Z.kind!=="slide"),ee=ie.map(Z=>{const Q=z.get(Z.id);return{x:Z.x+((Q==null?void 0:Q.dx)??0),y:Z.y+((Q==null?void 0:Q.dy)??0),width:Ke,height:Je}}),U=cn([...ye,...ee,...[...q.values()].map(Z=>({x:Z.x,y:Z.y-Wt,width:Z.width,height:Z.height+Wt}))]);k(Z=>Z.map(Q=>{const G=q.get(Q.id);return G?an(Q,G):Q.id===oe?U?an({...Q,cols:Math.max(1,Math.round(pe))},U):{...Q,cols:Math.max(1,Math.round(pe))}:Q})),j()},[j]),T=s.useCallback(()=>{const oe=f.current,pe=I.current,K=w.current,fe=x.current,ie=oe.size+pe.size+K.size+fe.size;if(ie<2)return;const Y=new Map,re=(N,Z)=>{if(N==null)return;const Q=Y.get(N)??{sel:0,all:0};Q.all+=1,Z&&(Q.sel+=1),Y.set(N,Q)};for(const N of u.current)re(N.groupId,oe.has(N.id));for(const N of d.current)re(N.groupId,pe.has(N.id));for(const N of h.current)re(N.groupId,K.has(N.id));for(const N of g.current)re(N.groupId,fe.has(N.id));const le=y.current.filter(N=>{const Z=Y.get(N.id);return!!Z&&Z.all>0&&Z.sel===Z.all}),b=le.filter(N=>N.parentId==null&&!y.current.some(Z=>Z.parentId===N.id));if(le.length!==b.length){A({title:"Groups only nest one level deep â ungroup the outer group first.",variant:"error"});return}if(b.length){const N=new Set(b.map(Ee=>Ee.id)),Z=(Ee,qe)=>qe.has(Ee.id)&&!(Ee.groupId!=null&&N.has(Ee.groupId)),Q=u.current.filter(Ee=>Z(Ee,oe)),G=d.current.filter(Ee=>Z(Ee,pe)),se=h.current.filter(Ee=>Z(Ee,K)),ne=g.current.filter(Ee=>Z(Ee,fe)),de=b.length+Q.length+G.length+se.length+ne.length;if(de<2)return;const F=R.current++,$={slide:new Set(Q.map(Ee=>Ee.id)),doc:new Set(G.map(Ee=>Ee.id)),note:new Set(se.map(Ee=>Ee.id)),image:new Set(ne.map(Ee=>Ee.id))},P=b.map(Ee=>{var qe;return(qe=t.current.find(Ae=>Ae.id===Ee.id))==null?void 0:qe.frame}).filter(Ee=>!!Ee).map(Ee=>
31({x:Ee.x,y:Ee.y-Wt,width:Ee.width,height:Ee.height+Wt})),me=cn([...P,...Q.map(Ee=>({x:Ee.x,y:Ee.y,width:Ke,height:Je})),...G,...se,...ne]),he=qn(de,1,ys),Me={id:F,title:"",cols:he,snap:!0};k(Ee=>[...Ee.map(qe=>N.has(qe.id)?{...qe,parentId:F}:qe),{...me?an(Me,me):Me,title:`Group ${Ee.length+1}`}]);const He=(Ee,qe)=>Ee.map(Ae=>$[qe].has(Ae.id)?{...Ae,groupId:F}:Ae);l(Ee=>He(Ee,"slide")),G.length&&c(Ee=>He(Ee,"doc")),se.length&&p(Ee=>He(Ee,"note")),ne.length&&m(Ee=>He(Ee,"image")),setTimeout(()=>O(F,he)),o(F),j();return}const C=ie===oe.size,z=R.current++;let B=u.current.map(N=>oe.has(N.id)?{...N,groupId:z}:N);C&&(B=Xi(B,z,Od,In));let M=null;if(!C){const N=(se,ne)=>se.y-ne.y||se.x-ne.x,Z=[...B.filter(se=>oe.has(se.id)).map(se=>({kind:"slide",id:se.id,x:se.x,y:se.y,width:Ke,height:Je})),...d.current.filter(se=>pe.has(se.id)).map(se=>({kind:"doc",id:se.id,x:se.x,y:se.y,width:se.width,height:se.height})),...h.current.filter(se=>K.has(se.id)).map(se=>({kind:"note",id:se.id,x:se.x,y:se.y,width:se.width,height:se.height})),...g.current.filter(se=>fe.has(se.id)).map(se=>({kind:"image",id:se.id,x:se.x,y:se.y,width:se.width,height:se.height}))].sort(N),Q=Math.min(...Z.map(se=>se.x)),G=Math.min(...Z.map(se=>se.y));M=vo(Z,Q,G,Z.length),B=B.map(se=>{const ne=M.get(Ye("slide",se.id));return ne?{...se,x:ne.x,y:ne.y}:se})}const q=(N,Z)=>M?N.map(Q=>{const G=M.get(Ye(Z,Q.id));return G?{...Q,x:G.x,y:G.y}:Q}):N,ue=pe.size?q(d.current.map(N=>pe.has(N.id)?{...N,groupId:z}:N),"doc"):null,ye=K.size?q(h.current.map(N=>K.has(N.id)?{...N,groupId:z}:N),"note"):null,ee=fe.size?q(g.current.map(N=>fe.has(N.id)?{...N,groupId:z}:N),"image"):null,U=cn([...B.filter(N=>N.groupId===z).map(N=>({x:N.x,y:N.y,width:Ke,height:Je})),...(ue??[]).filter(N=>N.groupId===z),...(ye??[]).filter(N=>N.groupId===z),...(ee??[]).filter(N=>N.groupId===z)]),_={id:z,title:""};k(N=>[...N,{...U?an(_,U):_,title:C?`Presentation ${N.length+1}`:`Group ${N.length+1}`}]),l(B),ue&&c(ue),ye&&p(ye),ee&&m(ee),o(z),j()},[j,o,A,O]),X=s.useCallback(()=>{const oe=n.current;if(oe.size){const K=new Set(oe),fe=new Set(y.current.filter(Y=>Y.parentId!=null&&K.has(Y.parentId)).map(Y=>Y.id)),ie=Y=>Y.groupId!=null&&K.has(Y.groupId)?{...Y,groupId:null}:Y;l(Y=>Y.map(ie)),c(Y=>Y.map(ie)),p(Y=>Y.map(ie)),m(Y=>Y.map(ie)),k(Y=>Y.filter(re=>!K.has(re.id)).map(re=>fe.has(re.id)?{...re,parentId:null}:re)),j();return}const pe=new Set;for(const K of u.current)f.current.has(K.id)&&K.groupId!=null&&pe.add(K.groupId);for(const K of d.current)I.current.has(K.id)&&K.groupId!=null&&pe.add(K.groupId);for(const K of h.current)w.current.has(K.id)&&K.groupId!=null&&pe.add(K.groupId);for(const K of g.current)x.current.has(K.id)&&K.groupId!=null&&pe.add(K.groupId);pe.size&&(l(K=>K.map(fe=>fe.groupId!=null&&pe.has(fe.groupId)?{...fe,groupId:null}:fe)),c(K=>K.map(fe=>fe.groupId!=null&&pe.has(fe.groupId)?{...fe,groupId:null}:fe)),p(K=>K.map(fe=>fe.groupId!=null&&pe.has(fe.groupId)?{...fe,groupId:null}:fe)),m(K=>K.map(fe=>fe.groupId!=null&&pe.has(fe.groupId)?{...fe,groupId:null}:fe)),k(K=>K.filter(fe=>!pe.has(fe.id))),j())},[j]),L=s.useCallback((oe,pe)=>{k(K=>K.map(fe=>fe.id===oe?{...fe,title:pe}:fe)),j()},[j]),W=s.useCallback((oe,pe)=>{const K=t.current.find(M=>M.id===oe);if(!K)return;const fe=(M,q)=>M.y-q.y||M.x-q.x,ie=K.memberRects.filter(M=>M.kind==="slide").sort(fe),Y=K.memberRects.filter(M=>M.kind!=="slide").sort(fe),re=[...K.memberRects].sort(fe),le=vo(re,K.frame.x+Ht,K.frame.y+Ht,pe??re.length,K.parentId!=null?Ht:fa,K.parentId!=null?Ht:ha),b=new Map(ie.map(M=>[M.id,le.get(Ye("slide",M.id))]).filter(([,M])=>!!M)),C=new Map(Y.map(M=>[Ye(M.kind,M.id),le.get(Ye(M.kind,M.id))]).filter(([,M])=>!!M));b.size&&l(M=>M.map(q=>{const ue=b.get(q.id);return ue&&(q.x!==ue.x||q.y!==ue.y)?{...q,x:ue.x,y:ue.y}:q}));const z=(M,q)=>M.map(ue=>{const ye=C.get(Ye(q,ue.id));return ye&&(ue.x!==ye.x||ue.y!==ye.y)?{...ue,x:ye.x,y:ye.y}:ue});c(M=>z(M,"doc")),p(M=>z(M,"note")),m(M=>z(M,"image"));const B=cn([...ie.map(M=>({...M,...b.get(M.id)??{}})),...Y.map(M=>({...M,...C.get(Ye(M.kind,M.id))??{}}))]);B&&k(M=>M.map(q=>q.id===oe?an(q,B):q))},[]),H=s.useCallback((oe,pe)=>{if(y.current.some(re=>re.parentId===oe)){O(oe,qn(Math.round(pe),1,ys));return}const K=qn(Math.round(pe),1,ys),fe=t.current.find(re=>re.id===oe);if(fe&&fe.parentId==null&&fe.memberRects.some(re=>re.kind!=="slide")){k(re=>re.map(le=>le.id===oe?{...le,cols:K}:le)),W(oe,K),j();return}const ie=Xi(u.current,oe,K,In),Y=cn(ie.filter(re=>re.groupId===oe).map(re=>({x:re.x,y:re.y,width:Ke,height:Je})));k(re=>re.map(le=>le.id===oe?Y?an({...le,cols:K},Y):{...le,cols:K}:le)),l(ie),j()},[j,O,W]),ae=s.useCallback(oe=>{var z;const pe=t.current.find(B=>B.id===oe);if(!pe)return;if(pe.parentId==null){W(oe,(z=y.current.find(B=>B.id===oe))==null?void 0:z.cols),j();return}const K=(B,M)=>
31B.y-M.y||B.x-M.x,fe=pe.memberRects.filter(B=>B.kind==="slide").sort(K),ie=pe.memberRects.filter(B=>B.kind!=="slide").sort(K),Y=vu(pe.memberRects,pe.frame.x+Ht,pe.frame.y+Ht),re=new Map(fe.map(B=>[B.id,Y.get(Ye("slide",B.id))]).filter(([,B])=>!!B)),le=new Map(ie.map(B=>[Ye(B.kind,B.id),Y.get(Ye(B.kind,B.id))]).filter(([,B])=>!!B));re.size&&l(B=>B.map(M=>{const q=re.get(M.id);return q&&(M.x!==q.x||M.y!==q.y)?{...M,x:q.x,y:q.y}:M}));const b=(B,M)=>B.map(q=>{const ue=le.get(Ye(M,q.id));return ue&&(q.x!==ue.x||q.y!==ue.y)?{...q,x:ue.x,y:ue.y}:q});c(B=>b(B,"doc")),p(B=>b(B,"note")),m(B=>b(B,"image"));const C=cn([...fe.map(B=>({...B,...re.get(B.id)??{}})),...ie.map(B=>({...B,...le.get(Ye(B.kind,B.id))??{}}))]);if(C){const B=pe.parentId;k(M=>M.map(q=>{if(q.id===oe)return an(q,C);if(B!=null&&q.id===B){const ue=t.current.find(U=>U.id===B),ye=t.current.filter(U=>U.parentId===B&&U.id!==oe),ee=cn([...(ue==null?void 0:ue.memberRects)??[],...[C,...ye.map(U=>U.frame)].map(U=>({x:U.x,y:U.y-Wt,width:U.width,height:U.height+Wt}))]);return ee?an(q,ee):q}return q}))}j()},[j]),ge=s.useCallback(oe=>{var K,fe;const pe=!dr(y.current.find(ie=>ie.id===oe),((K=t.current.find(ie=>ie.id===oe))==null?void 0:K.slidesOnly)??!1);k(ie=>ie.map(Y=>Y.id===oe?{...Y,snap:pe}:Y)),pe&&(y.current.some(Y=>Y.parentId===oe)?O(oe,((fe=y.current.find(Y=>Y.id===oe))==null?void 0:fe.cols)??kr):ae(oe)),j()},[j,ae,O]),J=s.useCallback((oe,pe)=>{const K=t.current.find(fe=>fe.id===oe);k(fe=>fe.map(ie=>ie.id===oe?an(ie,Yy(pe,(K==null?void 0:K.contentBounds)??null)):ie)),j()},[j]),ce=s.useCallback(oe=>{const pe=t.current.find(K=>K.id===oe);!pe||pe.members.length===0||(k(K=>K.map(fe=>fe.id===oe?{...fe,collapsed:!fe.collapsed}:fe)),j())},[j]),we=s.useCallback(oe=>{const pe=t.current.find(ie=>ie.id===oe);if(!pe)return;const K=new Set(pe.allItemKeys),fe={slide:new Set(u.current.filter(ie=>K.has(Ye("slide",ie.id))).map(ie=>ie.id)),doc:new Set(d.current.filter(ie=>K.has(Ye("doc",ie.id))).map(ie=>ie.id)),note:new Set(h.current.filter(ie=>K.has(Ye("note",ie.id))).map(ie=>ie.id)),image:new Set(g.current.filter(ie=>K.has(Ye("image",ie.id))).map(ie=>ie.id)),web:new Set};a(i(fe),pe.frame.width+Ht,0)},[i,a]),ve=s.useCallback(oe=>{const pe=t.current.find(ie=>ie.id===oe);if(!pe)return;const K=new Set(pe.allItemKeys),fe=new Set([oe,...y.current.filter(ie=>ie.parentId===oe).map(ie=>ie.id)]);S.current(d.current.filter(ie=>K.has(Ye("doc",ie.id)))),l(ie=>ie.filter(Y=>!K.has(Ye("slide",Y.id)))),c(ie=>ie.filter(Y=>!K.has(Ye("doc",Y.id)))),p(ie=>ie.filter(Y=>!K.has(Ye("note",Y.id)))),m(ie=>ie.filter(Y=>!K.has(Ye("image",Y.id)))),k(ie=>ie.filter(Y=>!fe.has(Y.id))),D(),j()},[D,j,S]);return{arrangeDeckRows:O,groupSelectedSlides:T,ungroupSelectedSlides:X,renameGroup:L,relayoutMixedGroup:W,setGroupCols:H,arrangeGroup:ae,toggleGroupSnap:ge,resizeGroup:J,toggleGroupCollapsed:ce,duplicateGroup:we,deleteGroup:ve}}function vw({store:e,snapshotChart:t}){const{slidesRef:n,groupsRef:o,flushSave:i,showToast:a}=e,[l,u]=s.useState(null),[c,d]=s.useState(null),[p,h]=s.useState(null),m=s.useRef(!1),g=s.useCallback(async(f,I,w)=>{if(m.current)return;const x=f.map(D=>{var R;return{id:String(D.id),background:(R=D.baked)==null?void 0:R.background}});if(x.length){m.current=!0,u(w.groupId),d(w.slideId);try{await i(),h(new Set(f.map(j=>j.id))),await xg(x.map(j=>j.id));const D=f.filter(j=>j.graphyConfig&&j.baked&&!Fd(j.baked));if(D.length){const{captureChartPng:j}=await ta(async()=>{const{captureChartPng:S}=await import("./birtvyGraphyCapture-rI0LAw6d.js");return{captureChartPng:S}},[]);for(const S of D){const A=Gd(S.baked),O=document.querySelector(`[data-graphy-chart="${S.id}"]`);if(!(!A||!O||!O.querySelector("svg *, canvas")))try{const T=await j(O,{width:A.width,height:A.height},{x:0,y:0,w:A.width,h:A.height});T.length>2e3&&t(S.id,T,{w:A.width,h:A.height})}catch(T){console.warn("birtvy export: chart snapshot failed â exporting the live render instead",T)}}await new Promise(S=>setTimeout(S,80))}const R=await Hp(x,`${I}.pdf`);R.ok<R.total&&a({title:R.ok?`Exported ${R.ok} of ${R.total} slides â ${R.total-R.ok} couldn't be captured.`:"Export failed â no slides could be captured. Try again.",variant:R.ok?void 0:"error"})}catch(D){console.warn("birtvy: group PDF export failed",D),a({title:"Export failed. Try again.",variant:"error"})}finally{h(null),u(null),d(null),m.current=!1}}},[n,o,i,a,t]),k=s.useCallback(f=>{var x;const I=ua(n.current,o.current,f),w=((x=o.current.find(D=>D.id===f))==null?void 0:x.title)||"presentation";return g(I,w,{groupId:f,slideId:null})},[g,n,o]),y=s.useCallback(f=>{var w;const I=n.current.find(x=>x.id===f);return I?g([I],((w=I.docMeta)==null?void 0:w.title)||"artifact",{groupId:null,
31slideId:f}):Promise.resolve()},[g,n]);return{exportGroup:k,exportSlide:y,exportingGroupId:l,exportingSlideId:c,exportLiveIds:p}}function kw({store:e,slides:t,docs:n,notes:o,images:i,groups:a}){const{setSlides:l,setDocs:u,setNotes:c,setImages:d,setGroups:p}=e;s.useEffect(()=>{const h=[...t.map(I=>I.groupId),...n.map(I=>I.groupId),...o.map(I=>I.groupId),...i.map(I=>I.groupId)],{keep:m,remap:g,clearParent:k,changed:y}=Jy(a,h);if(!y)return;p(I=>I.filter(w=>m.has(w.id)).map(w=>k.has(w.id)?{...w,parentId:null}:w));const f=I=>I.groupId!=null&&!m.has(I.groupId)?{...I,groupId:g.get(I.groupId)??null}:I;l(I=>I.some(w=>w.groupId!=null&&!m.has(w.groupId))?I.map(f):I),u(I=>I.some(w=>w.groupId!=null&&!m.has(w.groupId))?I.map(f):I),c(I=>I.some(w=>w.groupId!=null&&!m.has(w.groupId))?I.map(f):I),d(I=>I.some(w=>w.groupId!=null&&!m.has(w.groupId))?I.map(f):I)},[t,n,o,i,a,l,u,c,d,p])}function Sw({store:e,demo:t,demoRef:n,isAgentOpen:o,AGENT_WIDTH:i,apply:a,setZoomPct:l,setLod:u,focusCancelRef:c,revealDocsInPlace:d,setWebBusy:p,setDemoBusyKinds:h}){const{setSlides:m,setNotes:g,setDocs:k,setImages:y,setWebs:f,setSelectedIds:I,setSelectedNoteIds:w,setSelectedWebIds:x,idRef:D,viewportRef:R,pan:j,zoom:S}=e,A=s.useCallback((T,X=!0,L,W=!1)=>{var we;const H=R.current;if(!H||T.w<=0||T.h<=0)return;const ae=Math.max(1,H.clientWidth-(o?i:0)),ge=H.clientHeight,J=qn(W?Math.max(ae/T.w,ge/T.h):Math.min(ae/T.w,ge/T.h)*.82,gs,1),ce={x:ae/2-(T.x+T.w/2)*J,y:ge/2-(T.y+T.h/2)*J};if((we=c.current)==null||we.call(c),!X){S.current=J,j.current=ce,a(),l(J*100),u(J*100<fr);return}c.current=Rd({fromPan:{x:j.current.x,y:j.current.y},fromZoom:S.current,toPan:ce,toZoom:J,duration:L,easing:Up,logZoom:!0,onUpdate:(ve,oe)=>{j.current=ve,S.current=oe,a()},onComplete:()=>{c.current=null,l(S.current*100),u(S.current*100<fr)}})},[a,o]),O=t;n.current=!!t,s.useEffect(()=>{O!=null&&O.onReady&&O.onReady({reset:()=>{var T;(T=c.current)==null||T.call(c),m([]),g([]),k([]),y([]),f([]),I(new Set),w(new Set),x(new Set),p(null),h(new Set)},addNote:(T,X)=>{g(L=>[...L,{id:D.current++,x:X.x,y:X.y,width:Or,height:Or,content:T,color:"default"}])},addSlide:(T,X)=>{const L=D.current++;m(W=>[...W,{id:L,x:X.x,y:X.y,status:"done",prompt:"",html:gn(T,L),baked:T}])},addDoc:(T,X)=>{const L=D.current++;k(W=>[...W,{id:L,x:X.x,y:X.y,width:T.width??En,height:T.height??Cn,content:T.content,title:T.title}]),d([L])},frameRect:(T,X)=>A(T,(X==null?void 0:X.animate)??!0,X==null?void 0:X.durationMs,X==null?void 0:X.fill),addWeb:(T,X)=>{const L=D.current++;return f(W=>[...W,{width:cr.width,height:cr.height,...T,id:L,x:Math.round(X.x),y:Math.round(X.y)}]),L},updateWeb:(T,X)=>{f(L=>L.map(W=>W.id===T?{...W,...X}:W))},selectWeb:T=>x(T==null?new Set:new Set([T])),setExtracting:T=>h(new Set((T==null?void 0:T.kinds)??[])),addBrandTiles:(T,X,L)=>{const W=Ad({x:X.x,y:X.y},T,()=>D.current++);if(W.length===0)return;const H=(L==null?void 0:L.scale)??1,ae=H===1?W:W.map(ge=>({...ge,x:Math.round(X.x+(ge.x-X.x)*H),y:Math.round(X.y+(ge.y-X.y)*H),width:Math.round(ge.width*H),height:Math.round(ge.height*H)}));f(ge=>[...ge,...ae])},addImages:(T,X,L)=>{if(L!=null&&L.slots){const ve=T.map((K,fe)=>{const ie=L.slots[fe]??L.slots[L.slots.length-1],Y=Wr(K.naturalWidth,K.naturalHeight);return{src:K.src,x:Math.round(ie.x),y:Math.round(ie.y),width:Math.round(ie.w??Y.width),height:Math.round(ie.h??Y.height)}});y(K=>[...K,...ve.map(fe=>({id:D.current++,x:fe.x,y:fe.y,width:fe.width,height:fe.height,src:fe.src,sourceUrl:L==null?void 0:L.sourceUrl}))]);const oe=Math.min(...ve.map(K=>K.x)),pe=Math.min(...ve.map(K=>K.y));return{width:Math.max(...ve.map(K=>K.x+K.width))-oe,height:Math.max(...ve.map(K=>K.y+K.height))-pe}}const W=(L==null?void 0:L.maxRowWidth)??2400,H=[];let ae=0,ge=0,J=0;for(const ve of T){const oe=Wr(ve.naturalWidth,ve.naturalHeight);ae>0&&ae+oe.width>W&&(ae=0,ge+=J+ms,J=0),H.push({src:ve.src,x:X.x+ae,y:X.y+ge,width:oe.width,height:oe.height}),ae+=oe.width+ms,J=Math.max(J,oe.height)}const ce=H.reduce((ve,oe)=>Math.max(ve,oe.x+oe.width-X.x),0),we=H.reduce((ve,oe)=>Math.max(ve,oe.y+oe.height-X.y),0);return H.length===0?{width:0,height:0}:(y(ve=>[...ve,...H.map(oe=>({id:D.current++,x:Math.round(oe.x),y:Math.round(oe.y),width:oe.width,height:oe.height,src:oe.src,sourceUrl:L==null?void 0:L.sourceUrl}))]),{width:ce,height:we})}})},[O,A,d,p,h])}function Iw({demo:e,selectedCount:t,bottom:n,left:o,dockMs:i,dockEase:a}){const l=s.useRef(null);return s.useEffect(()=>{let u=0,c=performance.now(),d=0,p=0;const h=m=>{d+=m-c,c=m,p+=1,d>=250&&(l.current&&(l.current.textContent=String(Math.round(p*1e3/d))),d=0,p=0),u=requestAnimationFrame(h)};return u=requestAnimationFrame(h),()=>cancelAnimationFrame(u)},[]),e?null:r.jsxs("div",{style:{position:"absolute",zIndex:20,bottom:n,left:o,transition:`bottom ${i}ms ${a}, left ${i}ms ${a}`,display:"flex",alignItems:"center",gap:8,background:"#18181b",color:"#fff",padding:"6px 12px",borderRadius:8,fontSize:12},children:[r.jsx("span",{style:{color:"#a1a1aa"},children:"fps"}),r.jsx("span",{ref:l,style:{fontVariantNumeric:"tabular-nums",fontWeight:800,minWidth:26,textAlign:"right",color:"#4ade80"},children:"â"}),t>0?r.jsxs("span",{style:{color:"#a1a1aa",marginLeft:8},children:["· ",t," selected"]}):null]})}const Cw=s.lazy(()=>ta(()=>import("./index.es-CFf7dwvF.js"),__vite__mapDeps([0,1])));function Ew(){return r.jsx("div",{style:{position:"absolute",inset:0,zIndex:4,display:"flex",alignItems:"center",justifyContent:"center",background:"#ffffff",pointerEvents:"none"},children:r.jsx(s.Suspense,{fallback:null,children:r.jsx(Cw,{animationData:Lg,loop:!0,style:{width:"35%"}})})})}function Rw(e){var n;const t=s.useRef(null);return e==null?t.current=null:(t.current==null||t.current.baked!==e)&&(t.current={baked:e,v2:e.includes(Ud)}),((n=t.current)==null?void 0:n.v2)===!0}function Mw({slide:e,z:t,selected:n,lod:o,glMode:i,thumbTick:a,docStreaming:l=!1,docActive:u=!1,docWarmHold:c=!1,restLive:d=!1,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onOpen:g,onChartSnapshot:k,onDocBaked:y}){var D,R;const f=o&&!!e.html,I=Rw(e.docBaked),w={position:"absolute",left:e.x,top:e.y,width:Ke,height:Je,background:"#ffffff",borderRadius:32,zIndex:t,boxShadow:Io(n),transition:So,overflow:"hidden",contain:"layout style paint",contentVisibility:"auto",containIntrinsicSize:`${Ke}px ${Je}px`},x=s.useRef(!1);return l?x.current=!0:e.docBaked&&(x.current=!1),e.docHtml?o&&!l&&!!e.docBaked&&e.docBaked?i&&Br()?r.jsx("div",{"data-sli
31de-id":e.id,style:{...w,background:ji(e.docBaked)},onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g}):r.jsx("div",{"data-slide-id":e.id,style:w,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g,children:r.jsx(cd,{html:`<style>${Hr()??""}</style>`+e.docBaked,background:ji(e.docBaked),tick:a,doc:!0})}):(o||c)&&!l&&!u&&!e.docBaked&&!x.current?r.jsx("div",{"data-slide-id":e.id,style:i&&Br()?{...w,background:Nw(e.docHtml)}:w,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g}):!o&&i&&Br()&&e.docBaked&&!l&&!u&&!d?r.jsx("div",{"data-slide-id":e.id,style:{...w,background:ji(e.docBaked)},onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g}):r.jsx("div",{"data-slide-id":e.id,style:w,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g,children:r.jsx(Tw,{html:e.docHtml,slideId:e.id,streaming:l,active:u||l,baked:e.docBaked,bakedV2:I,warmHold:c,onBaked:y})}):e.status==="generating"?r.jsx("div",{"data-slide-id":e.id,style:w,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,children:e.html?r.jsx("div",{style:{position:"relative",width:Ke,height:Je,overflow:"hidden"},dangerouslySetInnerHTML:{__html:e.html}}):null}):e.graphyConfig&&!Fd(e.baked)?r.jsx("div",{"data-slide-id":e.id,style:w,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g,children:r.jsxs("div",{"data-deckgen-slide-surface":"","data-slide-id":e.id,style:{position:"relative",width:Ke,height:Je,overflow:"hidden"},children:[e.html?r.jsx("div",{style:{position:"absolute",inset:0},dangerouslySetInnerHTML:{__html:e.html}}):null,(()=>{const j=Gd(e.baked);return j?r.jsx("div",{"data-graphy-chart":e.id,style:{position:"absolute",left:j.x,top:j.y,width:j.width,height:j.height,pointerEvents:"none"},children:r.jsx(jo,{config:e.graphyConfig,interactive:!1,responsive:!0,onSnapshot:k})}):null})()]})}):e.html?r.jsx("div",{"data-slide-id":e.id,style:f?{...w,background:((D=e.baked)==null?void 0:D.background)||"#ffffff"}:w,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g,children:f?i?null:r.jsx(cd,{html:e.html,background:(R=e.baked)==null?void 0:R.background,tick:a}):r.jsx("div",{"data-deckgen-slide-surface":"","data-slide-id":e.id,style:{position:"relative",width:Ke,height:Je,overflow:"hidden",cursor:e.baked?"pointer":"default"},dangerouslySetInnerHTML:{__html:e.html}})}):r.jsx("div",{"data-slide-id":e.id,style:w,onPointerDown:p,onPointerEnter:h,onPointerLeave:m,onDoubleClick:g})}const oo=()=>{},Mi={width:Ke,height:Je,border:0,display:"block",pointerEvents:"none"},jw=250,io=new Map;function ji(e){const t=io.get(e);if(t!==void 0)return t;const n=/background-color:\s*([^;"']+)/.exec(e),o=n?n[1].trim():"#ffffff";return io.size>240&&io.clear(),io.set(e,o),o}const ao=new Map;function Nw(e){const t=ao.get(e);if(t!==void 0)return t;const n=/--a-bg:\s*([^;}]+)/.exec(e),o=n?null:/background(?:-color)?:\s*(#[0-9a-fA-F]{3,8}|rgb[^;}]+|hsl[^;}]+)/.exec(e),i=(n?n[1]:o?o[1]:"#f4f4f5").trim();return ao.size>240&&ao.clear(),ao.set(e,i),i}const Dw=3;function Tw({html:e,slideId:t,streaming:n,active:o,baked:i,bakedV2:a,warmHold:l=!1,onBaked:u}){const[c,d]=s.useState(n?"live":"off"),p=s.useRef(!1);p.current||(p.current=!0);const[h,m]=s.useState(!1),g=c!=="off",k=s.useRef(e);k.current=e;const y=s.useRef(u);y.current=u;const f=s.useRef(0),I=s.useRef(e),w=s.useRef(Vn(e)),x=s.useRef(null);if(I.current!==e){const B=Zm(I.current,e);I.current=e,B?(x.current=B,oo(t,`html changed: LOGO-ONLY (${B.length} fills) â keeping mounted document`)):(f.current+=1,w.current=Vn(e),x.current=null,oo(t,`html changed: remount -> gen ${f.current}`))}const D=f.current,R=s.useRef(i!=null?{baked:i,html:e}:null);i==null?R.current=null:(R.current==null||R.current.baked!==i)&&(R.current={baked:i,html:e});const j=i!=null&&a&&R.current!=null&&R.current.html===e,S=j||l&&i!=null&&R.current!=null&&R.current.html===e,[A,O]=s.useState(o);s.useEffect(()=>{if(!o){O(!1);return}if(n){O(!0);return}const B=window.setTimeout(()=>O(!0),jw);return()=>window.clearTimeout(B)},[o,n]);const T=A||g,X=T||!S;s.useEffect(()=>{if(n){d("live"),m(!1),le(!1);return}if(c==="live"){const B=h?300:6e3,M=window.setTimeout(()=>d("fading"),B);return()=>
31window.clearTimeout(M)}if(c==="fading"){const B=window.setTimeout(()=>d("off"),240);return()=>window.clearTimeout(B)}},[n,c,h]);const[L,W]=s.useState(-1);s.useEffect(()=>{X||(W(-1),w.current=Vn(k.current),x.current=null)},[X]);const H=X&&L===D,[ae,ge]=s.useState(null),J=ae!=null,ce=H||!J,we=!(X&&ce),ve=s.useRef(null);s.useLayoutEffect(()=>{var ue;const B=ve.current;if(!B||i==null||!S||ae===i)return;const M=B.shadowRoot??B.attachShadow({mode:"open"});M.innerHTML=i,ge(i);const q=(ue=M.querySelector("[data-bds-root]"))==null?void 0:ue.getAttribute("data-bds-fonts");if(q)try{const ye=JSON.parse(q);Array.isArray(ye)&&bo(ye.filter(ee=>typeof ee=="string"))}catch{}},[i,S,ae]);const oe=s.useRef(null),pe=s.useRef(null);s.useEffect(()=>{var M,q;if(!H)return;const B=x.current;B&&(x.current=null,oo(t,`logo fill posted (${B.length})`),(q=(M=pe.current)==null?void 0:M.contentWindow)==null||q.postMessage({__bds_logos:B},"*"))},[H,e]);const[K,fe]=s.useState(!1),ie=s.useRef(0),Y=s.useRef(e);Y.current!==e&&(Y.current=e,ie.current=0),s.useEffect(()=>{if(!(!T&&!n&&!j&&H)){K&&fe(!1);return}if(K)return;const M=e;let q=null;const ue=window.setTimeout(()=>{q=Hd({id:t,getWindow:()=>{var ye;return(ye=pe.current)==null?void 0:ye.contentWindow},getPriority:()=>{var ee;const ye=(ee=oe.current)==null?void 0:ee.getBoundingClientRect();return ye&&ye.right>0&&ye.bottom>0&&ye.left<window.innerWidth&&ye.top<window.innerHeight?0:1},onDone:ye=>{var ee;if(oo(t,`bake reply ok=${ye.ok}`),ye.ok&&ye.html!=null){if(k.current!==M)return;ye.fontHrefs&&bo(ye.fontHrefs),(ee=y.current)==null||ee.call(y,ye.html)}else fe(!0)}})},900);return()=>{window.clearTimeout(ue),q==null||q()}},[T,n,j,H,e,t,K]),s.useEffect(()=>{if(!(K&&!T&&!n&&!j)||ie.current>=Dw)return;const M=oe.current;if(!M)return;const q=new IntersectionObserver(ue=>{ue.some(ye=>ye.isIntersecting)&&(q.disconnect(),ie.current+=1,fe(!1))},{threshold:0});return q.observe(M),()=>q.disconnect()},[K,T,n,j]),s.useEffect(()=>{var B,M;!X||L!==f.current||(M=(B=pe.current)==null?void 0:B.contentWindow)==null||M.postMessage({__bfz:!T},"*")},[T,X,L]);const[re,le]=s.useState(!1),b=s.useRef(null);s.useEffect(()=>{if(!g)return;const B=M=>{var q,ue;M.source===((q=b.current)==null?void 0:q.contentWindow)&&(ue=M.data)!=null&&ue.__bds_skel_done&&le(!0)};return window.addEventListener("message",B),()=>window.removeEventListener("message",B)},[g]);const C=s.useRef(null),z=s.useCallback(B=>{var ue;if((ue=C.current)==null||ue.call(C),C.current=null,b.current=B,!B)return;let M=null;const q=()=>{const ye=B.contentWindow;ye&&(ye.postMessage({__bds:1,t:"hello",skeleton:!0,ground:!0},"*"),M=ho.subscribe(t,ee=>{ee.delta!=null&&ye.postMessage({__bds:1,t:"chunk",s:ee.delta},"*"),ee.refresh!=null&&ye.postMessage({__bds:1,t:"refresh",s:ee.refresh},"*"),ee.done&&(ye.postMessage({__bds:1,t:"done"},"*"),m(!0))}))};B.addEventListener("load",q),C.current=()=>{B.removeEventListener("load",q),M==null||M()}},[t]);return r.jsxs("div",{ref:oe,style:{position:"relative",width:Ke,height:Je},children:[r.jsx("div",{ref:ve,style:{...Mi,position:"absolute",inset:0,zIndex:0,overflow:"hidden",visibility:we?"visible":"hidden"}}),X?r.jsx("iframe",{ref:pe,srcDoc:w.current,sandbox:"allow-scripts",title:`Slide ${t}`,onLoad:()=>{W(D)},style:{...Mi,position:"relative",zIndex:1,visibility:ce?"visible":"hidden"}},`live${D}`):null,g?r.jsx("iframe",{ref:z,srcDoc:Tg(),sandbox:"allow-scripts",title:`Slide ${t} streaming`,style:{...Mi,position:"absolute",inset:0,zIndex:3,opacity:c==="fading"?0:1,transition:"opacity 220ms ease"}}):null,g&&!re?r.jsx(Ew,{}):null]})}function cd({html:e,background:t,tick:n,doc:o}){const i=s.useRef(null),a=s.useRef(null);return s.useEffect(()=>{var d;const l=_n("b",e);if(a.current===l)return;const u=Fr(l,e,512,o?{doc:!0}:void 0),c=i.current;u&&c&&(c.width=u.width,c.height=u.height,(d=c.getContext("2d"))==null||d.drawImage(u,0,0),a.current=l)},[e,n,o]),r.jsx("canvas",{ref:i,style:{display:"block",width:Ke,height:Je,background:t||"#ffffff"}})}const Aw=s.memo(function({slide:t,z:n,selected:o,lod:i,glMode:a,thumbTick:l,docStreaming:u,docActive:c,docWarmHold:d,restLive:p,onCardPointerDown:h,onHover:m,onHoverClear:g,onOpenSlide:k,onSnapshotChart:y,onDocBaked:f}
31){const I=mb(t.id);return r.jsx(Mw,{slide:t,z:n,selected:o,lod:i,glMode:a,thumbTick:l,docStreaming:u||I,docActive:c,docWarmHold:d,restLive:p,onPointerDown:w=>h(t.id,w),onPointerEnter:()=>m("slide",t.id),onPointerLeave:g,onOpen:()=>k(t.id),onChartSnapshot:(w,x)=>y(t.id,w,x),onDocBaked:w=>f==null?void 0:f(t.id,w)})}),$w="_frame_kzxy7_6",Pw="_barAnchor_kzxy7_16",Lw="_bar_kzxy7_16",zw="_labelPill_kzxy7_43",_w="_title_kzxy7_63",Ow="_titleInput_kzxy7_71",Bw="_actions_kzxy7_84",Fw="_chip_kzxy7_95",ln={frame:$w,barAnchor:Pw,bar:Lw,labelPill:zw,title:_w,titleInput:Ow,actions:Bw,chip:Fw};function Gw({icon:e,label:t,onClick:n,disabled:o,loading:i,loadingLabel:a}){const l=!!(i&&a);return r.jsx("div",{className:ln.chip,onPointerDown:u=>u.stopPropagation(),children:r.jsx(st,{variant:"soft",size:l?"xs":"icon-xs",onClick:u=>{u.stopPropagation(),n()},disabled:o||i,"aria-label":l?a:t,title:l?void 0:t,children:l?r.jsx("span",{className:"flex items-center gap-[var(--spacing-6)] text-[var(--color-text-subtle)]",children:r.jsx(Qd,{text:a,showLoadingDots:!1})}):r.jsx(At,{name:e,size:16,className:"text-[var(--color-icon-default-muted)]"})})})}function go({kind:e,id:t,x:n,y:o,title:i,busy:a,statusText:l,onRename:u,actions:c,extraLeading:d,onPointerEnter:p,onPointerLeave:h,onPointerDown:m}){const[g,k]=s.useState(!1),[y,f]=s.useState(i??""),I=s.useRef(null);s.useEffect(()=>{g||f(i??"")},[i,g]),s.useEffect(()=>{var x;g&&((x=I.current)==null||x.select())},[g]);const w=()=>{k(!1),y.trim()!==i&&(u==null||u(y))};return r.jsx("div",{"data-item-bar":`${e}:${t}`,"data-item-chrome":"",className:ln.barAnchor,style:{left:n,top:o,zIndex:1045},children:r.jsxs("div",{className:`${ln.bar}${m?" cursor-grab active:cursor-grabbing":""}`,onPointerEnter:p,onPointerLeave:h,onPointerDown:m,children:[i===void 0&&!a?null:r.jsx("div",{className:ln.labelPill,onDoubleClick:x=>{x.stopPropagation(),!a&&u&&k(!0)},children:a?r.jsx(Qd,{text:l||"Generating"}):g?r.jsx("input",{ref:I,className:ln.titleInput,value:y,onChange:x=>f(x.target.value),onBlur:w,onKeyDown:x=>{x.key==="Enter"&&w(),x.key==="Escape"&&(f(i??""),k(!1)),x.stopPropagation()},onPointerDown:x=>x.stopPropagation()}):r.jsx("span",{className:ln.title,title:u?"Double-click to rename":i,children:i})}),r.jsxs("div",{className:ln.actions,children:[d,c.map(({key:x,...D})=>r.jsx(Gw,{chipKey:x,...D},x))]})]})})}const Ww="_shimmer_zl2lk_19",Hw="_comet_zl2lk_49",Uw="_cometTop_zl2lk_60",Xw="_cometBottom_zl2lk_63",Yw="_sheen_zl2lk_140",Kw="_shimmerStatic_zl2lk_176",Pn={shimmer:Ww,comet:Hw,cometTop:Uw,cometBottom:Xw,sheen:Yw,shimmerStatic:Kw};function dd({onStop:e,variant:t="generating",lightweight:n=!1}){const o=n?`${Pn.shimmer} ${Pn.shimmerStatic}`:Pn.shimmer,i=r.jsxs("div",{className:o,"aria-hidden":!0,children:[r.jsx("div",{className:`${Pn.comet} ${Pn.cometTop}`}),r.jsx("div",{className:`${Pn.comet} ${Pn.cometBottom}`})]});return t==="writing"?i:t==="editing"?r.jsxs(r.Fragment,{children:[i,r.jsx("div",{className:Pn.sheen,"aria-hidden":!0}),r.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:r.jsxs("span",{className:"flex items-center rounded-full bg-black/85 text-white shadow-xl backdrop-blur-sm",style:{paddingInline:56,paddingBlock:32,fontSize:56,lineHeight:1,gap:24},children:[r.jsx("span",{"aria-hidden":!0,className:"inline-block shrink-0 animate-spin rounded-full border-white/30 border-t-white",style:{width:56,height:56,borderWidth:6}}),r.jsx("span",{style:{fontWeight:600},children:"Editing"})]})})]}):r.jsxs(r.Fragment,{children:[i,r.jsx("div",{className:Pn.sheen,"aria-hidden":!0}),r.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:r.jsxs("button",{type:"button",onMouseDown:a=>a.stopPropagation(),onPointerDown:a=>a.stopPropagation(),onClick:a=>{a.stopPropagation(),e==null||e()},className:"pointer-events-auto flex items-center rounded-full bg-black/85 text-white shadow-xl backdrop-blur-sm transition hover:bg-black",style:{paddingInline:56,paddingBlock:32,fontSize:56,lineHeight:1,gap:24},"aria-label":"Stop generating this slide",children:[r.jsx(At,{name:"stop",size:56}),r.jsx("span",{style:{fontWeight:600},children:"Stop"})]})})]})}const Vw=e=>{const t=Gi[Math.round(e)]??Ro;return t.charAt(0).toUpperCase()+t.slice(1)};function qw({creativity:e,textDensity:t,onCreativity:n,onTextDensity:o,openUp:i=!1}){return r.jsxs("div",{"data-canvas-scroll":!0,className:`absolute left-0 z-[1600] flex w-[248px] flex-col gap-[var(--spacing-8)] rounded-[var(--radius-lg)] border border-[var(--color-border-default)] bg-[var(--color-default)] p-[var(--spacing-12)] shadow-[var(--shadow-modal-md)] ${i?"bottom-full mb-2":"top-full mt-2"}`,onPointerDown:a=>a.stopPropagation(),children:[r.jsx(Ir,{mode:"continuous",min:Dg,max:Ng,step:jg,value:e,onCh
31ange:n,size:"md",label:"Creativity",ariaLabel:"Creativity",formatValue:a=>a.toFixed(2)}),r.jsx(Ir,{values:[0,1,2],selectedIndex:Math.max(0,Gi.indexOf(t)),onChange:a=>o(Gi[a]??Ro),size:"md",label:"Text",ariaLabel:"Text density",formatValue:Vw})]})}const Jw="_bar_74p18_4",Zw="_middle_74p18_20",Qw="_prompt_74p18_31",ev="_bottom_74p18_35",tv="_left_74p18_43",nv="_right_74p18_44",rv="_control_74p18_60",sv="_menu_74p18_67",ov="_menuUp_74p18_67",iv="_menuRow_74p18_93",av="_menuRowActive_74p18_113",Sn={bar:Jw,middle:Zw,prompt:Qw,bottom:ev,left:tv,right:nv,control:rv,menu:sv,menuUp:ov,menuRow:iv,menuRowActive:av},lv=[1,2,4];function cv(e){return e.startsWith("gemini")?{name:"sparkling-fill",preserveColors:!1}:e.startsWith("openai/")?{name:"brand-chatgpt",preserveColors:!0}:e.startsWith("claude")?{name:"claude-logo",preserveColors:!0}:{name:"sparkling-fill",preserveColors:!1}}function dv({value:e,onChange:t,onSubmit:n,onStop:o,onDismiss:i,busy:a,placeholder:l,statusText:u,codeTail:c,startedAt:d,model:p,onModelChange:h,creativity:m,textDensity:g,onCreativity:k,onTextDensity:y,attachments:f,onAddImages:I,onRemoveAttachment:w,designSystems:x,activeDesignSystemId:D,onSetActiveDesignSystem:R,onConcepts:j,conceptsLoading:S,conceptsOpen:A}){var B;const{modelAccess:O}=nu(),T=Md((O==null?void 0:O.currentTier)??null),[X,L]=s.useState(1),[W,H]=s.useState(!1),[ae,ge]=s.useState(!1),[J,ce]=s.useState(!1),[we,ve]=s.useState(!1),oe=s.useRef(null),pe=s.useRef(null),K=Ac(oe,[ae]),fe=Ac(pe,[J]),ie=s.useRef(null),Y=s.useRef(null),re=s.useRef(null),le=s.useRef(null);s.useEffect(()=>{if(!W&&!ae&&!J&&!we)return;const M=q=>{const ue=q.target;W&&ie.current&&!ie.current.contains(ue)&&H(!1),ae&&Y.current&&!Y.current.contains(ue)&&ge(!1),J&&re.current&&!re.current.contains(ue)&&ce(!1),we&&le.current&&!le.current.contains(ue)&&ve(!1)};return window.addEventListener("pointerdown",M,!0),()=>window.removeEventListener("pointerdown",M,!0)},[W,ae,J,we]);const b=s.useCallback(()=>{a||n(X)},[a,n,X]),C=s.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),b()):M.key==="Escape"&&(i==null||i())},[b,i]);(B=x==null?void 0:x.find(M=>M.id===D))==null||B.name;const z=cv(p);return r.jsxs("div",{className:Sn.bar,onPointerDown:M=>M.stopPropagation(),children:[r.jsxs("div",{className:Sn.middle,children:[f&&f.length>0?r.jsx(Og,{items:f,layout:"row",onRemove:w}):null,r.jsx("div",{className:Sn.prompt,children:r.jsx(zg,{value:e,placeholder:l??"Add instructions or ask for change...",disabled:a,onChange:M=>t(M.target.value),onKeyDown:C})})]}),r.jsxs("div",{className:Sn.bottom,children:[r.jsxs("div",{className:Sn.left,children:[null,r.jsxs("div",{className:Sn.control,ref:ie,children:[r.jsx(eu,{label:Zd[p],isOpen:W,onClick:()=>H(M=>!M),selectedId:p,leadIconName:z.name,leadIconPreserveColors:z.preserveColors,size:"sm"}),W?r.jsx(tu,{options:T,selectedId:p,onSelect:M=>{h(M),H(!1)},onLockedSelect:M=>{h(M),H(!1)}}):null]}),null,r.jsxs("div",{className:Sn.control,ref:Y,children:[r.jsxs(st,{variant:"ghost",size:"sm",tailIcon:"arrow-down-s",disabled:a,onClick:M=>{M.stopPropagation(),ge(q=>!q)},children:[X,"x"]}),ae?r.jsx("div",{ref:oe,role:"listbox","data-canvas-scroll":!0,className:`${Sn.menu} ${K?Sn.menuUp:""}`,children:lv.map(M=>r.jsxs("button",{type:"button",role:"option","aria-selected":X===M,className:`${Sn.menuRow} ${X===M?Sn.menuRowActive:""}`,onClick:q=>{q.stopPropagation(),L(M),ge(!1)},children:[M,"x"]},M))}):null]}),r.jsxs("div",{className:Sn.control,ref:re,children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"settings","aria-label":"Generation settings",title:"Creativity & text density",disabled:a,onClick:M=>{M.stopPropagation(),ce(q=>!q)}}),J?r.jsx("div",{ref:pe,children:r.jsx(qw,{creativity:m,textDensity:g,onCreativity:k,onTextDensity:y,openUp:fe})}):null]})]}),r.jsxs("div",{className:Sn.right,children:[r.jsx(st,{variant:"ghostMuted",size:"icon-xs",leadIcon:"add","aria-label":"Add images",title:"Add images",disabled:a,"data-active":f!=null&&f.length?"true":void 0,onClick:M=>{M.stopPropagation(),I==null||I()}}),r.jsx(_g,{mode:a?"stop":"send",disabled:a&&!o,onClick:()=>a?o==null?void 0:o():b()})]})]}),null]})}const uv="_flash_15sqq_3",fv={flash:uv};function hv(){const{slides:e,zOrder:t,selectedIds:n,selectedGroupIds:o,lod:i,exportLiveIds:a,glMode:l,thumbTick:u,editingSlideId:c,farNext:d,hoveredId:p,docWarmHoldIds:h,liveDocIds:m,onDocBaked:g,renameArtifact:k,exportSlide:y,exportingSlideId:f,onCardPointerDown:I,hover:w,hoverKeep:x,hoverClearSoon:D,openSlide:R,snapshotChart:j,redesigningIds:S,generatingCount:A,stopGenerate:O,editFlashes:T,openId:X,chromeVisible:L,totalSelected:W,chatEditSlideId:H,setPresentingSlideId:ae,toggleSlideExcluded:ge,duplicateSlide:J,deleteSlide:ce,editBarValues:we,setEditBarValues:ve,barAttachments:oe,setBarAttachments:pe,setSlidePrompt:K,editStatus:fe,editCodeTail:ie,editStartedAt:Y,generateDocSlide:re,editSlide:le,model:b,setModel:C,generateVariantsFromToolbar:z,slideGenCreativity:B,slideGenTextDensity:M,setSlideGenCreativity:q,setSlideGenTextDensity:ue,designSystems:ye,activeDesignSystemId:ee,setActiveDesignSystem:U,openConcepts:_,conceptsLoading:N,conceptsSlideId:Z}=Rn(),Q=s.useRef(null),G=s.useRef(null),se=s.useCallback(F=>{var $;G.current=F,($=Q.current)==null||$.click()},[]),ne=s.useCallback((F,$)=>{$!=null&&$.length&&Array.from($).filter(P=>
31P.type.startsWith("image/")).forEach(P=>{const me=new FileReader;me.onload=()=>{typeof me.result=="string"&&pe(he=>{const Me=he[F]??[];return{...he,[F]:[...Me,{id:`${P.name}:${P.size}:${Me.length}`,kind:"image",src:me.result,alt:P.name,name:P.name,interactive:!1}]}})},me.readAsDataURL(P)})},[pe]),de=s.useCallback((F,$)=>{const P=(we[F.id]??"").trim(),me=(oe[F.id]??[]).map(Me=>Me.src).filter(Me=>!!Me),he=()=>{ve(Me=>({...Me,[F.id]:""})),pe(Me=>({...Me,[F.id]:[]}))};if(F.docHtml){re(F.id,P||F.prompt||"Improve this slide. Keep its style.",me.length?{referenceImages:me}:void 0),he();return}if(P&&(F.baked||F.html)){le(F.id,P,void 0,me.length?me:void 0),he();return}P&&K(F.id,P),z(F.id,$),he()},[we,oe,ve,pe,re,le,z,K]);return r.jsxs(r.Fragment,{children:[r.jsx("input",{ref:Q,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:F=>{const $=G.current;$!=null&&ne($,F.target.files),F.target.value=""}}),e.map(F=>r.jsxs(s.Fragment,{children:[r.jsx(Aw,{slide:F,z:t[`slide:${F.id}`],selected:n.has(F.id)&&o.size===0,lod:i&&!(a!=null&&a.has(F.id)),glMode:l,thumbTick:u,docStreaming:c===F.id&&!!F.docHtml,docActive:!!F.docHtml&&(c===F.id||!d&&p===F.id),docWarmHold:h.has(F.id),restLive:m.has(F.id)||!!(a!=null&&a.has(F.id)),onDocBaked:g,onCardPointerDown:I,onHover:w,onHoverClear:D,onOpenSlide:R,onSnapshotChart:j}),F.status==="generating"&&!F.docHtml?r.jsx("div",{"data-gen-overlay":F.id,style:{position:"absolute",left:F.x,top:F.y,width:Ke,height:Je,pointerEvents:"none"},children:r.jsx(dd,{variant:S.has(F.id)?"redesigning":"generating",lightweight:A>1,onStop:()=>O(F.id)})}):c===F.id&&!F.docHtml?r.jsx("div",{"data-gen-overlay":F.id,style:{position:"absolute",left:F.x,top:F.y,width:Ke,height:Je,pointerEvents:"none"},children:r.jsx(dd,{variant:"editing"})}):null,L&&(p===F.id||n.has(F.id)&&o.size===0||F.status==="generating"||c===F.id)?(()=>{var He;const $=F.status==="generating"||c===F.id,P=F.status==="generating"?[{key:"stop",icon:"stop",label:"Stop generating",onClick:()=>O(F.id)}]:[],me=[{key:"present",icon:"play-large-fill",label:"Present this artifact",onClick:()=>ae(F.id)},{key:"export",icon:"file-text",label:"Export this artifact as a PDF",onClick:()=>void y(F.id),loading:f===F.id,loadingLabel:"Exporting"},{key:"duplicate",icon:"Copy",label:"Duplicate artifact",onClick:()=>J(F.id)},{key:"delete",icon:"delete-bin-6",label:"Delete artifact",onClick:()=>ce(F.id)}],he=[{key:"exclude",icon:F.excludedFromPresentation?"eye":"eye-off",label:F.excludedFromPresentation?"Include in presentation":"Exclude from presentation",onClick:()=>ge(F.id)},{key:"duplicate",icon:"Copy",label:"Duplicate slide",onClick:()=>J(F.id)},{key:"delete",icon:"delete-bin-6",label:"Delete slide",onClick:()=>ce(F.id)}],Me=!!F.docHtml;return r.jsx(go,{kind:"slide",id:F.id,x:F.x,y:F.y,title:Me?((He=F.docMeta)==null?void 0:He.title)||"Artifact":`Slide ${e.findIndex(Ee=>Ee.id===F.id)+1}`,busy:$,statusText:fe,onRename:Me?Ee=>k(F.id,Ee):void 0,actions:$?P:Me?me:he,onPointerEnter:x,onPointerLeave:D,onPointerDown:Ee=>I(F.id,Ee)})})():null,F.excludedFromPresentation?r.jsx("div",{"data-gen-overlay":F.id,style:{position:"absolute",left:F.x,top:F.y,width:Ke,height:Je,pointerEvents:"none"},children:r.jsx("div",{"aria-label":"Excluded from presentation",style:{position:"absolute",right:0,top:0,display:"flex",transform:"translateY(-100%) translateY(calc(-8px * var(--sel-scale, 1))) scale(var(--sel-scale, 1))",transformOrigin:"bottom right",color:"var(--color-icon-default-muted)"},children:r.jsx(At,{name:"eye-off",size:18})})}):null]},F.id)),T.length>0?[...new Set(T.map(F=>F.slideId))].map(F=>{const $=e.find(P=>P.id===F);return $?r.jsx("div",{"data-gen-overlay":F,style:{position:"absolute",left:$.x,top:$.y,width:Ke,height:Je,pointerEvents:"none",zIndex:1004,borderRadius:32,overflow:"hidden"},children:T.filter(P=>P.slideId===F).map(P=>r.jsx("div",{className:fv.flash,style:{left:P.rect.x,top:P.rect.y,width:P.rect.width,height:P.rect.height,borderRadius:P.rect.radius}},P.key))},`editflash${F}`):null}):null,r.jsx(xs,{kind:"slide",keyPrefix:"ports",items:e,hoveredId:p,selectedIds:n,suppressed:X!=null}),(()=>{if(X!=null||!L)return null;const F=n.size===1&&W===1?[...n][0]:null,$=F!=null?e.find(he=>he.id===F):null,P=$&&($.baked||$.docHtml)&&$.status!=="generating"?F:null,me=[];return p!=null&&me.push(p),P!=null&&P!==p&&me.push(P),me.length===0?null:me.map(he=>
31{const Me=e.find(Ee=>Ee.id===he);if(!Me||Me.status==="generating")return null;const He=H!==he;return r.jsx(Hx,{kind:"slide",id:Me.id,x:Me.x,y:Me.y,width:Ke,itemHeight:Je,actions:[],topSlot:He?r.jsx(dv,{value:we[Me.id]??"",onChange:Ee=>ve(qe=>({...qe,[Me.id]:Ee})),busy:c===he,statusText:fe,codeTail:ie,startedAt:Y,onSubmit:Ee=>de(Me,Ee),model:b,onModelChange:C,creativity:B[Me.id]??Ur,textDensity:M[Me.id]??Ro,onCreativity:Ee=>q(qe=>({...qe,[Me.id]:Ee})),onTextDensity:Ee=>ue(qe=>({...qe,[Me.id]:Ee})),attachments:oe[Me.id],onAddImages:()=>se(Me.id),onRemoveAttachment:Ee=>pe(qe=>({...qe,[Me.id]:(qe[Me.id]??[]).filter(Ae=>Ae.id!==Ee)})),designSystems:ye,activeDesignSystemId:ee,onSetActiveDesignSystem:U,onConcepts:()=>void _(Me.id),conceptsLoading:N&&Z===Me.id,conceptsOpen:Z===Me.id}):void 0},`bar${he}`)})})()]})}const pv="_revealing_nsfk1_15",mv={revealing:pv},gv=32;function xv({doc:e,z:t,selected:n,revealing:o,onPointerDown:i,onPointerEnter:a,onPointerLeave:l,onOpen:u,arriveIndex:c}){const d=Wd(e.content),p=s.useMemo(()=>{var g;const m=(g=e.title)==null?void 0:g.trim();return!m||/^\s*(#{1,6}\s|<h[1-3][\s>])/.test(e.content??"")?!1:m!==Bi(e.content)},[e.title,e.content]),h=c===void 0?null:Pd(e,c);return r.jsx("div",{"data-doc-id":e.id,className:h==null?void 0:h.className,onPointerDown:i,onPointerEnter:a,onPointerLeave:l,onDoubleClick:u,style:{...h==null?void 0:h.style,position:"absolute",left:e.x,top:e.y,width:e.width,height:e.height,background:"#ffffff",borderRadius:gv,zIndex:t,overflow:"hidden",contain:"layout style paint",contentVisibility:"auto",containIntrinsicSize:`${En}px ${Cn}px`,boxShadow:Io(n),transition:So},children:r.jsxs("div",{className:o?`${fo.docProse} ${mv.revealing}`:fo.docProse,style:{position:"relative",height:"100%",overflow:"hidden",paddingTop:Sr.padTop,paddingLeft:Sr.padX,paddingRight:Sr.padX,pointerEvents:"none",userSelect:"none",WebkitUserSelect:"none"},children:[p?r.jsx("h1",{className:fo.docCardTitle,children:e.title}):null,r.jsx(ea,{editor:d}),r.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0",style:{height:180,background:"linear-gradient(to bottom, rgba(255,255,255,0), #ffffff)"}})]})})}const yv="_bigger_sh84t_4",bv={bigger:yv},wv=32,vv=40;function kv({note:e,z:t,selected:n,onPointerDown:o,onPointerEnter:i,onPointerLeave:a,onContentChange:l,onHeightChange:u,onEditingChange:c}){const[d,p]=s.useState(!1),h=Xp(e.content,d?l:void 0),m=s.useRef(null),g=s.useRef(null),k=s.useRef(null),y=f=>{k.current=f??null,p(!0),c==null||c(!0)};return s.useEffect(()=>{var w;if(!d||!h)return;const f=k.current;k.current=null;const I=f?(w=h.view.posAtCoords({left:f.x,top:f.y}))==null?void 0:w.pos:void 0;h.commands.focus(I??"end")},[d,h]),s.useEffect(()=>{if(!d)return;const f=()=>{p(!1),c==null||c(!1)},I=window.setTimeout(()=>window.addEventListener("pointerdown",f),0);return()=>{window.clearTimeout(I),window.removeEventListener("pointerdown",f)}},[d]),s.useEffect(()=>{const f=m.current;if(!f)return;const I=()=>{const x=Math.ceil(f.scrollHeight),D=Math.max(e.width,x);Math.abs(D-e.height)>1&&u(D)};I();const w=new ResizeObserver(I);return w.observe(f),()=>w.disconnect()},[h,e.content,e.width,e.height,u]),r.jsx("div",{"data-note-id":e.id,onPointerDown:f=>{if(d){f.stopPropagation();return}g.current={x:f.clientX,y:f.clientY,wasSelected:n},o(f)},onPointerUp:f=>{if(d)return;const I=g.current;g.current=null,I&&I.wasSelected&&Math.abs(f.clientX-I.x)+Math.abs(f.clientY-I.y)<=3&&y({x:f.clientX,y:f.clientY})},onPointerEnter:i,onPointerLeave:a,onDoubleClick:f=>{d||y({x:f.clientX,y:f.clientY})},style:{position:"absolute",left:e.x,top:e.y,width:e.width,height:e.height,borderRadius:wv,backgroundColor:$u(e.color),zIndex:t,overflow:"hidden",cursor:"pointer",boxShadow:Io(n),transition:`${So}, background-color 160ms ease`},children:r.jsx("div",{ref:m,className:`${Yp.noteProse} ${bv.bigger}`,style:{position:"relative",padding:vv,pointerEvents:d?"auto":"none",userSelect:d?"text":"none",WebkitUserSelect:d?"text":"none"},onPointerDown:f=>{d&&f.stopPropagation()},children:r.jsx(ea,{editor:h})})})}function Sv({color:e,onPick:t}){const[n,o]=s.useState(!1);return r.jsx(ur,{content:"Note color",side:"top",sideOffset:12,className:"z-[1500]",children:r.jsxs("div",{className:"relative",children:[r.jsx(st,{variant:"ghost",size:"icon-sm","aria-label":"Note color",onClick:i=>{i.stopPropagation(),o(a=>!a)},children:r.jsx("span",{className:"block h-[18px] w-[18px] rounded-full",style:{background:$u(e),boxShadow:"inset 0 0 0 1px rgba(0,0,0,0.12)"}})}),n?r.jsx("div",{className:"absolute left-1/2 top-full z-[1600] mt-[var(--spacing-6)] flex w-max -translate-x-1/2 items-center gap-[var(--spacing-6)] rounded-[18px] border border-[var(--color-border-default)] bg-[var(--color-default)] p-[var(--spacing-6)] shadow-[var(--shadow-modal-md)]",children:Au.map(i=>{const a=i.key===(e??"default");return r.jsx("button",{type:"button",title:i.label,"aria-label":i.label,onClick:l=>{l.stopPropagation(),t(i.key)},className:"relative h-[18px] w-[18px] shrink-0 rounded-full transition-transform hover:scale-110",style:{background:i.fill,boxShadow:a?"0 0 0 1.5px var(--color-default), 0 0 0 3px var(--color-text-default)":"inset 0 0 0 1px rgba(0,0,0,0.10)"}},i.key)})}):null]})})}const Pu=32,Iv="#8b5cf6";function Cv({value:e,height:t,visible:n,onCommit:o}){const i=s.useRef(null),[a,l]=s.useState(null),u=a??e,c=100-u,d=n||a!=null,p=Math.round(Math.max(13,t*.085)),h=Math.round(Math.max(9,t*.04)),m=f=>{const I=i.current;if(!I)return u;const w=I.getBoundingClientRect(),x=1-(f-w.top)/w.height;return Math.round(Math.max(0,Math.min(1,x))*100)},g=f=>{var I,w;f.stopPropagation(),f.preventDefault(),(w=(I=f.target).setPointerCapture)==null||w.call(I,f.pointerId),l(m(f.clientY))},k=f=>{a!=null&&(f.stopPropagation(),l(m(f.clientY)))},y=f=>{var w,x;if(a==null)return;f.stopPropagation(),(x=(w=f.target).releasePointerCapture)==null||x.call(w,f.pointerId);const I=m(f.clientY);l(null),I!==e&&o(I)};return r.jsxs("div",{className:"pointer-events-none absolute inset-0 overflow-hidden",style:{borderRadius:Pu},children:[c>0&&r.jsx("div",{className:"absolute inset-x-0 top-0",style:{height:`${c}%`,background:"rgba(250,250,250,0.6)",backdropFilter:"saturate(0.7) brightness(1.05)",borderBottom:"1px solid rgba(9,9,11,0.14)"}}),(d||u<100)&&r.jsx("div",{className:"absolute inset-0 flex items-end justify-end",style:{padding:Math.round(t*.05)},children:r.jsxs("span",{className:"inline-flex items-center justify-center font-semibold tabular-nums text-[var(--color-text-default)]",style:{fontSize:p,lineHeight:1,padding:"0.28em 0.5em",borderRadius:999,background:"#ffffff",boxShadow:"0 1px 6px rgba(9,9,11,0.16)"},children:[u,"%"]})}),d&&r.jsx("div",{ref:i,onPointerDown:g,onPointerMove:k,onPointerUp:y,className:"pointer-events-auto absolute cursor-ns-resize overflow-hidden rounded-full",style:{left:h,top:"5%",height:"90%",width:h,background:"rgba(255,255,255,0.2)",boxShadow:"0 1px 6px rgba(9,9,11,0.2)",touchAction:"none"},children:r.jsx("div",{className:"absolute inset-x-0 bottom-0",style:{height:`${u}%`,background:Iv}})})]})}function Ev({image:e,z:t,selected:n,styleWired:o,styleStrength:i,showStyleChrome:a,lod:l=!1,lodFill:u,onStyleStrengthCommit:c,onPointerDown:d,onPointerEnter:p,onPointerLeave:h,onOpen:m,arriveIndex:g}){const[k,y]=s.useState(null),f=k===e.src,I=g===void 0?null:Pd(e,g);return r.jsxs("div",{"data-image-id":e.id,className:I==null?void 0:I.className,onPointerDown:d,onPointerEnter:p,onPointerLeave:h,onDoubleClick:w=>{w.stopPropagation(),m()},style:{...I==null?void 0:I.style,position:"absolute",left:e.x,top:e.y,width:e.width,height:e.height,borderRadius:Pu,background:l?u??"#ececef":"#ffffff",zIndex:t,overflow:"hidden",cursor:"pointer",boxShadow:Io(n),transition:So},children:[l?null:r.jsxs(r.Fragment,{children:[f?null:r.jsx("div",{className:hr.shimmer,style:{position:"absolute",inset:0,pointerEvents:"none"},"aria-hidden":!0}),r.jsx("img",{src:e.src,alt:"",draggable:!1,decoding:"async",onLoad:()=>y(e.src),onError:()=>y(e.src),style:{display:"block",width:"100%",height:"100%",objectFit:"cover",pointerEvents:"none",userSelect:"none"}})]}),o&&!l?r.jsx(Cv,{value:i,height:e.height,visible:a,onCommit:c}):null,null]})}function Rv(e){if(!e||e.startsWith("data:"))return"";const t=e.split("?")[0].split("/").pop()??"",n=t.lastIndexOf(".");return decodeURIComponent(n>0?t.slice(0,n):t)}function Mv(){const{demoChrome:e,store:t,chromeVisible:n,deleteDoc:o,deleteImage:i,deleteNote:a,docs:l,duplicateDoc:u,duplicateImage:c,duplicateNote:d,farNext:p,glActive:h,hiddenMemberKeys:m,hover:g,hoverKeep:k,hoverClearSoon:y,hoveredDocId:f,hoveredImageId:I,hoveredNoteId:w,images:x,lod:D,notes:R,onDocPointerDown:j,onImagePointerDown:S,onNotePointerDown:A,openDoc:O,openDocId:T,revealingDocIds:X,selectedDocIds:L,selectedGroupIds:W,selectedImageIds:H,selectedNoteIds:ae,setImageStyleStrength:ge,setViewerImageId:J,singleSelection:ce,startImageResize:we,updateNoteColor:ve,renameDoc:oe,renameImage:pe,updateNoteContent:K,updateNoteHeight:fe,wires:ie,worldRef:Y,zOrder:re}=Rn(),{clearSelection:le}=t;return r.jsxs(r.Fragment,{children:[x.filter(b=>!m.has(Ye("image",b.id))).map(b=>{var B;const C=ie.filter(M=>M.from.kind==="image"&&M.from.id===b.id&&M.mode==="style"),z=h&&p&&D;return r.jsx(Ev,{image:b,arriveIndex:e?x.indexOf(b):void 0,z:re[`image:${b.id}`],selected:H.has(b.id)&&W.size===0,styleWired:C.length>0,styleStrength:((B=C[0])==null?void 0:B.styleStrength)??100,showStyleChrome:I===b.id||H.has(b.id),lod:z,lodFill:z?xp(Id(b.src)):void 0,onStyleStrengthCommit:M=>ge(b.id,M),onPointerDown:M=>S(b.id,M),onPointerEnter:()=>g("image",b.id),onPointerLeave:y,onOpen:()=>J(b.id)},b.id)}),e?null:r.jsx(xs,{kind:"image",keyPrefix:"imageports",items:x,hoveredId:I,selectedIds:H}),(()=>{var z;if(!n)return null;const b=I??(ce&&H.size===1?[...H][0]:null);if(b==null)return null;const C=x.find(B=>B.id===b);return C?r.jsx(go,{kind:"image",id:C.id,x:C.x,y:C.y,title:((z=C.label)==null?void 0:z.trim())||Rv(C.src
31)||"Image",onRename:B=>pe(C.id,B),actions:[{key:"duplicate",icon:"Copy",label:"Duplicate image",onClick:()=>c(C.id)},{key:"delete",icon:"delete-bin-6",label:"Delete image",onClick:()=>i(C.id)}],onPointerEnter:k,onPointerLeave:y,onPointerDown:B=>S(C.id,B)}):null})(),(()=>{if(!ce||H.size!==1||!n)return null;const b=[...H][0],C=x.find(z=>z.id===b);return C?r.jsx(Wx,{x:C.x,y:C.y,w:C.width,h:C.height,portsFor:`image:${b}`,onHandleDown:(z,B)=>we(b,z,B)},`imgresize${b}`):null})(),l.filter(b=>!m.has(Ye("doc",b.id))).map(b=>r.jsxs(s.Fragment,{children:[r.jsx(xv,{doc:b,arriveIndex:e?0:void 0,z:re[`doc:${b.id}`],selected:L.has(b.id)&&W.size===0,revealing:X.has(b.id),onPointerDown:C=>j(b.id,C),onPointerEnter:()=>g("doc",b.id),onPointerLeave:y,onOpen:()=>{var C;return O(b.id,(C=Y.current)==null?void 0:C.querySelector(`[data-doc-id="${b.id}"]`))}}),X.has(b.id)?r.jsx("div",{style:{position:"absolute",left:b.x,top:b.y,width:b.width,height:b.height,pointerEvents:"none"},children:r.jsx("div",{className:Pn.shimmer,"aria-hidden":!0})}):null]},b.id)),e?null:r.jsx(xs,{kind:"doc",keyPrefix:"docports",items:l,hoveredId:f,selectedIds:L,suppressed:T!=null}),(()=>{var C;if(f==null||T!=null||!n)return null;const b=l.find(z=>z.id===f);return b?r.jsx(go,{kind:"doc",id:b.id,x:b.x,y:b.y,title:((C=b.title)==null?void 0:C.trim())||"Document",onRename:z=>oe(b.id,z),actions:[{key:"duplicate",icon:"Copy",label:"Duplicate document",onClick:()=>u(b.id)},{key:"delete",icon:"delete-bin-6",label:"Delete document",onClick:()=>o(b.id)}],onPointerEnter:k,onPointerLeave:y,onPointerDown:z=>j(b.id,z)}):null})(),R.filter(b=>!m.has(Ye("note",b.id))).map(b=>r.jsx(kv,{note:b,z:re[`note:${b.id}`],selected:ae.has(b.id)&&W.size===0,onPointerDown:C=>A(b.id,C),onPointerEnter:()=>g("note",b.id),onPointerLeave:y,onContentChange:C=>K(b.id,C),onHeightChange:C=>fe(b.id,C),onEditingChange:C=>{C&&le()}},b.id)),e?null:r.jsx(xs,{kind:"note",keyPrefix:"noteports",items:R,hoveredId:w,selectedIds:ae}),(()=>{if(w==null||!n)return null;const b=R.find(C=>C.id===w);return b?r.jsx(go,{kind:"note",id:b.id,x:b.x,y:b.y,extraLeading:r.jsx(Sv,{color:b.color,onPick:C=>ve(b.id,C)},`color${b.id}`),actions:[{key:"duplicate",icon:"Copy",label:"Duplicate note",onClick:()=>d(b.id)},{key:"delete",icon:"delete-bin-6",label:"Delete note",onClick:()=>a(b.id)}],onPointerEnter:k,onPointerLeave:y,onPointerDown:C=>A(b.id,C)}):null})()]})}const ud=320,Ni=8;function jv({deckId:e,groupId:t,anchorRef:n,onFlush:o,onClose:i}){const{showToast:a}=Qi(),[l,u]=s.useState({phase:"loading"}),[c,d]=s.useState(!1),[p,h]=s.useState(!1),[m,g]=s.useState(null),k=s.useRef(null);s.useEffect(()=>()=>{k.current&&clearTimeout(k.current)},[]);const y=x=>`${window.location.origin}/birtvy/public/${x}`;s.useLayoutEffect(()=>{const x=n.current;if(!x)return;const D=x.getBoundingClientRect(),R=ud/2,j=Math.min(Math.max(D.left+D.width/2,R+Ni),window.innerWidth-R-Ni);g({top:D.bottom+Ni,left:j})},[n]),s.useEffect(()=>{const x=R=>{var A;const j=R.target;if((A=n.current)!=null&&A.contains(j))return;const S=document.getElementById("birtvy-share-menu");S!=null&&S.contains(j)||i()},D=R=>{R.key==="Escape"&&i()};return document.addEventListener("pointerdown",x),document.addEventListener("keydown",D),()=>{document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",D)}},[n,i]),s.useEffect(()=>{if(!e){u({phase:"private"});return}let x=!1;return(async()=>{try{const D=await kg(e,t);if(x)return;u(D?{phase:"public",url:y(D)}:{phase:"private"})}catch{x||u({phase:"private"})}})(),()=>{x=!0}},[e,t]);const f=s.useCallback(async(x,D=!0)=>{try{await navigator.clipboard.writeText(x),h(!0),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>h(!1),1500),D&&a({title:"Share link copied to clipboard",variant:"success"})}catch{a({title:"Could not copy the link",variant:"error"})}},[a]),I=s.useCallback(async()=>{if(!e){a({title:"Give the deck a moment to save, then try sharing",variant:"error"});return}if(!c){d(!0);try{await o();const x=await Sg(e,t),D=y(x);u({phase:"public",url:D}),await f(D)}catch(x){console.error("birtvy: failed to create share link:",x),a({title:"Could not create a share link",variant:"error"})}finally{d(!1)}}},[e,t,c,o,f,a]),w=s.useCallback(async()=>
31{if(!(!e||c)){d(!0);try{await Ig(e,t),u({phase:"private"}),a({title:"Link disabled â this group is private again",variant:"success"})}catch(x){console.error("birtvy: failed to disable share link:",x),a({title:"Could not disable the link",variant:"error"})}finally{d(!1)}}},[e,t,c,a]);return m==null?null:Mo.createPortal(r.jsxs("div",{id:"birtvy-share-menu",role:"dialog","aria-label":"Share presentation",onPointerDown:x=>x.stopPropagation(),style:{position:"fixed",top:m.top,left:m.left,transform:"translateX(-50%)",width:ud,zIndex:2e3},className:"flex flex-col gap-[var(--spacing-8)] rounded-[16px] border border-[var(--color-border-default)] bg-[var(--color-default)] p-[var(--spacing-12)] shadow-[var(--shadow-modal-md)]",children:[r.jsx("div",{className:"text-base font-semibold text-[var(--color-text-default)]",children:"Share presentation"}),l.phase==="loading"&&r.jsx("div",{className:"text-sm text-[var(--color-text-subtle)]",children:"Loadingâ¦"}),l.phase==="private"&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"text-sm text-[var(--color-text-subtle)]",children:"Only you can see this. Create a link anyone can open."}),r.jsx(st,{variant:"default",size:"sm",leadIcon:"link",loading:c,onClick:I,children:"Create public link"})]}),l.phase==="public"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex items-center gap-[var(--spacing-6)] text-sm text-[var(--color-text-subtle)]",children:[r.jsx("span",{"aria-hidden":!0,children:"ð"}),r.jsx("span",{children:"Anyone with the link can view"})]}),r.jsxs("div",{className:"flex items-center gap-[var(--spacing-6)]",children:[r.jsx("input",{className:"min-w-0 flex-1 rounded-[10px] border border-[var(--color-border-default)] bg-[var(--color-subtle)] px-[var(--spacing-8)] py-[var(--spacing-6)] text-sm text-[var(--color-text-default)] outline-none",value:l.url,readOnly:!0,onFocus:x=>x.currentTarget.select()}),r.jsx(st,{variant:"default",size:"sm",leadIcon:p?"check-line":"file-copy-line",onClick:()=>f(l.url),children:p?"Copied":"Copy"})]}),r.jsx("button",{type:"button",className:"self-start text-sm text-[var(--color-text-subtle)] underline-offset-2 hover:underline disabled:opacity-50",disabled:c,onClick:w,children:"Make private"})]})]}),document.body)}const Lu="text-[var(--color-icon-default-subtle)]",fd=16,hd=12,Nv=[{handle:"topLeft",ux:0,uy:0,cursor:"nwse-resize",corner:!0},{handle:"topRight",ux:1,uy:0,cursor:"nesw-resize",corner:!0},{handle:"bottomLeft",ux:0,uy:1,cursor:"nesw-resize",corner:!0},{handle:"bottomRight",ux:1,uy:1,cursor:"nwse-resize",corner:!0},{handle:"top",ux:.5,uy:0,cursor:"ns-resize",corner:!1},{handle:"bottom",ux:.5,uy:1,cursor:"ns-resize",corner:!1},{handle:"left",ux:0,uy:.5,cursor:"ew-resize",corner:!1},{handle:"right",ux:1,uy:.5,cursor:"ew-resize",corner:!1}];function Hn({icon:e,label:t,onClick:n,refEl:o,active:i,disabled:a,loading:l,loadingLabel:u}){const c=!!(l&&u);return r.jsx("div",{ref:o,className:ln.chip,onPointerDown:d=>d.stopPropagation(),children:r.jsx(st,{variant:"soft",size:c?"xs":"icon-xs",leadIcon:r.jsx(At,{name:e,size:"button-xs",className:i?"text-[var(--color-state-primary)]":Lu}),"aria-label":c?u:t,"aria-pressed":i,title:c?void 0:t,disabled:a,loading:l,onClick:d=>{d.stopPropagation(),n()},children:c?u:null})})}function Dv({view:e,revealed:t,selected:n,deckId:o,onHeaderPointerDown:i,onRename:a,onArrange:l,onToggleCollapse:u,onDuplicate:c,onDelete:d,onResize:p,onOpenSlide:h,onPresent:m,onExport:g,onFlush:k,exporting:y,cols:f,maxCols:I,onSetCols:w,snap:x,onToggleSnap:D,getZoom:R}){const[j,S]=s.useState(!1),[A,O]=s.useState(!1),T=e.isParent||e.slidesOnly||e.parentId==null&&e.memberRects.some(M=>M.kind!=="slide"),X=s.useRef(null),L=s.useRef(null),W=s.useRef(null),[H,ae]=s.useState(!1),[ge,J]=s.useState(e.title),ce=s.useRef(null),[we,ve]=s.useState(null),oe=s.useRef(null),pe=s.useRef(null);s.useEffect(()=>{H||J(e.title)},[e.title,H]),s.useEffect(()=>{var M,q;H&&((M=ce.current)==null||M.focus(),(q=ce.current)==null||q.select())},[H]);const K=()=>{a(ge.trim()||"Group"),ae(!1)},fe=t||n||j||A,ie={opacity:fe?1:0,transition:"opacity 0.15s ease"},Y=we&&!e.collapsed?Jc(e.frame,e.contentBounds,we.handle,we.dx,we.dy):e.frame,re=M=>q=>{var ue,ye;q.button===0&&(q.stopPropagation(),q.preventDefault(),oe.current={handle:M,startX:q.clientX,startY:q.clientY},ve({handle:M,dx:0,dy:0}),(ye=(ue=q.currentTarget).setPointerCapture)==null||ye.call(ue,q.pointerId))},le=M=>{const q=oe.current;if(!q)return;const ue=Math.max(R(),.01);ve({handle:q.handle,dx:(M.clientX-q.startX)/ue,dy:(M.clientY-q.startY)/ue})},b=M=>{var ue,ye;const q=oe.current;if(oe.current=null,(ye=(ue=M.currentTarget).releasePointerCapture)==null||ye.call(ue,M.pointerId),q){const ee=Math.max(R(),.01);p(Jc(e.frame,e.contentBounds,q.handle,(M.clientX-q.startX)/ee,(M.clientY-q.startY)/ee))}ve(null)},C=M=>q=>{var ue,ye;q.button===0&&(q.stopPropagation(),pe.current={startX:q.clientX,startY:q.clientY,started:!1,slideId:M},(ye=(ue=q.target).setPointerCapture)==null||ye.call(ue,q.pointerId))},z=M=>{const q=pe.current;!q||q.started||Math.abs(M.clientX-q.startX)+Math.abs(M.clientY-q.startY)>2&&(q.started=!0,i(M))},B=M=>{var ue,ye;const q=pe.current;pe.current=null,(ye=(ue=M.target).releasePointerCapture)==null||ye.call(ue,M.pointerId),q&&!q.started&&h(q.slideId)};return r.jsxs(r.Fragment,{children:[r.jsx("div",{"data-group-frame":e.id,className:ln.frame,style:{left:Y.x,top:Y.y,width:Y.width,height:Y.height,boxShadow:n?"0 0 0 calc(2px * var(--sel-scale, 1)) var(--color-state-primary)":void 0,...ie}}
31),n&&!e.collapsed?r.jsx("div",{"data-group-frame":e.id,style:{position:"absolute",left:Y.x,top:Y.y,width:Y.width,height:Y.height,zIndex:1052,pointerEvents:"none"},children:[...Nv].sort((M,q)=>Number(M.corner)-Number(q.corner)).map(({handle:M,ux:q,uy:ue,cursor:ye,corner:ee})=>{const U={position:"absolute",left:`${q*100}%`,top:`${ue*100}%`,cursor:ye,pointerEvents:"auto",touchAction:"none"},_=ee?{...U,width:`calc(${fd}px * var(--sel-scale, 1))`,height:`calc(${fd}px * var(--sel-scale, 1))`,transform:"translate(-50%, -50%)"}:M==="top"||M==="bottom"?{...U,left:0,width:"100%",height:`calc(${hd}px * var(--sel-scale, 1))`,transform:"translateY(-50%)"}:{...U,top:0,height:"100%",width:`calc(${hd}px * var(--sel-scale, 1))`,transform:"translateX(-50%)"};return r.jsx("div",{style:_,onPointerDown:re(M),onPointerMove:le,onPointerUp:b},M)})}):null,r.jsx("div",{"data-group-frame":e.id,className:ln.barAnchor,style:{left:Y.x,top:Y.y,zIndex:1050,...ie,pointerEvents:fe?void 0:"none"},children:r.jsxs("div",{className:ln.bar,children:[r.jsxs("div",{className:ln.labelPill,onPointerDown:i,children:[H?r.jsx("input",{ref:ce,className:ln.titleInput,value:ge,onChange:M=>J(M.target.value),onPointerDown:M=>M.stopPropagation(),onBlur:K,onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),K()):M.key==="Escape"&&(M.preventDefault(),J(e.title),ae(!1))},"aria-label":"Group name"}):r.jsx("span",{className:ln.title,onDoubleClick:M=>{M.stopPropagation(),ae(!0)},children:e.title}),r.jsx("span",{className:"ml-[var(--spacing-6)] text-xs text-[var(--color-text-subtle)]",children:e.memberCount})]}),r.jsxs("div",{ref:X,className:ln.actions,children:[e.isParent||e.slidesOnly?r.jsxs(r.Fragment,{children:[r.jsx(Hn,{refEl:L,icon:"share-2",label:"Share a public link to this group",onClick:()=>S(M=>!M)}),r.jsx(Hn,{icon:"file-text",label:"Export this group as a PDF",onClick:g,disabled:y,loading:y,loadingLabel:"Exporting"}),r.jsx(Hn,{icon:"play-large-fill",label:"Present this group",onClick:m})]}):null,T?r.jsx(Hn,{refEl:W,icon:"grid",label:e.isParent?"Deck layout â slides per row":"Grid layout â items per row",onClick:()=>O(M=>!M)}):r.jsx(Hn,{icon:"grid",label:"Arrange into a grid",onClick:l}),r.jsx(Hn,{icon:"attachment-2",active:x,label:x?e.isParent?"Snap on â slides keep their rows":e.slidesOnly?"Snap on â slides keep their grid slots":"Snap on â members snap into the arrangement":e.isParent||e.slidesOnly?"Snap off â slides move freely":"Snap off â members move freely",onClick:D}),!e.isParent&&!e.slidesOnly?r.jsx(r.Fragment,{children:e.canCollapse?r.jsx(Hn,{icon:e.collapsed?"unfold":"fold",label:e.collapsed?"Expand group":"Collapse group",onClick:u}):null}):null,r.jsx(Hn,{icon:"Copy",label:"Duplicate group",onClick:c}),r.jsx(Hn,{icon:"delete-bin-6",label:"Delete group and its contents",onClick:d})]})]})}),e.collapsed?e.members.map(M=>r.jsx("div",{"data-group-frame":e.id,className:"absolute cursor-grab",style:{left:M.x,top:M.y,width:Ke,height:Je,zIndex:1049},onPointerDown:C(M.id),onPointerMove:z,onPointerUp:B},`collapsed-slide-${M.id}`)):null,e.collapsed&&!fe?r.jsx("div",{"data-group-frame":e.id,className:ln.barAnchor,style:{left:Y.x,top:Y.y,zIndex:1050},children:r.jsx("div",{className:ln.bar,children:r.jsxs(st,{variant:"soft",size:"xs",leadIcon:r.jsx(At,{name:"unfold",size:"button-xs",className:Lu}),"aria-label":"Expand group",title:"Expand group",onClick:M=>{M.stopPropagation(),u()},children:[e.hiddenCount," hidden"]})})}):null,j?r.jsx(jv,{deckId:o,groupId:String(e.id),anchorRef:L,onFlush:k,onClose:()=>S(!1)}):null,A?r.jsx(Tv,{anchorRef:X,keepRef:W,cols:f,maxCols:I,onSetCols:w,onClose:()=>O(!1)}):null]})}function Tv({anchorRef:e,keepRef:t,cols:n,maxCols:o,onSetCols:i,onClose:a}){const[l,u]=s.useState(null),c=Math.max(1,o),d=Math.min(Math.max(1,n),c);return s.useEffect(()=>{let p=0,h=null;const m=()=>{const g=e.current;if(g){const k=g.getBoundingClientRect(),y={top:k.bottom+8,left:Math.max(8,Math.min(k.left,window.innerWidth-240-8))};(!h||h.top!==y.top||h.left!==y.left)&&(h=y,u(y))}p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[e]),s.useEffect(()=>{const p=m=>{var k,y;const g=m.target;(k=t.current)!=null&&k.contains(g)||(y=document.getElementById("birtvy-group-layout"))!=null&&y.contains(g)||a()},h=m=>{m.key==="Escape"&&a()};return document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",h),()=>{document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",h)}},[t,a]),l==null?null:Mo.createPortal(r.jsx("div",{id:"birtvy-group-layout",role:"dialog","aria-label":"Grid layout",onPointerDown:p=>
31p.stopPropagation(),style:{position:"fixed",top:l.top,left:l.left,width:240,zIndex:2e3},className:"rounded-[16px] border border-[var(--color-border-default)] bg-[var(--color-default)] p-[var(--spacing-8)] shadow-[var(--shadow-modal-md)]",children:r.jsx(Ir,{mode:"continuous",min:1,max:c,value:d,onChange:i,size:"md",label:"Items per row",ariaLabel:"Items per row"})}),document.body)}const Av=320,$v=180,pd=320,Pv=` 32attribute vec2 a_pos; // world units 33attribute vec2 a_uv; // atlas uv (0..1) 34uniform vec2 u_res; // viewport, css px 35uniform vec2 u_pan; // camera pan, css px 36uniform float u_zoom; 37varying vec2 v_uv; 38void main() { 39 vec2 screen = a_pos * u_zoom + u_pan; 40 vec2 clip = (screen / u_res) * 2.0 - 1.0; 41 gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0); 42 v_uv = a_uv; 43}`,Lv=` 44precision mediump float; 45varying vec2 v_uv; 46uniform sampler2D u_tex; 47void main() { gl_FragColor = texture2D(u_tex, v_uv); }`;function zv(e,t,n){const o=e.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,antialias:!1});if(!o)return null;const i=(L,W)=>{const H=o.createShader(L);if(o.shaderSource(H,W),o.compileShader(H),!o.getShaderParameter(H,o.COMPILE_STATUS))throw new Error(o.getShaderInfoLog(H)||"shader compile");return H};let a;try{if(a=o.createProgram(),o.attachShader(a,i(o.VERTEX_SHADER,Pv)),o.attachShader(a,i(o.FRAGMENT_SHADER,Lv)),o.linkProgram(a),!o.getProgramParameter(a,o.LINK_STATUS))throw new Error(o.getProgramInfoLog(a)||"link")}catch(L){return console.warn("birtvy gl-thumbs: shader failed",L),null}const l=o.getAttribLocation(a,"a_pos"),u=o.getAttribLocation(a,"a_uv"),c={res:o.getUniformLocation(a,"u_res"),pan:o.getUniformLocation(a,"u_pan"),zoom:o.getUniformLocation(a,"u_zoom"),tex:o.getUniformLocation(a,"u_tex")},d=o.createBuffer(),p=o.createTexture(),h=document.createElement("canvas"),m=h.getContext("2d");let g=0,k=null,y=[],f=[],I=null,w=1,x=1;const D=L=>
47L.kind==="image"?Id(L.src):_n("b",L.html),R=(L,W)=>L.kind==="image"?yp(W,L.src,pd):Fr(W,L.html,pd,L.doc?{doc:!0}:void 0),j=(L,W)=>{const H=new Map,ae=new Set,ge=new Set,J=new Set;let ce=!1;for(const ie of L){const Y=D(ie);if(ae.add(Y),ie.kind==="image"?ce=!0:ge.add(Y),H.has(Y)){ie.kind!=="image"&&J.add(Y);continue}const re=R(ie,Y);re&&(H.set(Y,re),ie.kind!=="image"&&J.add(Y))}const we=H.size;if(we===0)return g=0,k=null,y=[],{allReady:ae.size===0,vertCount:0,ready:0,total:ge.size};const ve=o.getParameter(o.MAX_TEXTURE_SIZE)||4096,oe=n.current*100>=8,pe=oe?512:Av,K=oe?288:$v,fe=new Map;if(ce){const ie=new Map;for(const[re,le]of H){const b=Math.min(pe/Math.max(le.width,le.height),1),C=ge.has(re);ie.set(re,{w:C?pe:Math.max(16,Math.round(le.width*b)),h:C?K:Math.max(16,Math.round(le.height*b))})}let Y=1;for(let re=0;re<4;re++){fe.clear();let le=0,b=0;for(const{w:ee,h:U}of ie.values())le+=Math.ceil(ee*Y)*Math.ceil(U*Y),b=Math.max(b,Math.ceil(ee*Y));const C=Math.min(ve,Math.max(b,Math.ceil(Math.sqrt(le/.8)))),z=[...ie.entries()].sort((ee,U)=>U[1].h-ee[1].h||U[1].w-ee[1].w);let B=0,M=0,q=0,ue=0;for(const[ee,U]of z){const _=Math.max(8,Math.ceil(U.w*Y)),N=Math.max(8,Math.ceil(U.h*Y));B+_>C&&B>0&&(M+=q,B=0,q=0),fe.set(ee,{x:B,y:M,w:_,h:N}),B+=_,q=Math.max(q,N),ue=Math.max(ue,B)}const ye=M+q;if(ue<=ve&&ye<=ve||re===3){h.width=Math.max(1,Math.min(ue,ve)),h.height=Math.max(1,Math.min(ye,ve));break}Y*=Math.min(ve/ue,ve/ye)*.98}m.clearRect(0,0,h.width,h.height)}else{const ie=Math.ceil(Math.sqrt(we)),Y=Math.ceil(we/ie),re=Math.min(1,ve/(ie*pe),ve/(Y*K)),le=Math.max(32,Math.floor(pe*re)),b=Math.max(18,Math.floor(K*re));h.width=ie*le,h.height=Y*b,m.clearRect(0,0,h.width,h.height);let C=0;for(const[z]of H)fe.set(z,{x:C%ie*le,y:Math.floor(C/ie)*b,w:le,h:b}),C++}for(const[ie,Y]of H){const re=fe.get(ie);re&&(ge.has(ie)?(m.save(),m.beginPath(),m.rect(re.x,re.y,re.w,re.h),m.clip(),m.drawImage(Y,0,0,Y.width,Y.height,re.x,re.y,re.w,re.h),m.globalCompositeOperation="destination-in",m.beginPath(),m.roundRect(re.x+.5,re.y+.5,re.w-1,re.h-1,re.w*(32/1920)+1.25),m.fill(),m.restore()):m.drawImage(Y,0,0,Y.width,Y.height,re.x,re.y,re.w,re.h))}o.bindTexture(o.TEXTURE_2D,p),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1);try{o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,h)}catch(ie){return console.warn("birtvy gl-thumbs: atlas upload failed (tainted capture?) â far view falls back to DOM",ie),h.width=h.width,g=0,k=null,I=null,y=L.map(()=>({start:0,count:0})),{allReady:!0,vertCount:0,ready:J.size,total:ge.size}}return o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),f=L,I=fe,w=h.width,x=h.height,S(L,fe,h.width,h.height,W),{allReady:we===ae.size,vertCount:g,ready:J.size,total:ge.size}},S=(L,W,H,ae,ge)=>{const J=new Float32Array(L.length*6*4);let ce=0;const we=(ve,oe,pe,K)=>{J[ce++]=ve,J[ce++]=oe,J[ce++]=pe,J[ce++]=K};y=[];for(let ve=0;ve<L.length;ve++){const oe=L[ve],pe=ge!=null&&ge.has(ve)?void 0:W.get(D(oe));if(pe===void 0){y.push({start:ce,count:0});continue}y.push({start:ce,count:24});const K=(pe.x+.5)/H,fe=(pe.y+.5)/ae,ie=(pe.x+pe.w-.5)/H,Y=(pe.y+pe.h-.5)/ae,re=oe.x,le=oe.y,b=oe.x+oe.w,C=oe.y+oe.h;we(re,le,K,fe),we(b,le,ie,fe),we(re,C,K,Y),we(b,le,ie,fe),we(b,C,ie,Y),we(re,C,K,Y)}g=ce/4,k=J.slice(0,ce),o.bindBuffer(o.ARRAY_BUFFER,d),o.bufferData(o.ARRAY_BUFFER,k,o.DYNAMIC_DRAW)},A=L=>{I&&S(f,I,w,x,L)},O=L=>{if(!k||L.size===0)return;const W=k.slice();for(const[H,ae]of L){const ge=y[H];if(!(!ge||ge.count===0))for(let J=ge.start;J<ge.start+ge.count;J+=4)W[J]+=ae.dx,W[J+1]+=ae.dy}o.bindBuffer(o.ARRAY_BUFFER,d),o.bufferData(o.ARRAY_BUFFER,W,o.DYNAMIC_DRAW)},T=()=>{const L=Math.min(typeof window<"u"&&window.devicePixelRatio||1,2),W=Math.max(1,Math.round(window.innerWidth*L)),H=Math.max(1,Math.round(window.innerHeight*L));(e.width!==W||e.height!==H)&&(e.width=W,e.height=H),o.viewport(0,0,e.width,e.height)},X=()=>{if(T(),o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT),!g)return;const L=window.innerWidth,W=window.innerHeight;o.useProgram(a),o.bindBuffer(o.ARRAY_BUFFER,d),o.enableVertexAttribArray(l),o.vertexAttribPointer(l,2,o.FLOAT,!1,16,0),o.enableVertexAttribArray(u),o.vertexAttribPointer(u,2,o.FLOAT,!1,16,8),o.uniform2f(c.res,L,W),o.uniform2f(c.pan,t.current.x,t.current.y),o.uniform1f(c.zoom,n.current),o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,p),o.uniform1i(c.tex,0),o.enable(o.BLEND),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.drawArrays(o.TRIANGLES,0,g)};return T(),{rebuild:j,applySkip:A,offsetQuads:O,draw:X,resize:T,dispose:()=>{o.deleteBuffer(d),o.deleteTexture(p),o.deleteProgram(a)}}}function _v({active:e,quads:t,skip:n,panRef:o,zoomRef:i,thumbTick:a,drawRef:l,dragRef:u,onProgress:c}){const d=s.useRef(null),p=s.useRef(null),h=s.useRef(e);h.current=e;const m=s.useRef(n);m.current=n;const[g,k]=s.useState(0);return s.useEffect(()=>{const y=d.current;if(!y)return;let f=!1;const I=()=>{var j;(j=p.current)==null||j.dispose();const R=zv(y,o,i);if(p.current=R,!R){console.warn("birtvy: WebGL unavailable â far view shows slide background colors only");return}l.current=()=>{var S;h.current&&((S=p.current)==null||S.draw())},u&&(u.current=S=>{var A,O;h.current&&((A=p.current)==null||A.offsetQuads(S),(O=p.current)==null||O.draw())})};I();const w=R=>{R.preventDefault(),console.warn("birtvy gl-thumbs: WebGL context LOST â awaiting restore")},x=()=>{f||(console.warn("birtvy gl-thumbs: WebGL context restored â rebuilding the atlas"),I(),k(R=>R+1))};y.addEventListener("webglcontextlost",w),y.addEventListener("webglcontextrestored",x);const D=()=>{var R,j;
47(R=p.current)==null||R.resize(),h.current&&((j=p.current)==null||j.draw())};return window.addEventListener("resize",D),()=>{var R;f=!0,y.removeEventListener("webglcontextlost",w),y.removeEventListener("webglcontextrestored",x),window.removeEventListener("resize",D),(R=p.current)==null||R.dispose(),p.current=null,l.current=()=>{},u&&(u.current=()=>{})}},[o,i,l,u]),s.useEffect(()=>{if(!e||!p.current)return;let y=!1,f=0,I=-1,w=0;const x=()=>{const D=p.current;if(y||!D)return;const R=$i();if(R>0&&R===I){++w<400&&window.setTimeout(x,150);return}const j=D.rebuild(t,m.current);I=$i(),D.draw(),typeof window<"u"&&(window.__birtvyGlLast={...j,quadsIn:t.length,at:Date.now()}),c==null||c(j.ready,j.total),f++,!j.allReady&&f<50&&window.setTimeout(x,150)};return x(),()=>{y=!0}},[e,t,a,c,g]),s.useEffect(()=>{const y=p.current;y&&(y.applySkip(n),h.current&&y.draw())},[n]),r.jsx("canvas",{ref:d,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",display:e?"block":"none"}})}function Ov(){const{hiddenMemberKeys:e,wires:t,deleteWire:n,slides:o,notes:i,images:a,docs:l,webs:u}=Rn();return r.jsx(ib,{wires:e.size===0?t:t.filter(c=>!(c.from.kind!=="web"&&e.has(Ye(c.from.kind,c.from.id)))&&!(c.to.kind!=="web"&&e.has(Ye(c.to.kind,c.to.id)))),onDeleteWire:n,rectFor:c=>c.kind==="slide"?(()=>{const d=o.find(p=>p.id===c.id);return d?{x:d.x,y:d.y,width:Ke,height:Je}:null})():c.kind==="note"?(()=>{const d=i.find(p=>p.id===c.id);return d?{x:d.x,y:d.y,width:d.width,height:d.height}:null})():c.kind==="image"?(()=>{const d=a.find(p=>p.id===c.id);return d?{x:d.x,y:d.y,width:d.width,height:d.height}:null})():c.kind==="web"?(()=>{const d=u.find(p=>p.id===c.id);return d?{x:d.x,y:d.y,width:d.width,height:d.height}:null})():c.kind==="doc"?(()=>{const d=l.find(p=>p.id===c.id);return d?{x:d.x,y:d.y,width:d.width,height:d.height}:null})():null})}function Bv(){const{groupViews:e,revealedGroupIds:t,selectedGroupIds:n,deckIdRef:o,onGroupHeaderPointerDown:i,renameGroup:a,arrangeGroup:l,toggleGroupCollapsed:u,duplicateGroup:c,deleteGroup:d,resizeGroup:p,openSlide:h,setPresentingGroupId:m,exportGroup:g,exportingGroupId:k,groups:y,setGroupCols:f,toggleGroupSnap:I,store:w}=Rn(),{flushSave:x,zoom:D}=w;return r.jsx(r.Fragment,{children:e.map(R=>r.jsx(Dv,{view:R,revealed:t.has(R.id),selected:n.has(R.id),deckId:o.current??void 0,onHeaderPointerDown:j=>i(R.id,j),onRename:j=>a(R.id,j),onArrange:()=>l(R.id),onToggleCollapse:()=>u(R.id),onDuplicate:()=>c(R.id),onDelete:()=>d(R.id),onResize:j=>p(R.id,j),onOpenSlide:j=>h(j),onPresent:()=>m(R.id),onExport:()=>void g(R.id),onFlush:x,exporting:k===R.id,cols:(()=>{const j=y.find(A=>A.id===R.id);if((j==null?void 0:j.cols)!=null)return j.cols;if(!R.isParent){const A=R.memberRects.filter(O=>O.kind!=="slide").length;return A>0?Math.max(1,Math.ceil(Math.sqrt(A))):kr}const S=y.filter(A=>A.parentId===R.id).length+R.members.length;return(j==null?void 0:j.cols)??Math.max(1,S)})(),maxCols:R.isParent?Math.max(1,Math.min(ys,y.filter(j=>j.parentId===R.id).length+R.members.length)):Math.max(1,Math.min(ys,R.memberCount)),onSetCols:j=>f(R.id,j),snap:dr(y.find(j=>j.id===R.id),R.slidesOnly),onToggleSnap:()=>I(R.id),getZoom:()=>D.current},R.id))})}function Fv(){const{snapVGuideRef:e,snapHGuideRef:t}=Rn();return r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:e,style:{position:"absolute",top:0,left:0,width:"calc(1px * var(--port-scale, 1))",transform:"translateX(-50%)",background:Dc,display:"none",pointerEvents:"none",zIndex:999999}}),r.jsx("div",{ref:t,style:{position:"absolute",top:0,left:0,height:"calc(1px * var(--port-scale, 1))",transform:"translateY(-50%)",background:Dc,display:"none",pointerEvents:"none",zIndex:999999}})]})}function Gv(){const{glMode:e,glActive:t,glQuads:n,glSkipIndices:o,thumbTick:i,glDrawRef:a,glDragQuadsRef:l,onGlProgress:u,store:c}=Rn(),{pan:d,zoom:p}=c;return e?r.jsx(_v,{active:t,quads:n,skip:o,panRef:d,zoomRef:p,thumbTick:i,drawRef:a,dragRef:l,onProgress:u}):null}function Wv(){const{marqueeActive:e,marqueeRectRef:t,overlayRef:n,store:o}=Rn(),{pan:i,zoom:a}=o;return e&&t.current?r.jsx("div",{ref:n,"data-active":"1",style:{position:"absolute",pointerEvents:"none",border:"1px solid #2563eb",background:"rgba(37,99,235,0.10)",left:t.current.x*a.current+i.current.x,top:t.current.y*a.current+i.current.y,width:t.current.w*a.current,height:t.current.h*a.current}}):null}function Hv(){const{isAgentOpen:e,AGENT_DOCK_GAP:t,AGENT_WIDTH:n,AGENT_DOCK_MS:o,AGENT_DOCK_EASE:i}=Rn();
47return r.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute",style:{top:e?t:0,left:e?t:0,bottom:e?t:0,right:e?n:0,borderRadius:e?"var(--radius-lg)":"0px",boxShadow:e?"inset 0 0 0 1px var(--color-border-default)":"inset 0 0 0 0 transparent",transition:`top ${o}ms ${i}, left ${o}ms ${i}, bottom ${o}ms ${i}, right ${o}ms ${i}, border-radius ${o}ms ${i}, box-shadow ${o}ms ${i}`}})}function Uv(e){for(const t of(e??"").split(` 48`)){const n=t.replace(/^\s*#{1,6}\s+/,"").replace(/^\s*[-*+]\s+/,"").trim();if(n)return n}return"Empty document"}function Xv({conversationId:e,placedDocumentIds:t,onPlace:n,onDocumentDeleted:o,onClose:i}){const{documents:a,isLoading:l,isSaving:u,error:c,createDocument:d,deleteDocument:p}=Kp(e),{showToast:h}=Qi(),[m,g]=s.useState(null),[k,y]=s.useState(!1),f=s.useRef(null),I=s.useRef(null);la(f,i);const w=async()=>{if(!u){try{const S=await d({content:""});n(S)}catch{h({title:"Couldnât create the document â the Library is unavailable. Try again in a moment.",variant:"error"})}i()}},x=S=>{g(null),o(S),p(S)},D=/\.(md|markdown|txt|mdx)$/i,R=async S=>{const A=(S?Array.from(S):[]).filter(O=>D.test(O.name)||O.type==="text/markdown"||O.type==="text/plain");if(!(A.length===0||!e)){y(!0);try{for(const O of A){const T=await O.text();T.trim()&&await d({title:"",content:T})}}catch{}finally{y(!1)}}};return r.jsxs(Kn.div,{ref:f,className:"fixed left-[calc(var(--spacing-12)+72px)] top-1/2 z-[1400] flex w-[340px] -translate-y-1/2 flex-col overflow-hidden rounded-[20px] border border-[var(--color-border-default)] bg-[var(--color-default)] shadow-[var(--shadow-modal-lg)]",style:{transformOrigin:"left center"},initial:{opacity:0,scale:.96,x:-4},animate:{opacity:1,scale:1,x:0},transition:{duration:.14,ease:[.22,1,.36,1]},onPointerDown:S=>S.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center gap-[var(--spacing-8)] border-b border-[var(--color-border-default)] py-[var(--spacing-12)] pl-[var(--spacing-16)] pr-[var(--spacing-12)]",children:[r.jsx("span",{className:"flex-1 text-sm font-medium text-[var(--color-text-default)]",children:"Documents"}),r.jsxs("div",{className:"flex items-center gap-[var(--spacing-6)]",children:[r.jsx(st,{type:"button",variant:"ghost",size:"xs",disabled:k||!e,loading:k,leadIcon:"upload",title:"Upload a Markdown or text file as a document",onClick:()=>{var S;return(S=I.current)==null?void 0:S.click()},children:k?"Uploadingâ¦":"Upload"}),r.jsx(st,{type:"button",variant:"secondary",size:"xs",disabled:u||!e,loading:u,leadIcon:"add",onClick:()=>void w(),children:u?"Creatingâ¦":"New"})]}),r.jsx("input",{ref:I,type:"file",accept:".md,.markdown,.mdx,.txt,text/markdown,text/plain",multiple:!0,className:"hidden",onChange:S=>{R(S.target.files),S.target.value=""}})]}),r.jsxs("div",{className:"h-[320px] overflow-y-auto p-[var(--spacing-8)]",children:[l?r.jsx("div",{className:"flex flex-col gap-[var(--spacing-4)]",children:Array.from({length:6}).map((S,A)=>r.jsxs("div",{className:"flex items-center gap-[var(--spacing-8)] p-[var(--spacing-6)]",children:[r.jsx("div",{className:`h-5 w-5 shrink-0 rounded-[6px] ${hr.shimmer}`}),r.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-[var(--spacing-6)] py-0.5",children:[r.jsx("div",{className:`h-3 rounded-[4px] ${hr.shimmer}`,style:{width:`${70-A%3*12}%`}}),r.jsx("div",{className:`h-2.5 w-2/5 rounded-[4px] ${hr.shimmer}`})]})]},A))}):a.length===0?r.jsxs("div",{className:"px-2 py-6 text-center text-sm text-[var(--color-text-subtle)]",children:["No documents yet.",r.jsx("button",{type:"button",className:"ml-1 font-medium text-[var(--color-text-default)] underline disabled:opacity-50",disabled:u||!e,onClick:()=>void w(),children:"Create one"})]}):r.jsx("div",{className:"flex flex-col gap-[var(--spacing-4)]",children:a.map(S=>{const A=t.has(S.id),O=S.status==="PROPOSED";return r.jsxs("div",{className:"group relative flex items-center gap-[var(--spacing-8)] rounded-[var(--radius-sm)] py-[var(--spacing-6)] pl-[var(--spacing-6)] pr-[var(--spacing-14)] transition-colors hover:bg-[var(--color-subtle)]",children:[r.jsxs("button",{type:"button",title:A?"Already on canvas â select it":"Place on canvas",className:"flex min-w-0 flex-1 items-center gap-[var(--spacing-8)] text-left",onClick:()=>{n(S),i()},children:[r.jsx(At,{name:"file-text",size:20,className:"shrink-0 text-[var(--color-icon-default-muted)]"}),r.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-[var(--spacing-4)]",children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"truncate text-sm font-medium leading-5 text-[var(--color-text-subtle)]",children:S.title||"Untitled"}),O?r.jsx("span",{className:"shrink-0 rounded-full bg-[var(--color-subtle)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-text-muted)]",children:"Proposed"}):null]}),r.jsx("span",{className:"block truncate text-xs leading-4 text-[var(--color-text-muted)]",children:Uv(S.content)})]})]}),m===S.id?r.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 self-center",children:[r.jsx("button",{type:"button",className:"rounded-md px-1.5 py-1 text-xs font-medium text-[var(--color-state-error,#dc2626)] hover:underline",onClick:()=>x(S.id),children:"Delete"}),r.jsx("button",{type:"button",className:"rounded-md px-1.5 py-1 text-xs font-medium text-[var(--color-text-muted)] hover:underline",onClick:()=>g(null),children:"Cancel"})]}):r.jsx(st,{type:"button",variant:"ghostMuted",size:"icon-2xs",leadIcon:"delete-bin-6","aria-label":"Delete from Library",title:"Delete from Library (permanent)",className:"shrink-0 self-center opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>g(S.id)})]},S.id)})}),c?r.jsx("p",{className:"px-2 pt-2 text-xs text-[var(--color-state-error,#dc2626)]",children:c}):null]})]})}const Yv="_menu_9og5r_6",Kv="_item_9og5r_21",Vv="_danger_9og5r_53",qv="_content_9og5r_56",Jv="_shortcut_9og5r_74",Zv="_separator_9og5r_83",Lr={menu:Yv,item:Kv,danger:Vv,content:qv,shortcut:Jv,separator:Zv};function Qv({position:e,items:t,onClose:n}){const o=s.useRef(null);s.useEffect(()=>{const p=k=>{(!o.current||!o.current.contains(k.target))&&n()},h=()=>n(),m=k=>{k.key==="Escape"&&n()},g=window.setTimeout(()=>{window.addEventListener("pointerdown",p,!0),window.addEventListener("wheel",h,{passive:!0}),window.addEventListener("blur",h)},0);return window.addEventListener("keydown",m),()=>{window.clearTimeout(g),window.removeEventListener("pointerdown",p,!0),window.removeEventListener("wheel",h),window.removeEventListener("blur",h),window.removeEventListener("keydown",m)}},[n]);const i=t.filter(p=>!("separator"in p)).length,a=t.length-i,l=i*40+a*9+16,c=Math.min(e.x,window.innerWidth-220-8),d=Math.min(e.y,window.innerHeight-l-8);return r.jsx("div",{ref:o,className:Lr.menu,style:{left:c,top:d},onPointerDown:p=>p.stopPropagation(),onContextMenu:p=>p.preventDefault(),children:t.map((p,h)=>"separator"in p?r.jsx("div",{className:Lr.separator},`sep-${h}`):r.jsxs("button",{type:"button",disabled:p.disabled,className:`${Lr.item} ${p.danger?Lr.danger:""}`,onClick:()=>{p.onSelect(),n()},children:[r.jsxs("span",{className:Lr.content,children:[r.jsx(At,{name:p.icon,size:16}),r.jsx("span",{children:p.label})]}),p.shortcut?r.jsx("span",{className:Lr.shortcut,children:p.shortcut}):null]},p.key))})}const e0=1024,t0=400,n0=6;function md(e){return e.startsWith("gemini")?{name:"sparkling-fill",preserveColors:!1}:e.includes("/")?{name:"brand-chatgpt",preserveColors:!0}:{name:"claude-logo",preserveColors:!0}}function r0({conversationId:e,onClose:t,onSave:n}){const{modelAccess:o}=nu(),i=(o==null?void 0:o.currentTier)??null,[a,l]=s.useState(Rg),u=Vp(i,a)?a:qp(i),c=Md(i),[d,p]=s.useState(!1),h=s.useRef(null),[m,g]=s.useState("collect"),[k,y]=s.useState([]),[f,I]=s.useState([]),[w,x]=s.useState([]),[D,R]=s.useState([]),[j,S]=s.useState(""),[A,O]=s.useState(!1),[T,X]=s.useState(null),[L,W]=s.useState(null),[H,ae]=s.useState(""),ge=s.useCallback(b=>{W(C=>C&&{...C,profile:{...C.profile,...b}})},[]),J=s.useRef(null),ce=s.useRef(null);s.useEffect(()=>{const b=C=>{C.key==="Escape"&&t()};return document.addEventListener("keydown",b),document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",b),document.body.style.overflow="unset"}},[t]),s.useEffect(()=>{if(!d)return;const b=C=>{h.current&&!h.current.contains(C.target)&&p(!1)};return window.addEventListener("pointerdown",b,!0),()=>window.removeEventListener("pointerdown",b,!0)},[d]);const ve=f.length+k.length>0&&!A,oe=s.useCallback(async b=>{if(!(b!=null&&b.length))return;X(null);const C=[];for(const z of Array.from(b)){if(!z.type.startsWith("image/"))continue;const B=URL.createObjectURL(z),M=await vs(B,e0);URL.revokeObjectURL(B),M&&C.push({id:`${Date.now()}-${C.length}`,dataUrl:M})}C.length&&y(z=>[...z,...C])},[]),pe=s.useCallback(async b=>{const C=b==null?void 0:b[0];if(!C)return;X(null),O(!0);const z=(await Fg(C,{maxPages:40,maxDim:1400})).map(B=>B.dataUrl);if(O(!1),z.length===0){X("Could not read that PDF.");return}I(B=>[...B,...z]),x(B=>[...B,C.name])},[]),K=s.useCallback(()=>{const b=j.trim();if(!b)return;const C=/^https?:\/\//i.test(b)?b:`https://${b}`;R(z=>z.includes(C)?z:[...z,C]),S("")},[j]),fe=s.useCallback(async()=>{const b=[...f,...k.map(B=>B.dataUrl)];if(b.length===0){X("Add at least one image or PDF.");return}g("synthesizing"),X(null);const C=await Jp(b),z=await Gg(b,D,e,u,C);if(!z){g("collect"),X("Synthesis failed. Try again.");return}W(z),ae(z.title||"Design system"),g("ready")},[f,k,D,e,u]),ie=s.useCallback(async()=>
48{if(!L)return;const b=(await Promise.all(Wg(f,n0).map(C=>vs(C,t0)))).filter(C=>!!C);n({name:H,profile:L.profile,sources:{...D.length?{websites:D}:{},...w.length?{pdf:w}:{}},...b.length?{examples:b}:{}}),t()},[L,H,f,D,w,n,t]),Y=s.useMemo(()=>{const b=[];return f.length&&b.push(`${f.length} PDF page${f.length>1?"s":""}`),k.length&&b.push(`${k.length} image${k.length>1?"s":""}`),D.length&&b.push(`${D.length} website${D.length>1?"s":""}`),b.join(" · ")},[f.length,k.length,D.length]);return Mo.createPortal(r.jsx("div",{className:"fixed inset-0 z-[1500] flex items-center justify-center bg-black/40 p-4",onPointerDown:b=>b.target===b.currentTarget&&t(),children:r.jsxs("div",{className:"flex w-[min(940px,94vw)] max-h-[88vh] flex-col overflow-hidden rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-card)] shadow-[var(--shadow-modal-md)]",onPointerDown:b=>b.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-[var(--color-border-default)] px-5 py-4",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx(At,{name:"reference-image",size:20,className:"text-[var(--color-icon-default-muted)]"}),r.jsx("h2",{className:"text-base font-semibold text-[var(--color-text-default)]",children:"Design system"})]}),r.jsx("button",{type:"button",onClick:t,"aria-label":"Close",className:"rounded-md p-1 text-[var(--color-icon-default-muted)] hover:bg-[var(--color-subtle)]",children:r.jsx(At,{name:"close",size:20})})]}),r.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4",children:[m==="collect"&&r.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-[var(--color-text-subtle)]",children:"Synthesize with"}),r.jsxs("div",{className:"relative",ref:h,onPointerDown:b=>b.stopPropagation(),children:[r.jsx(eu,{label:Zd[u],isOpen:d,onClick:()=>p(b=>!b),selectedId:u,leadIconName:md(u).name,leadIconPreserveColors:md(u).preserveColors,size:"sm"}),d?r.jsx(tu,{options:c,selectedId:u,onSelect:b=>{l(b),p(!1)},onLockedSelect:()=>p(!1)}):null]})]}),m==="collect"&&r.jsx(s0,{photos:k,pdfPages:f,pdfBusy:A,websiteUrls:D,websiteDraft:j,onWebsiteDraft:S,onAddWebsite:K,onRemoveWebsite:b=>R(C=>C.filter(z=>z!==b)),onRemovePhoto:b=>y(C=>C.filter(z=>z.id!==b)),onPickImages:()=>{var b;return(b=J.current)==null?void 0:b.click()},onPickPdf:()=>{var b;return(b=ce.current)==null?void 0:b.click()}}),m==="synthesizing"&&r.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 py-20 text-center",children:[r.jsx("div",{className:"h-7 w-7 animate-spin rounded-full border-2 border-[var(--color-border-default)] border-t-[var(--color-text-default)]"}),r.jsx("p",{className:"text-sm text-[var(--color-text-muted)]",children:"Reading your references and building the systemâ¦"})]}),m==="ready"&&L&&r.jsx(o0,{profile:L.profile,name:H,onName:ae,onPatchProfile:ge,examples:f,provenance:Y})]}),r.jsxs("div",{className:"flex items-center justify-between gap-3 border-t border-[var(--color-border-default)] px-5 py-3",children:[r.jsx("div",{className:"min-h-[20px] text-xs text-[var(--color-text-subtle)]",children:T?r.jsx("span",{className:"text-[var(--color-text-danger)]",children:T}):Y||"Add a PDF, images, or a website."}),m==="ready"?r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(st,{type:"button",variant:"secondary",size:"default",onClick:()=>g("collect"),children:"Back"}),r.jsx(st,{type:"button",variant:"default",size:"default",onClick:ie,children:"Use as deck style"})]}):r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(st,{type:"button",variant:"secondary",size:"default",onClick:t,children:"Cancel"}),r.jsx(st,{type:"button",variant:"default",size:"default",disabled:!ve||m==="synthesizing",loading:m==="synthesizing",onClick:fe,children:"Synthesize"})]})]}),r.jsx("input",{ref:J,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:b=>{oe(b.target.files),b.target.value=""}}),r.jsx("input",{ref:ce,type:"file",accept:"application/pdf",className:"hidden",onChange:b=>{pe(b.target.files),b.target.value=""}})]})}),document.body)}function s0(e){const t="flex flex-1 flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-[var(--color-border-default)] bg-[var(--color-subtle)] px-4 py-6 text-center transition-colors hover:border-[var(--color-border-strong)]";return r.jsxs("div",{className:"flex flex-col gap-5",children:[r.jsx("p",{className:"text-sm text-[var(--color-text-muted)]",children:"Collect references, then Synthesize them into one reusable style. A PDF deck is the strongest source â its pages teach the type, colour, and spacing."}),r.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row",children:[r.jsxs("button",{type:"button",className:t,onClick:e.onPickPdf,children:[r.jsx(At,{name:"file-text",size:22,className:"text-[var(--color-icon-default-muted)]"}),r.jsx("span",{className:"text-sm font-medium text-[var(--color-text-default)]",children:e.pdfBusy?"Reading PDFâ¦":"Upload PDF"}),r.jsx("span",{className:"text-xs text-[var(--color-text-subtle)]",children:e.pdfPages.length?`${e.pdfPages.length} pages added`:"pages become references"})]}),r.jsxs("button",{type:"button",className:t,onClick:e.onPickImages,children:[r.jsx(At,{name:"image_editor",size:22,className:"text-[var(--color-icon-default-muted)]"}),r.jsx("span",{className:"text-sm font-medium text-[var(--color-text-default)]",children:"Add images"}),r.jsx("span",{className:"text-xs text-[var(--color-text-subtle)]",children:e.photos.length?`${e.photos.length} added`:"photos, screenshots"})]}),r.jsxs("div",{className:t.replace("hover:border-[var(--color-border-strong)]",""),children:[r.jsx(At,{name:"link-extract",size:22,className:"text-[var(--color-icon-default-muted)]"}),r.jsxs("div",{className:"flex w-full items-center gap-1.5",children:[r.jsx("input",{value:e.websiteDraft,onChange:n=>e.onWebsiteDraft(n.target.value),onKeyDown:n=>n.key==="Enter"&&e.onAddWebsite(),placeholder:"paste a website",className:"min-w-0 flex-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-card)] px-2 py-1 text-xs text-[var(--color-text-default)] outline-none focus:border-[var(--color-border-strong)]"}),r.jsx("button",{type:"button",onClick:e.onAddWebsite,className:"rounded-md bg-[var(--color-card)] px-2 py-1 text-xs font-medium text-[var(--color-text-default)] hover:bg-[var(--color-subtle)]",children:"Add"})]}),r.jsx("span",{className:"text-xs text-[var(--color-text-subtle)]",children:"reads brand fonts + colours"})]})]}),(e.pdfPages.length>0||e.photos.length>0)&&r.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.pdfPages.map((n,o)=>r.jsx("div",{className:"h-20 w-28 overflow-hidden rounded-md border border-[var(--color-border-default)] bg-[var(--color-subtle)]",children:r.jsx("img",{src:n,alt:"",className:"h-full w-full object-cover"})},`pdf-${o}`)),e.photos.map(n=>r.jsxs("div",{className:"group relative h-20 w-20 overflow-hidden rounded-md border border-[var(--color-border-default)]",children:[r.jsx("img",{src:n.dataUrl,alt:"",className:"h-full w-full object-cover"}),r.jsx("button",{type:"button",onClick:()=>e.onRemovePhoto(n.id),"aria-label":"Remove",className:"absolute right-1 top-1 hidden rounded bg-black/60 p-0.5 text-white group-hover:block",children:r.jsx(At,{name:"close",size:12})})]},n.id))]}),e.websiteUrls.length>0&&r.jsx("div",{className:"flex flex-wrap gap-2",children:e.websiteUrls.map(n=>r.jsxs("span",{className:"flex items-center gap-1.5 rounded-full border border-[var(--color-border-default)] bg-[var(--color-subtle)] py-1 pl-3 pr-1.5 text-xs text-[var(--color-text-default)]",children:[n.replace(/^https?:\/\//,""),r.jsx("button",{type:"button",onClick:()=>e.onRemoveWebsite(n),"aria-label":"Remove",className:"rounded-full p-0.5 hover:bg-[var(--color-card)]",children:r.jsx(At,{name:"close",size:12})})]},n))})]})}function o0({profile:e,name:t,onName:n,onPatchProfile:o,examples:i,provenance:a}){return r.jsxs("div",{className:"flex flex-col gap-5",children:[r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsx("input",{value:t,onChange:l=>n(l.target.value),className:"w-full rounded-lg border border-[var(--color-border-default)] bg-[var(--color-subtle)] px-3 py-2 text-lg font-semibold text-[var(--color-text-default)] outline-none focus:border-[var(--color-border-strong)]",placeholder:"Name this style"}),a&&r.jsxs("span",{className:"text-xs text-[var(--color-text-subtle)]",children:["Built from ",a]})]}),e.palette.length>0&&r.jsx(zr,{label:"Colors",children:r.jsx("div",{className:"flex flex-wrap gap-2",children:e.palette.map(l=>r.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-[var(--color-border-default)] py-1 pl-1.5 pr-2.5",children:[r.jsx("span",{className:"h-6 w-6 rounded-md border border-black/10",style:{background:l}}),r.jsx("span",{className:"font-mono text-xs text-[var(--color-text-muted)]",children:l})]},l))})}),r.jsxs(zr,{label:"Type",children:[r.jsxs("div",{className:"flex flex-wrap gap-4",children:[r.jsx(gd,{label:"Heading",value:e.headingFont,onChange:l=>o({headingFont:l})}),r.jsx(gd,{label:"Body",value:e.bodyFont,onChange:l=>o({bodyFont:l})})]}),e.typography&&r.jsx("p",{className:"mt-1 text-sm text-[var(--color-text-muted)]",children:e.typography})]}),(e.spacing||e.shadows||e.tone)&&r.jsx(zr,{label:"System",children:r.jsxs("div",{className:"flex flex-col gap-1.5 text-sm",children:[e.spacing&&r.jsx(Di,{k:"Spacing",v:e.spacing}),e.shadows&&r.jsx(Di,{k:"Shadows",v:e.shadows}),e.tone&&r.jsx(Di,{k:"Tone",v:e.tone})]})}),e.patterns&&e.patterns.length>0&&r.jsx(zr,{label:"How to use",children:r.jsx("ul",{className:"flex flex-col gap-1.5",children:e.patterns.map((l,u)=>r.jsxs("li",{className:"flex gap-2 text-sm leading-relaxed text-[var(--color-text-muted)]",children:[r.jsx("span",{className:"mt-1.5 h-1 w-1 shrink-0 rounded-full bg-[var(--color-text-subtle)]"}),r.jsx("span",{children:l})]},u))})}),e.tasteProfile&&r.jsx(zr,{label:"Direction",children:r.jsx("p",{className:"text-sm leading-relaxed text-[var(--color-text-muted)]",children:e.tasteProfile})}),(e.keywords.length>0||e.avoids.length>0)&&r.jsxs("div",{className:"flex flex-col gap-2",children:[e.keywords.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.keywords.map(l=>r.jsx("span",{className:"rounded-full bg-[var(--color-subtle)] px-2.5 py-1 text-xs text-[var(--color-text-default)]",children:l},l))}),e.avoids.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.avoids.map(l=>r.jsx("span",{className:"rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-subtle)] line-through",children:l},l))})]}),i.length>0&&r.jsx(zr,{label:"Examples",children:r.jsx("div",{className:"flex flex-wrap gap-2",children:i.slice(0,8).map((l,u)=>r.jsx("div",{className:"h-24 w-36 overflow-hidden rounded-md border border-[var(--color-border-default)] bg-[var(--color-subtle)]",children:r.jsx("img",{src:l,alt:"",className:"h-full w-full object-cover"})},u))})})]})}function zr({label:e,children:t}){return r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-[var(--color-text-subtle)]",children:e}),t]})}function gd({label:e,value:t,onChange:n}){const o=!!t&&xo.some(i=>i.label===t);return r.jsxs("label",{className:"flex flex-col gap-1 text-xs text-[var(--color-text-subtle)]",children:[e,r.jsxs("select",{value:t??"",onChange:i=>n(i.target.value),className:"rounded-md border border-[var(--color-border-default)] bg-[var(--color-card)] px-2 py-1.5 text-sm text-[var(--color-text-default)] outline-none focus:border-[var(--color-border-strong)]",children:[!t&&r.jsx("option",{value:"",children:"Chooseâ¦"}),t&&!o&&r.jsx("option",{value:t,children:t}),xo.map(i=>r.jsx("option",{value:i.label,children:i.label},i.id))]})]})}function Di({k:e,v:t}){return r.jsxs("div",{className:"flex gap-3",children:[r.jsx("span",{className:"w-20 shrink-0 text-[var(--color-text-subtle)]",children:e}),r.jsx("span",{className:"text-[var(--color-text-default)]",children:t})]})}function i0({systems:e,activeId:t,onEdit:n,onToggleActive:o,onNew:i,onPromote:a,promotedIds:l,onClose:u}){const c=s.useRef(null);return la(c,u),r.jsxs(Kn.div,{ref:c,className:"fixed left-[calc(var(--spacing-12)+72px)] top-1/2 z-[1400] flex w-[300px] -translate-y-1/2 flex-col overflow-hidden rounded-[20px] border border-[var(--color-border-default)] bg-[var(--color-default)] shadow-[var(--shadow-modal-lg)]",style:{transformOrigin:"left center"},initial:{opacity:0,scale:.96,x:-4}
48,animate:{opacity:1,scale:1,x:0},transition:{duration:.14,ease:[.22,1,.36,1]},onPointerDown:p=>p.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center gap-[var(--spacing-8)] border-b border-[var(--color-border-default)] py-[var(--spacing-12)] pl-[var(--spacing-16)] pr-[var(--spacing-12)]",children:[r.jsx(At,{name:"reference-image",size:16,className:"text-[var(--color-icon-default-muted)]"}),r.jsx("span",{className:"flex-1 text-sm font-medium text-[var(--color-text-default)]",children:"Design system"})]}),r.jsx("div",{"data-canvas-scroll":!0,className:"flex max-h-[50vh] flex-col overflow-y-auto py-[var(--spacing-6)]",children:e.length===0?r.jsx("p",{className:"px-[var(--spacing-16)] py-[var(--spacing-12)] text-xs leading-relaxed text-[var(--color-text-subtle)]",children:"No styles yet. Build one from a PDF, images, or a website â then every generation follows it."}):e.map(p=>{const h=p.id===t;return r.jsxs("div",{className:"group flex items-center gap-[var(--spacing-6)] px-[var(--spacing-8)] pl-[var(--spacing-12)]",children:[r.jsx(ur,{content:h?"Active style":"Use as style",side:"top",className:"z-[1500]",children:r.jsx(st,{variant:h?"soft":"ghost",size:"icon-xs",leadIcon:"check","aria-label":h?"Active style":"Use as style","aria-pressed":h,onClick:()=>o(p.id)})}),a?r.jsx(ur,{content:l!=null&&l.has(p.id)?"Saved to your Brand Kits":"Save to your Brand Kits",side:"top",className:"z-[1500]",children:r.jsx(st,{variant:"ghost",size:"icon-xs",leadIcon:l!=null&&l.has(p.id)?"check":"bookmark","aria-label":l!=null&&l.has(p.id)?`${p.name} saved to your Brand Kits`:`Save ${p.name} to your Brand Kits`,disabled:l==null?void 0:l.has(p.id),onClick:()=>a(p.id)})}):null,r.jsxs("button",{type:"button",onClick:m=>{const g=m.currentTarget.getBoundingClientRect();n(p.id,{x:g.left,y:g.top,width:g.width,height:g.height})},className:"flex min-w-0 flex-1 items-center gap-2 rounded-[var(--radius-md)] py-[var(--spacing-8)] pl-[var(--spacing-4)] pr-[var(--spacing-8)] text-left transition-colors hover:bg-[var(--color-state-ghost-hover)]",children:[r.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-[var(--color-text-default)]",children:p.name}),r.jsx(a0,{profile:p.profile}),r.jsx(At,{name:"arrow-right-s",size:14,className:"shrink-0 text-[var(--color-icon-default-muted)] opacity-0 group-hover:opacity-100"})]})]},p.id)})}),r.jsx("div",{className:"flex items-center border-t border-[var(--color-border-default)] px-[var(--spacing-8)] py-[var(--spacing-8)]",children:r.jsx(st,{variant:"ghost",size:"sm",leadIcon:"add",onClick:i,children:"New from references"})})]})}function a0({profile:e}){const t=e.roles??{},n=[t.background??e.palette[0],t.accent??e.palette[1],t.text??e.palette[2]].filter(o=>!!o);return n.length===0?null:r.jsx("span",{className:"flex shrink-0 items-center gap-0.5",children:n.map((o,i)=>r.jsx("span",{className:"h-3 w-3 rounded-sm border border-black/10",style:{background:o}},`${o}-${i}`))})}function l0({label:e,hint:t,children:n}){return r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsxs("div",{className:"flex items-baseline gap-1.5",children:[r.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-[var(--color-text-subtle)]",children:e}),t?r.jsxs("span",{className:"text-xs normal-case text-[var(--color-text-subtle)] opacity-60",children:["· ",t]}):null]}),n]})}function xd(e){const t=e.trim().replace(/^#/,"");return/^[0-9a-fA-F]{6}$/.test(t)?`#${t.toLowerCase()}`:/^[0-9a-fA-F]{3}$/.test(t)?`#${t.split("").map(n=>n+n).join("").toLowerCase()}`:null}const Es="w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-card)] px-2 py-1.5 text-sm text-[var(--color-text-default)] outline-none focus:border-[var(--color-border-strong)]";function _r({label:e,value:t,placeholder:n,hint:o,rows:i=2,onChange:a}){const l=s.useRef(null);return s.useEffect(()=>{const u=l.current;u&&(u.style.height="auto",u.style.height=`${u.scrollHeight}px`)},[t]),r.jsxs("label",{className:"flex flex-col gap-1 text-xs text-[var(--color-text-subtle)]",children:[r.jsxs("span",{className:"flex items-baseline gap-1.5",children:[e,o?r.jsxs("span",{className:"text-[var(--color-text-subtle)] opacity-60",children:["· ",o]}):null]}),r.jsx("textarea",{ref:l,value:t??"",rows:i,placeholder:n,onChange:u=>a(u.target.value),className:`${Es} resize-none leading-relaxed`})]})}function yd({label:e,items:t,strike:n=!1,placeholder:o,onChange:i}){const[a,l]=s.useState(""),u=()=>{const c=a.trim();c&&(t.some(d=>d.toLowerCase()===c.toLowerCase())||i([...t,c]),l(""))};return r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("span",{className:"text-xs text-[var(--color-text-subtle)]",children:e}),t.length>0?r.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(c=>r.jsxs("span",{className:n?"flex items-center gap-1 rounded-full border border-[var(--color-border-default)] py-1 pl-2.5 pr-1 text-xs text-[var(--color-text-subtle)]":"flex items-center gap-1 rounded-full bg-[var(--color-subtle)] py-1 pl-2.5 pr-1 text-xs text-[var(--color-text-default)]",children:[r.jsx("span",{className:n?"line-through":void 0,children:c}),r.jsx("button",{type:"button","aria-label":`Remove ${c}`,onClick:()=>i(t.filter(d=>d!==c)),className:"rounded-full p-0.5 hover:bg-[var(--color-card)]",children:r.jsx(At,{name:"close",size:12})})]},c))}):null,r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("input",{value:a,onChange:c=>l(c.target.value),onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),u())},placeholder:o,className:Es}),r.jsx("button",{type:"button",onClick:u,className:"shrink-0 rounded-md bg-[var(--color-subtle)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-default)] hover:bg-[var(--color-state-ghost-hover)]",children:"Add"})]})]})}function c0({rules:e,onChange:t}){return r.jsxs("div",{className:"flex flex-col gap-2",children:[e.map((n,o)=>r.jsxs("div",{className:"flex items-start gap-1.5",children:[r.jsx(d0,{value:n,onChange:i=>t(e.map((a,l)=>l===o?i:a))}),r.jsx("button",{type:"button","aria-label":"Remove rule",onClick:()=>t(e.filter((i,a)=>a!==o)),className:"mt-1.5 shrink-0 rounded-md p-1 text-[var(--color-icon-default-muted)] hover:bg-[var(--color-subtle)]",children:r.jsx(At,{name:"close",size:14})})]},o)),r.jsx("button",{type:"button",onClick:()=>t([...e,""]),className:"self-start rounded-md px-2 py-1 text-xs font-medium text-[var(--color-text-muted)] hover:bg-[var(--color-subtle)]",children:"+ Add rule"})]})}
48function d0({value:e,onChange:t}){const n=s.useRef(null);return s.useEffect(()=>{const o=n.current;o&&(o.style.height="auto",o.style.height=`${o.scrollHeight}px`)},[e]),r.jsx("textarea",{ref:n,value:e,rows:1,placeholder:"e.g. Accent red: single-word emphasis only, never a page background",onChange:o=>t(o.target.value),className:`${Es} resize-none leading-relaxed`})}function bd({label:e,hex:t,onChange:n,onRemove:o,onUnset:i}){const[a,l]=s.useState(t);s.useEffect(()=>l(t),[t]);const u=c=>{const d=xd(c);d?n(d):l(t)};return r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"w-[92px] shrink-0 text-xs text-[var(--color-text-subtle)]",children:e}),r.jsxs("label",{className:"relative h-7 w-7 shrink-0 cursor-pointer overflow-hidden rounded-md border border-black/10",children:[r.jsx("span",{className:"block h-full w-full",style:{background:t||"transparent"}}),r.jsx("input",{type:"color",value:xd(t)??"#71717a",onChange:c=>n(c.target.value),"aria-label":`${e} colour`,className:"absolute inset-0 h-full w-full cursor-pointer opacity-0"})]}),r.jsx("input",{value:a,onChange:c=>l(c.target.value),onBlur:c=>u(c.target.value),onKeyDown:c=>{c.key==="Enter"&&u(c.target.value)},placeholder:"#000000",spellCheck:!1,className:`${Es} max-w-[110px] font-mono text-xs`}),o?r.jsx("button",{type:"button","aria-label":`Remove ${e}`,onClick:o,className:"shrink-0 rounded-md p-1 text-[var(--color-icon-default-muted)] hover:bg-[var(--color-subtle)]",children:r.jsx(At,{name:"close",size:14})}):null,i&&t?r.jsx("button",{type:"button",onClick:i,className:"shrink-0 rounded-md px-1.5 py-1 text-xs text-[var(--color-text-subtle)] hover:bg-[var(--color-subtle)]",children:"Unset"}):null]})}function wd({label:e,value:t,onChange:n}){const[o,i]=s.useState(!1),[a,l]=s.useState(""),u=s.useRef(null);s.useEffect(()=>{t&&Li(t)},[t]),s.useEffect(()=>{if(!o)return;const d=p=>{u.current&&!u.current.contains(p.target)&&i(!1)};return window.addEventListener("pointerdown",d,!0),()=>window.removeEventListener("pointerdown",d,!0)},[o]);const c=s.useMemo(()=>{const d=a.trim().toLowerCase();return(d?xo.filter(h=>h.label.toLowerCase().includes(d)):xo).slice(0,60)},[a]);return r.jsxs("div",{className:"relative flex flex-col gap-1",ref:u,children:[r.jsx("span",{className:"text-xs text-[var(--color-text-subtle)]",children:e}),r.jsxs("button",{type:"button",onClick:()=>{l(""),i(d=>!d)},className:`${Es} flex min-w-[180px] items-center justify-between gap-2 text-left`,children:[r.jsx("span",{style:t?{fontFamily:`'${t}'`}:void 0,children:t||"Chooseâ¦"}),r.jsx(At,{name:"arrow-down-s",size:14,className:"text-[var(--color-icon-default-muted)]"})]}),o?r.jsxs("div",{"data-canvas-scroll":!0,className:"absolute left-0 top-full z-[20] mt-1 flex max-h-[280px] w-[260px] flex-col overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-card)] shadow-[var(--shadow-modal-md)]",children:[r.jsx("input",{autoFocus:!0,value:a,onChange:d=>l(d.target.value),placeholder:"Search fonts",className:"border-b border-[var(--color-border-default)] bg-transparent px-3 py-2 text-sm text-[var(--color-text-default)] outline-none"}),r.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto py-1",children:[c.map(d=>r.jsxs("button",{type:"button",onPointerEnter:()=>Li(d.label),onClick:()=>{n(d.label),i(!1)},className:`flex w-full items-center justify-between px-3 py-1.5 text-left text-sm text-[var(--color-text-default)] hover:bg-[var(--color-state-ghost-hover)] ${d.label===t?"bg-[var(--color-state-ghost-press)]":""}`,children:[r.jsx("span",{style:{fontFamily:`'${d.label}'`},children:d.label}),r.jsx("span",{className:"text-[10px] uppercase tracking-wide text-[var(--color-text-subtle)]",children:d.category})]},d.id)),c.length===0?r.jsx("p",{className:"px-3 py-2 text-xs text-[var(--color-text-subtle)]",children:"No font matches that."}):null]})]}):null]})}const u0={duration:.42,ease:[.22,1,.36,1]},vd=.2,f0=2.5,ps=56,kd=[],Sd={},Ti=(e,t,n)=>Math.min(n,Math.max(t,e)),h0=[{key:"background",label:"Background"},{key:"surface",label:"Surface"},{key:"text",label:"Text"},{key:"textMuted",label:"Muted text"},{key:"accent",label:"Accent"},{key:"border",label:"Border"}],lo=[0,940,1410],co=[900,430,430],p0=40,Ai=[{key:"preview",col:0,cap:620},{key:"rules",col:0,cap:420},{key:"direction",col:0,cap:480},{key:"colors",col:1,cap:560},{key:"type",col:1,cap:320},{key:"system",col:1,cap:440},{key:"keywords",col:2,cap:460},{key:"examples",col:2,cap:320},{key:"notes",col:2,cap:420}];function m0({system:e,origin:t,instant:n=!1,onUpdate:o,onSaveAsNew:i,onDelete:a,onClose:l}){const[u,c]=s.useState(e.name),[d,p]=s.useState(e.profile),[h,m]=s.useState(e.examples??kd),[g,k]=s.useState(e.layout??Sd),y=s.useCallback(C=>p(z=>({...z,...C})),[]),[f,I]=s.useState({name:e.name,profile:e.profile,examples:e.examples??kd,layout:e.layout??Sd}),w=u.trim()||"Design system",x=w!==f.name||d!==f.profile||h!==f.examples||g!==f.layout,D=s.useCallback(()=>({name:w,profile:d,examples:h,...Object.keys(g).length?{layout:g}:{}}),[w,d,h,g]),[R,j]=s.useState("in"),S=s.useCallback(()=>{o(D()),I({name:w,profile:d,examples:h,layout:g})},[o,D,w,d,h,g]),A=s.useCallback(()=>{const C=w===e.name?`${w} copy`:w;i({...D(),name:C})},[i,D,w,e.name]),O=s.useCallback(async()=>
48{if(!x){j("out");return}const{action:C}=await Hg({title:"Keep these changes?",body:`Update writes them over ${e.name}. Save as new keeps the original and adds this version to the library.`,confirmLabel:"Update",tone:"primary",secondaryLabel:"Save as new",cancelLabel:"Discard",cancelTone:"danger"});if(C!=="dismiss"){if(C==="secondary"){A();return}C==="confirm"&&S(),j("out")}},[x,e.name,S,A]);s.useEffect(()=>{const C=B=>{B.key==="Escape"&&(B.stopPropagation(),O())};document.addEventListener("keydown",C);const z=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",C),document.body.style.overflow=z}},[O]);const T=s.useRef(null),X=s.useRef(null),L=s.useRef({x:ps,y:ps}),W=s.useRef(1),H=s.useCallback(()=>{const C=X.current;C&&(C.style.transform=`translate(${L.current.x}px, ${L.current.y}px) scale(${W.current})`)},[]),ae=s.useMemo(()=>Ai.filter(C=>C.key!=="examples"||h.length>0).map(C=>C.key),[h.length]),ge=s.useRef({}),[J,ce]=s.useState({});s.useLayoutEffect(()=>{const C={};lo.forEach((z,B)=>{var q;let M=0;for(const ue of Ai)ue.col!==B||!ae.includes(ue.key)||(C[ue.key]=M,M+=(((q=ge.current[ue.key])==null?void 0:q.offsetHeight)??ue.cap)+p0)}),ce(C)},[ae]);const we=s.useCallback(C=>{const z=Ai.find(M=>M.key===C);if(!z)return{x:0,y:0,w:co[0],h:400};const B=g[C];return{x:(B==null?void 0:B.x)??lo[z.col],y:(B==null?void 0:B.y)??J[C]??0,w:co[z.col],h:z.cap}},[g,J]);s.useEffect(()=>{const C=T.current;if(!C)return;const z=lo[lo.length-1]+co[co.length-1],B=Ti((C.clientWidth-ps*2)/z,vd,1);W.current=B,L.current={x:ps,y:ps},H()},[]),s.useEffect(()=>{const C=T.current;if(!C)return;const z=B=>{var ye;const M=B.target;if((ye=M==null?void 0:M.closest)!=null&&ye.call(M,"[data-canvas-scroll]"))return;for(let ee=M;ee&&ee!==C;ee=ee.parentElement){const U=getComputedStyle(ee).overflowY;if((U==="auto"||U==="scroll")&&ee.scrollHeight>ee.clientHeight+1)return}B.preventDefault();let q=B.deltaY,ue=B.deltaX;if(B.deltaMode===1?(q*=16,ue*=16):B.deltaMode===2&&(q*=100,ue*=100),B.ctrlKey||B.metaKey){const ee=C.getBoundingClientRect(),U=B.clientX-ee.left,_=B.clientY-ee.top,N=Ti(Math.exp(-q*.015),.4,2.5),Z=Ti(W.current*N,vd,f0);L.current.x=U-(U-L.current.x)*(Z/W.current),L.current.y=_-(_-L.current.y)*(Z/W.current),W.current=Z}else L.current.x-=ue,L.current.y-=q;H()};return C.addEventListener("wheel",z,{passive:!1}),()=>C.removeEventListener("wheel",z)},[H]),s.useEffect(()=>{const C=T.current;if(!C)return;const z=B=>{var ee,U;const M=(U=(ee=B.target)==null?void 0:ee.closest)==null?void 0:U.call(ee,"[data-style-widget]");if(B.button!==1&&(B.button!==0||M))return;B.preventDefault();const q={x:B.clientX,y:B.clientY,px:L.current.x,py:L.current.y};C.setPointerCapture(B.pointerId),C.style.cursor="grabbing";const ue=_=>{L.current.x=q.px+(_.clientX-q.x),L.current.y=q.py+(_.clientY-q.y),H()},ye=()=>{C.removeEventListener("pointermove",ue),C.removeEventListener("pointerup",ye),C.removeEventListener("pointercancel",ye),C.style.cursor=""};C.addEventListener("pointermove",ue),C.addEventListener("pointerup",ye),C.addEventListener("pointercancel",ye)};return C.addEventListener("pointerdown",z),()=>C.removeEventListener("pointerdown",z)},[H]);const ve=s.useCallback((C,z,B)=>{k(M=>({...M,[C]:{x:Math.round(z),y:Math.round(B)}}))},[]),[oe,pe]=s.useState(null),K=d.roles??{},fe=(C,z)=>{const B=K[C];y({roles:{...K,[C]:z},palette:B?d.palette.map(M=>M.toLowerCase()===B.toLowerCase()?z:M):d.palette})},ie=C=>{const z={...K};delete z[C],y({roles:z})},Y=new Set(Object.values(K).map(C=>String(C).toLowerCase())),re=d.palette.filter(C=>!Y.has(C.toLowerCase())),le=s.useMemo(()=>{var z,B,M,q;const C=[];return(B=(z=e.sources)==null?void 0:z.pdf)!=null&&B.length&&C.push(e.sources.pdf.join(", ")),(q=(M=e.sources)==null?void 0:M.websites)!=null&&q.length&&C.push(...e.sources.websites.map(ue=>ue.replace(/^https?:\/\//,""))),C.join(" · ")},[e.sources]),b={preview:{title:"Preview",hint:"this style, live",scroll:!1,content:r.jsx(x0,{profile:d})},colors:{title:"Colors",hint:"roles drive generation",content:r.jsxs("div",{className:"flex flex-col gap-1.5",children:[h0.map(C=>r.jsx(bd,{label:C.label,hex:K[C.key]??"",onChange:z=>fe(C.key,z),onUnset:()=>ie(C.key)},C.key)),re.length?r.jsx("div",{className:"mt-1 h-px bg-[var(--color-border-default)]"}):null,re.map(C=>r.jsx(bd,{label:"Palette",hex:C,onChange:z=>y({palette:d.palette.map(B=>B===C?z:B)}),onRemove:()=>y({palette:d.palette.filter(z=>z!==C)})},C)),r.jsx("button",{type:"button",onClick:()=>y({palette:[...d.palette,"#71717a"]}),className:"self-start rounded-md px-2 py-1 text-xs font-medium text-[var(--color-text-muted)] hover:bg-[var(--color-subtle)]",children:"+ Add colour"})]})},type:{title:"Type",scroll:!1,content:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsxs("div",{className:"flex flex-wrap gap-3",children:[r.jsx(wd,{label:"Heading",value:d.headingFont,onChange:C=>y({headingFont:C})}),r.jsx(wd,{label:"Body",value:d.bodyFont,onChange:C=>y({bodyFont:C})})]}),r.jsx(_r,{label:"Type hierarchy",value:d.typography,placeholder:"Display headlines 120px+ bold uppercase; 18px regular body",onChange:C=>y({typography:C})})]})},system:{title:"System",content:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsx(_r,{label:"Spacing",value:d.spacing,placeholder:"Generous margins, 80px gutters, lots of negative space",onChange:C=>y({spacing:C})}),r.jsx(_r,{label:"Shadows",value:d.shadows,placeholder:"Flat, no shadows",onChange:C=>y({shadows:C})}),r.jsx(_r,{label:"Tone",hint:"shapes the words on every slide",value:d.tone,placeholder:"Confident, plain, short â no hype",onChange:C=>y({tone:C})})]})},rules:{title:"How to use",hint:"followed literally when generating",content:r.jsx(c0,{rules:d.patterns??[],onChange:C=>y({patterns:C})})},direction:{title:"Direction",hint:"the largest instruction sent to the model",content:r.jsx(_r,{label:"Art direction",rows:4,value:d.guideline,placeholder:"Concrete art direction a slide generator should follow.",onChange:C=>y({guideline:C})})},keywords:{title:"Keywords",content:r.jsxs("div",{className:"flex flex-col gap-4",children:[r.jsx(yd,{label:"Reach for",items:d.keywords??[],placeholder:"editorial, minimalâ¦",onChange:C=>y({keywords:C})}),r.jsx(yd,{label:"Avoid",items:d.avoids??[],strike:!0,placeholder:"gradients, drop shadowsâ¦",onChange:C=>y({avoids:C})})]})},examples:{title:"Examples",hint:"illustration only",content:r.jsx("div",{className:"flex flex-wrap gap-2",children:h.map((C,z)=>r.jsxs("div",{className:"group relative h-24 w-36 overflow-hidden rounded-md border border-[var(--color-border-default)] bg-[var(--color-subtle)]",children:[r.jsx("img",{src:C,alt:"",className:"h-full w-full object-cover"}),r.jsx("button",{type:"button","aria-label":"Remove example",onClick:()=>m(h.filter((B,M)=>M!==z)),className:"absolute right-1 top-1 hidden rounded bg-black/60 p-0.5 text-white group-hover:block",children:r.jsx(At,{name:"close",size:12})})]},z))})},notes:{title:"Notes",hint:"not sent to generation",content:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsx(_r,{label:"What this style is",rows:4,value:d.tasteProfile,onChange:C=>y({tasteProfile:C})}),le?r.jsx(l0,{label:"Built from",children:r.jsx("span",{className:"text-xs leading-relaxed text-[var(--color-text-subtle)]",children:le})}):null]})}};return Mo.createPortal(r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[1440]"}),r.jsxs(Kn.div,{className:"fixed inset-0 z-[1450] overflow-hidden bg-[var(--color-subtle)]",initial:{y:n?0:"100%"},animate:{y:R==="out"?"100%":0},transition:u0,onAnimationComplete:()=>{R==="out"&&l()},children:[r.jsx("div",{ref:T,className:"absolute inset-0 cursor-grab overflow-hidden",children:r.jsx("div",{ref:X,style:{position:"absolute",top:0,left:0,transformOrigin:"0 0"},children:ae.map(C=>{const z=b[C];return z?r.jsx(g0,{id:C,rect:we(C),title:z.title,hint:z.hint,scroll:z.scroll,zoomRef:W,onTop:oe===C,onGrab:()=>pe(C),onEl:B=>{ge.current[C]=B},onMove:(B,M)=>ve(C,B,M),children:z.content},C):null})})}),r.jsxs("div",{className:"pointer-events-none absolute left-0 right-0 top-0 flex items-start justify-between gap-4 p-4",children:[r.jsxs("div",{className:"pointer-events-auto flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-default)] py-1.5 pl-1.5 pr-4 shadow-[var(--shadow-modal-md)]",children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"close","aria-label":"Close style",onClick:O}),r.jsx("span",{className:"h-4 w-px bg-[var(--color-border-default)]"}),r.jsx("input",{value:u,onChange:C=>c(C.target.value),placeholder:"Name this style","aria-label":"Style name",className:"min-w-[120px] max-w-[340px] bg-transparent px-2 text-sm font-medium text-[var(--color-text-default)] outline-none",style:{width:`${Math.max(u.length,8)}ch`}})]}),r.jsxs("div",{className:"pointer-events-auto flex items-center gap-2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-default)] p-1.5 shadow-[var(--shadow-modal-md)]",children:[x?r.jsx("span",{className:"pl-2 text-xs text-[var(--color-text-subtle)]",children:"Unsaved"}):null,a?r.jsxs(r.Fragment,{children:[r.jsx(st,{variant:"ghost",size:"icon-sm",leadIcon:"delete-bin-6","aria-label":"Delete style",onClick:a}),r.jsx("span",{className:"h-4 w-px bg-[var(--color-border-default)]"})]}):null,r.jsx(st,{variant:"ghost",size:"sm",onClick:A,children:"Save as new"}),r.jsx(st,{variant:"default",size:"sm",disabled:!x,onClick:S,children:"Update"})]})]})]})]}),document.body)}
48function g0({id:e,rect:t,title:n,hint:o,scroll:i=!0,zoomRef:a,onTop:l=!1,onGrab:u,onEl:c,onMove:d,children:p}){const h=s.useRef(null),m=s.useRef(null),g=f=>{f.button===0&&(f.stopPropagation(),f.currentTarget.setPointerCapture(f.pointerId),m.current={x:f.clientX,y:f.clientY,dx:0,dy:0})},k=f=>{const I=m.current,w=h.current;!I||!w||(I.dx=(f.clientX-I.x)/a.current,I.dy=(f.clientY-I.y)/a.current,w.style.transform=`translate(${I.dx}px, ${I.dy}px)`)},y=()=>{const f=m.current,I=h.current;m.current=null,!(!f||!I)&&(I.style.transform="",(Math.abs(f.dx)>1||Math.abs(f.dy)>1)&&d(t.x+f.dx,t.y+f.dy))};return r.jsxs("div",{ref:f=>{h.current=f,c==null||c(f)},"data-style-widget":e,onPointerDownCapture:u,className:"absolute flex cursor-default flex-col rounded-[20px] border border-[var(--color-border-default)] bg-[var(--color-card)] shadow-[var(--shadow-modal-md)]",style:{left:t.x,top:t.y,width:t.w,maxHeight:t.h,overflow:i?"hidden":"visible",zIndex:l?2:1},children:[r.jsxs("div",{onPointerDown:g,onPointerMove:k,onPointerUp:y,onPointerCancel:y,className:"flex shrink-0 cursor-grab items-baseline gap-1.5 px-4 pb-2 pt-3.5 active:cursor-grabbing",children:[r.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-[var(--color-text-subtle)]",children:n}),o?r.jsxs("span",{className:"text-xs normal-case text-[var(--color-text-subtle)] opacity-60",children:["· ",o]}):null]}),r.jsx("div",{"data-canvas-scroll":i?"":void 0,className:`min-h-0 flex-1 px-4 pb-4 ${i?"overflow-y-auto":"overflow-visible"}`,children:p})]})}function x0({profile:e}){const t=e.roles??{},n=t.background??e.palette[0]??"#ffffff",o=t.surface??e.palette[1]??n,i=t.text??"#111111",a=t.textMuted??i,l=t.accent??e.palette[2]??i,u=t.border??"rgba(0,0,0,0.1)",c=e.headingFont?`'${e.headingFont}'`:void 0,d=e.bodyFont?`'${e.bodyFont}'`:void 0;return r.jsxs("div",{className:"flex aspect-[16/9] w-full flex-col justify-between overflow-hidden rounded-xl border border-[var(--color-border-default)] p-8",style:{background:n},children:[r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsx("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:a,fontFamily:d},children:"Section"}),r.jsx("span",{className:"text-[44px] font-semibold leading-[1.05]",style:{color:i,fontFamily:c},children:"A headline in this style"}),r.jsx("span",{className:"max-w-[62%] text-sm leading-relaxed",style:{color:a,fontFamily:d},children:"Body copy sits at this weight and size, with the muted role carrying supporting lines under it."})]}),r.jsxs("div",{className:"flex items-end justify-between gap-6",children:[r.jsxs("div",{className:"flex items-center gap-4",children:[r.jsx("span",{className:"h-2 w-24 rounded-full",style:{background:l}}),r.jsx("span",{className:"rounded-lg px-3 py-2 text-xs",style:{background:o,color:i,border:`1px solid ${u}`,fontFamily:d},children:"Card"})]}),r.jsx("div",{className:"flex items-center gap-1.5",children:e.palette.slice(0,6).map((p,h)=>r.jsx("span",{className:"h-4 w-4 rounded-sm",style:{background:p,border:`1px solid ${u}`}},`${p}-${h}`))})]})]})}const y0=s.memo(Bg);function b0(){const{AGENT_DOCK_GAP:e,AGENT_WIDTH:t,activeDesignSystemId:n,addDesignSystem:o,addDocSlide:i,addEmptyWeb:a,addSlide:l,agentContentReady:u,attachmentCards:c,attachmentPrefix:d,captureThumbnail:p,chartPngRef:h,chartPrerenderJobs:m,chatMessages:g,clipboardRef:k,commitWireMode:y,conversationId:f,convId:I,copySelection:w,createSlideFromWire:x,ctxMenu:D,deckGenRunning:R,deckIdRef:j,deleteSelection:S,demo:A,designSystemMenuOpen:O,designSystemOpen:T,designSystems:X,docs:L,documentMenuOpen:W,duplicateSelection:H,editingSystem:ae,editingSystemId:ge,editingSystemOrigin:J,editingSystemSwap:ce,flowModalOpen:we,fullscreenEditorOpen:ve,generateDeckFromPlan:oe,getDocumentContent:pe,groupSelectedSlides:K,groups:fe,handleAgentWorkingChange:ie,handleChatCanvasEdit:Y,handleMessageSent:re,handlePlaceCanvasImages:le,handleRemoveAttachmentCard:b,handleSectionUpdate:C,hideWirePreview:z,imageMenuOpen:B,images:M,initialMessage:q,isAgentOpen:ue,isLoadingMessages:ye,messageAfterContent:ee,notes:U,onAgentMinimize:_,onCurrentModelChange:N,onInitialMessageConsumed:Z,onOpenGenerateModal:Q,openDocId:G,openId:se,pasteClipboard:ne,placeAgentDoc:de,placeDoc:F,placeImageFromSrc:$,placeNote:P,placedDocIds:me,presentingGroupId:he,presentingSlideId:Me,projectId:He,promoteDesignSystem:Ee,promotedSystemIds:qe,removeDesignSystem:Ae,removeDocsByDocumentId:jt,resolve
48CanvasImageSrc:kt,revealChapters:Ge,selectAll:Qe,selectedDocIds:ht,selectedGroupId:xt,selectedIds:Xe,selectedImageIds:Ue,selectedNoteIds:_e,selectedWebIds:yt,setActiveDesignSystem:bt,setAgentContentReady:Rt,setChartPrerenderJobs:Nt,setCtxMenu:vt,setDesignSystemMenuOpen:je,setDesignSystemOpen:Oe,setDocThemeOpen:tt,setDocumentMenuOpen:ot,setEditingSystemId:mt,setEditingSystemOrigin:dt,setEditingSystemSwap:$e,setFlowModalOpen:lt,setImageMenuOpen:it,setPresentingGroupId:Dt,setPresentingSlideId:en,setSlidesExcluded:Bt,setViewerWebId:tn,setWireDropMenu:sn,setWireModeMenu:dn,slides:Jt,snapshotChart:Re,turn:Ne,undoDocEdit:Be,ungroupSelectedSlides:ct,updateDesignSystem:De,updateDocByDocumentId:Ve,wireDropMenu:Ct,wireModeMenu:Mt}=Rn();return r.jsxs(r.Fragment,{children:[r.jsx(Ug,{initial:!1,children:ue&&(f||A!=null&&A.agentSlot)?r.jsx(Kn.aside,{initial:{x:t},animate:{x:0},exit:{x:t},transition:{duration:.28,ease:[.22,1,.36,1]},className:"fixed right-0 top-0 z-[95] flex h-full flex-col overflow-hidden bg-white",style:{width:t},onPointerDown:Te=>Te.stopPropagation(),onAnimationComplete:()=>Rt(!0),children:A!=null&&A.agentSlot?A.agentSlot:f?r.jsx(r.Fragment,{children:u?r.jsx(Wm.Provider,{value:kt,children:r.jsx(y0,{conversationId:f,projectId:He??null,activeCanvasId:j.current??void 0,messages:g,isLoadingMessages:ye,initialMessage:q,onInitialMessageConsumed:Z,onMinimize:_,onSectionUpdate:C,onChapterEdited:Ge,onMessageSent:re,onAgentWorkingChange:ie,onCanvasEditDispatch:Y,onPlaceCanvasImages:Te=>{const ut=Ne.placeImagesInFlightRef.current,Tt=(async()=>{ut&&await ut.catch(()=>{}),await le(Te)})();Ne.placeImagesInFlightRef.current=Tt,Tt.finally(()=>{Ne.placeImagesInFlightRef.current===Tt&&(Ne.placeImagesInFlightRef.current=null)})},messageAfterContent:ee,attachmentCards:c,onRemoveCard:b,attachmentPrefix:d,onDocumentAccepted:de,onDocumentUpdated:Ve,getDocumentContent:pe,onDocumentDeleted:jt,onCurrentModelChange:N,canGenerateDeck:!1,isGeneratingDeck:R,onGenerateDeck:Q})}):null}):null},"birtvy-agent"):null}),m.map(Te=>r.jsx("div",{"aria-hidden":!0,style:{position:"fixed",left:-99999,top:0,width:Te.w,height:Te.h,opacity:0,pointerEvents:"none"},children:r.jsx(jo,{config:Te.config,interactive:!1,responsive:!0,onSnapshot:(ut,Tt)=>{h.current.set(Te.slideId,{png:ut,w:Tt.w,h:Tt.h}),Re(Te.slideId,ut,{w:Tt.w,h:Tt.h}),Nt($t=>$t.filter(Pt=>Pt.key!==Te.key))}})},`prechart-${Te.key}`)),r.jsx(cg,{isOpen:we,onClose:()=>lt(!1),onGenerate:Te=>void oe(Te),sources:{notes:U.filter(Te=>{var ut;return(ut=Te.content)==null?void 0:ut.trim()}).map(Te=>({id:String(Te.id),label:Te.content.trim().slice(0,60)})),documents:L.map(Te=>({id:String(Te.id),label:Te.title||"Document"})),images:M.map(Te=>({id:String(Te.id),label:"Image",thumbnailUrl:Te.src})),websites:[]},designSystems:X.map(Te=>{var ut;return{id:Te.id,name:Te.name,palette:(ut=Te.profile)==null?void 0:ut.palette}}),activeDesignSystemId:n}),r.jsx(Ed,{mode:"canvas",activeTool:"select",onToolChange:()=>{},hidden:ve,stageInsetEdge:ue?e:0,stageInsetRight:ue?t:0,multiMixedSelection:Xe.size+ht.size+_e.size+Ue.size+yt.size>1?{count:Xe.size+ht.size+_e.size+Ue.size+yt.size,groupState:xt!=null?"grouped":"groupable",onGroup:K,onUngroup:ct,onDuplicate:H,onDelete:S}:null}),B&&se==null&&G==null?r.jsx(ru,{conversationId:f,onPlace:Te=>{$(Te)},onClose:()=>it(!1)}):null,W&&se==null&&G==null?r.jsx(Xv,{conversationId:I,placedDocumentIds:me,onPlace:Te=>{F(Te.content??"",Te.id||void 0,void 0,Te.title),ot(!1)},onDocumentDeleted:Te=>jt(Te),onClose:()=>ot(!1)}):null,Mt?r.jsx(ab,{client:Mt.client,onPick:Te=>{y(Mt.from,Mt.to,Te),z()},onClose:()=>{dn(null),z()}}):null,Ct?r.jsx(lb,{sourceKind:Ct.from.kind,client:Ct.client,onCreate:Te=>{x(Ct.from,Ct.world,Te),z()},onClose:()=>{sn(null),z()}}):null,D?(()=>{const{world:Te,target:ut}=D,Tt=()=>vt(null);let $t;if(!ut)$t=[{key:"paste",label:"Paste",icon:"Copy",shortcut:"âV",disabled:!k.current,onSelect:()=>ne(Te)},{separator:!0},{key:"add-slide",label:"Add slide",icon:"canvas",onSelect:()=>l(Te)},{key:"add-note",label:"Add note",icon:"sticky-note",onSelect:()=>P(Te)},{key:"add-image",label:"Add image",icon:"image",onSelect:()=>{ot(!1),it(!0)}},{key:"add-doc",label:"Add document",icon:"file-text",onSelect:()=>F("",void 0,Te)},{key:"add-web",label:"Add website",icon:"global",onSelect:()=>a(Te)},{key:"add-doc-slide",label:"Artifact",icon:"canvas",onSelect:()=>i(Te)},{separator:!0},{key:"artifact-theme",label:"Artifact theme",icon:"color-wheel",onSelect:()=>tt(!0)},...X.length?[...X.map(Pt=>({key:`style-${Pt.id}
48`,label:Pt.name,icon:Pt.id===n?"check":"reference-image",onSelect:()=>bt(Pt.id===n?null:Pt.id)}))]:[],{separator:!0},{key:"select-all",label:"Select all",icon:"grid",shortcut:"âA",onSelect:Qe}];else{const Pt=Xe.size+ht.size+_e.size+Ue.size+yt.size>1&&ut.kind==="slide"&&Xe.has(ut.id),un=ht.size+_e.size+Ue.size+yt.size>0,bn=Pt?[...Xe]:ut.kind==="slide"?[ut.id]:[],wn=Jt.filter(Ft=>bn.includes(Ft.id)),Nn=wn.length>0&&wn.every(Ft=>Ft.excludedFromPresentation),Lt=wn.length>1?` ${wn.length} slides`:"";$t=[...ut.kind==="web"?[{key:"open",label:"Open",icon:"arrow-right-up",onSelect:()=>tn(ut.id)},{separator:!0}]:[],...wn.length>0&&!(Pt&&un)?[{key:"exclude",label:(Nn?"Include in presentation":"Exclude from presentation")+Lt,icon:Nn?"eye":"eye-off",onSelect:()=>Bt(bn,!Nn)},{separator:!0}]:[],...ut.kind==="slide"&&Jt.some(Ft=>Ft.id===ut.id&&Ft.docHtml&&Ft.docPrevSource)?[{key:"doc-undo",label:"Undo last artifact edit",icon:"undo",onSelect:()=>Be(ut.id)},{separator:!0}]:[],{key:"duplicate",label:"Duplicate",icon:"Copy",shortcut:"âD",onSelect:H},{key:"copy",label:"Copy",icon:"Copy",shortcut:"âC",onSelect:()=>w()},...ut.kind==="slide"&&f&&Jt.some(Ft=>Ft.id===ut.id&&(Ft.baked||Ft.html))?[{separator:!0},{key:"set-thumbnail",label:"Set as deck thumbnail",icon:"image",onSelect:()=>void p(ut.id)}]:[],{separator:!0},{key:"delete",label:"Delete",icon:"delete-bin-6",shortcut:"â«",danger:!0,onSelect:S}]}return r.jsx(Qv,{position:D.client,items:$t,onClose:Tt})})():null,T?r.jsx(r0,{conversationId:f,onClose:()=>Oe(!1),onSave:o}):null,O&&se==null&&G==null&&ge==null?r.jsx(i0,{systems:X,activeId:n,onEdit:(Te,ut)=>{dt(ut),$e(!1),mt(Te),je(!1)},onToggleActive:Te=>bt(Te===n?null:Te),onNew:()=>{je(!1),Oe(!0)},onPromote:Ee,promotedIds:qe,onClose:()=>je(!1)}):null,ae?r.jsx(m0,{system:ae,origin:J,instant:ce,onUpdate:Te=>De(ae.id,Te),onSaveAsNew:Te=>{$e(!0),mt(o({...Te,sources:ae.sources}))},onDelete:()=>{Ae(ae.id),mt(null)},onClose:()=>mt(null)},ae.id):null,he!=null?(()=>{const{slides:Te,graphyConfigById:ut,docHtmlById:Tt}=Rc(ua(Jt,fe,he),void 0,{includeDocSlides:!0});return Te.length?r.jsx(Oi,{slides:Te,startIndex:0,onClose:()=>Dt(null),renderOverride:($t,Pt)=>{const un=Tt[$t.id];if(un&&Mc(Pt))return r.jsx("iframe",{srcDoc:Vn(un),sandbox:"allow-scripts",title:`Slide ${$t.id}`,style:{width:"100%",height:"100%",border:0,display:"block",pointerEvents:"none"}});const bn=ut[$t.id];return bn&&rn(Pt)?r.jsx(Wi,{config:bn,element:Pt}):null}}):null})():null,Me!=null?(()=>{const Te=Jt.find(Pt=>Pt.id===Me);if(!Te)return null;const{slides:ut,graphyConfigById:Tt,docHtmlById:$t}=Rc([Te],void 0,{includeDocSlides:!0});return ut.length?r.jsx(Oi,{slides:ut,startIndex:0,onClose:()=>en(null),renderOverride:(Pt,un)=>{const bn=$t[Pt.id];if(bn&&Mc(un))return r.jsx("iframe",{srcDoc:Vn(bn),sandbox:"allow-scripts",title:`Slide ${Pt.id}`,style:{width:"100%",height:"100%",border:0,display:"block",pointerEvents:"none"}});const wn=Tt[Pt.id];return wn&&rn(un)?r.jsx(Wi,{config:wn,element:un}):null}}):null})():null]})}function HS({conversationId:e,projectId:t,demo:n}={}){var Zl;const{showToast:o}=Qi(),i=s.useRef(!!n),[a,l]=s.useState(!!(n!=null&&n.agentSlot)),[u,c]=s.useState(!1);s.useEffect(()=>{if(!a){c(!1);return}const E=window.setTimeout(()=>c(!0),360);return()=>window.clearTimeout(E)},[a]);const d=400,p=8,h=280,m="cubic-bezier(0.22, 1, 0.36, 1)",{data:g,isLoading:k}=hp(e),y=s.useRef(g);s.useEffect(()=>{y.current=g},[g]);const f=gp(),{consumePendingMessage:I}=mp(),[w,x]=s.useState(null),D=pp(),R=s.useRef(!1);s.useEffect(()=>{if(!e||!t||R.current)return;R.current=!0;const E=I();E&&(l(!0),f.setQueryData(["planningChatMessages",e],()=>[{id:`optimistic-${Date.now()}`,role:"user",content:E.prompt,createdAt:new Date,actions:[],parts:null,pendingContextRequests:null}])),(async()=>{try{await D.mutateAsync({projectId:t,conversationId:e})}catch(te){console.error("birtvy: conversation registration failed",te)}E&&x({prompt:E.prompt,linearIdentifiers:(E.linearAttachments??[]).map(te=>te.identifier),images:E.imageAttachments.map(te=>te.file),files:(E.fileAttachments??[]).map(te=>te.file),selectedModel:E.selectedModel,enableWebSearch:E.enableWebSearch})})()},[e,t,D,f,I]);const{sections:j,handleSectionUpdate:S}
48=dg(e??""),{model:A}=ug(e??""),O=s.useRef(null),[T,X]=s.useState(!1),[L,W]=s.useState(!1),H=s.useRef({}),ae=s.useRef(new Set),ge=s.useRef(null),[J,ce]=s.useState([]),[we,ve]=s.useState("gemini-3.5-flash"),[oe,pe]=s.useState({}),[K,fe]=s.useState({}),ie=s.useCallback(E=>{pe(te=>{if(!(E in te))return te;const xe={...te};return delete xe[E],xe})},[]),[Y,re]=s.useState(null),[le,b]=s.useState(null),[C,z]=s.useState(null),[B,M]=s.useState(null),q=s.useRef(0),[ue,ye]=s.useState({}),[ee,U]=s.useState({}),[_,N]=s.useState(()=>new Set),Z=J.reduce((E,te)=>te.status==="generating"?E+1:E,0),[Q,G]=s.useState((n==null?void 0:n.deckTitle)??"Untitled"),[se,ne]=s.useState(30),[de,F]=s.useState(!1),$=s.useRef(de);$.current=de;const[P,me]=s.useState(()=>new Set),he=s.useRef(P),Me=s.useRef(!1),He=s.useRef(null),[Ee,qe]=s.useState(null),[Ae,jt]=s.useState(null),kt=(Ae==null?void 0:Ae.id)??null,[Ge,Qe]=s.useState(()=>new Set),[ht,xt]=s.useState(!1),Xe=s.useRef(null),[Ue,_e]=s.useState([]),yt=s.useRef(Ue);s.useEffect(()=>{yt.current=Ue},[Ue]);const[bt,Rt]=s.useState([]),Nt=s.useRef(bt);s.useEffect(()=>{Nt.current=bt},[bt]);const[vt,je]=s.useState([]),Oe=s.useRef(vt);s.useEffect(()=>{Oe.current=vt},[vt]);const[tt,ot]=s.useState(null),mt=s.useRef(null),dt=s.useCallback(()=>{var E;return $y((E=mt.current)==null?void 0:E.profile)},[]),$e=s.useRef(tt);s.useEffect(()=>{$e.current=tt},[tt]);const[lt,it]=s.useState(!1),[Dt,en]=s.useState(!1),[Bt,tn]=s.useState(null),[sn,dn]=s.useState(null),[Jt,Re]=s.useState(!1),Ne=s.useRef(Bt);s.useEffect(()=>{Ne.current=Bt},[Bt]);const[Be,ct]=s.useState(null),[De,Ve]=s.useState(null),[Ct,Mt]=s.useState(null),[Te,ut]=s.useState(null),[Tt,$t]=s.useState(null),Pt=s.useRef(null),un=s.useCallback(E=>{$t(E),Pt.current&&window.clearTimeout(Pt.current),Pt.current=window.setTimeout(()=>$t(null),2500)},[]),[bn,wn]=s.useState(0),[Nn]=s.useState(Tx),[Lt]=s.useState(Br),[Ft,Do]=s.useState(!1),[Bn,Er]=s.useState(!1),[pr,To]=s.useState(0),[mr,Dn]=s.useState(0),[Rr,Yr]=s.useState(!n),[fn,Kr]=s.useState(!n),[Vr,Rs]=s.useState(!1);s.useEffect(()=>{Lt&&bp(fn)},[Lt,fn]);const[qr,Jr]=s.useState(null),Ms=s.useRef(null),[hn,Mn]=s.useState([]),[vn,Zr]=s.useState(()=>new Set),[Qr,v]=s.useState(null),[V,be]=s.useState(null),[ke,Le]=s.useState(null),[Ie,Pe]=s.useState(!1),[ze,et]=s.useState([]),[Ze,ft]=s.useState(()=>new Set),[zt,Et]=s.useState(null),[Vt,Tn]=s.useState([]),Zn=s.useMemo(()=>[...hn.map(E=>({kind:"doc",id:E.id,x:E.x,y:E.y,width:E.width,height:E.height,groupId:E.groupId})),...ze.map(E=>({kind:"note",id:E.id,x:E.x,y:E.y,width:E.width,height:E.height,groupId:E.groupId})),...Vt.map(E=>({kind:"image",id:E.id,x:E.x,y:E.y,width:E.width,height:E.height,groupId:E.groupId}))],[hn,ze,Vt]),wt=s.useMemo(()=>Hy(J,bt,Zn),[J,bt,Zn]),Gt=s.useRef(wt);s.useEffect(()=>{Gt.current=wt},[wt]);const nn=s.useMemo(()=>Uy(wt),[wt]),gr=s.useRef(nn);s.useEffect(()=>{gr.current=nn},[nn]);const[_t,Fn]=s.useState(()=>new Set),[es,pa]=s.useState(null),[zu,Ao]=s.useState(!1),[ts,ma]=s.useState([]),[ns,ga]=s.useState(()=>new Set),[xa,ya]=s.useState(null),[js,Ns]=s.useState(null),[xr,yr]=s.useState(null),[_u,Ou]=s.useState(new Set),[Bu,rs]=s.useState(null),ss=s.useRef(null);s.useEffect(()=>()=>{ss.current&&window.clearTimeout(ss.current)},[]);const Mr=s.useMemo(()=>{const E=Ge.size+vn.size+Ze.size+_t.size;if(E<2)return eo;const te=nt=>{const{kind:We,id:pt}=bs(nt);return We==="slide"?Ge.has(pt):We==="doc"?vn.has(pt):We==="note"?Ze.has(pt):_t.has(pt)},xe=wt.filter(nt=>nt.allItemKeys.length>0&&nt.allItemKeys.every(te));if(!xe.length)return eo;const Se=new Set(xe.map(nt=>nt.id)),Ce=xe.filter(nt=>nt.parentId==null||!Se.has(nt.parentId));return Ce.reduce((nt,We)=>nt+We.allItemKeys.length,0)===E?new Set(Ce.map(nt=>nt.id)):eo},[wt,Ge,vn,Ze,_t]),Fu=s.useMemo(()=>Mr.size===1?[...Mr][0]:null,[Mr]),Gu=s.useRef({attachmentCards:[]}),ba=s.useMemo(()=>{var xe,Se;if(!Ge.size&&!vn.size&&!Ze.size&&!_t.size)return Gu.current;const E=[],te=[];for(const Ce of Ge){const Fe=J.findIndex(pt=>
48pt.id===Ce),nt=`Slide ${Fe>=0?Fe+1:Ce}`;E.push({id:`slide:${Ce}`,kind:"file",fileType:"Slide",name:nt});const We=Fe>=0?J[Fe]:void 0;te.push(We&&!We.baked&&!We.html&&We.status!=="generating"?`${nt} (empty frame â generate into it)`:nt)}for(const Ce of vn){const Fe=hn.find(We=>We.id===Ce);if(!Fe)continue;const nt=((xe=Fe.title)==null?void 0:xe.trim())||"Document";E.push({id:`doc:${Ce}`,kind:"file",fileType:"Doc",name:nt}),te.push(Fe.documentId?`Document "${nt}" · documentId: ${Fe.documentId}`:`Document "${nt}" · NOT LINKED (no documentId â do NOT guess which stored document this is; if the user asks you to change it, say it is not linked to the Library and ask them to re-add it)`)}for(const Ce of Ze){const Fe=ze.find(We=>We.id===Ce);if(!Fe)continue;const nt=((Se=Fe.content)==null?void 0:Se.trim().slice(0,40))||"Note";E.push({id:`note:${Ce}`,kind:"file",fileType:"Note",name:nt}),te.push(`Note "${nt}"`)}for(const Ce of _t){const Fe=Vt.find(nt=>nt.id===Ce);Fe&&(E.push({id:`image:${Ce}`,kind:"image",src:Fe.src,alt:"Canvas image"}),te.push(`Image #${Ce}`))}return{attachmentCards:E,attachmentPrefix:te.length?`[Selected on canvas: ${te.join(", ")}]`:void 0}},[Ge,vn,Ze,_t,J,hn,ze,Vt]),wa=s.useRef(ba);ht||(wa.current=ba);const{attachmentCards:Wu,attachmentPrefix:Hu}=wa.current,Uu=s.useCallback(E=>{var te;return(te=Qn.current.find(xe=>xe.id===E))==null?void 0:te.src},[]),Xu=s.useCallback(()=>x(null),[]),Yu=s.useCallback(()=>l(!1),[]),Ku=s.useCallback(E=>{O.current=E},[]),Vu=s.useCallback(()=>X(!0),[]),qu=s.useCallback(E=>{const{kind:te,id:xe}=bs(E);if(Number.isNaN(xe))return;const Se=Ce=>Cr(Ce,xe);te==="slide"?Qe(Se):te==="doc"?Zr(Se):te==="note"?ft(Se):te==="image"&&Fn(Se)},[]),[va,Ju]=s.useState(null),Zu=s.useMemo(()=>{const E=new Set,te=xe=>{var Ce;if(xe==null)return;const Se=((Ce=bt.find(Fe=>Fe.id===xe))==null?void 0:Ce.parentId)??xe;E.add(Se);for(const Fe of bt)Fe.parentId===Se&&E.add(Fe.id)};return te(Ct),te(Te),te(Tt),L&&te(va),E},[bt,Ct,Te,Tt,L,va]),[$o,ka]=s.useState(null),[Sa,Ds]=s.useState(!1),br=s.useRef(0),[Qu,Ia]=s.useState(null),[ef,Po]=s.useState(null),[tf,Ca]=s.useState(null),wr=s.useRef(0),{zOrder:nf,bringToFront:Lo}=yw(),Ts=s.useRef(null),jr=s.useRef(null),zo=s.useRef(null),rf=s.useRef(null),_o=s.useRef(()=>{}),Ea=s.useRef(null),Ra=s.useRef(()=>{}),Ma=s.useRef(()=>{}),As=s.useRef([]),Oo=s.useRef(!1),$s=s.useRef({x:120,y:120}),Gn=s.useRef(.3),ja=s.useRef(!1),Na=s.useRef(null),Da=s.useRef(null),sf=s.useRef(Yn),Ta=s.useRef(null),Aa=s.useRef(null),Ot=s.useRef([]);s.useEffect(()=>{Ot.current=J},[J]);const{thumbCapturedRef:$a,captureThumbnail:Bo}=Nb({slidesRef:Ot,conversationId:e,projectId:t,queryClient:f,showToast:o}),Ps=s.useRef(Q);s.useEffect(()=>{Ps.current=Q},[Q]);const{docTheme:Pa,setDocTheme:Ls,docThemeRef:La,docThemeOpen:za,setDocThemeOpen:zs}=fb(),_a=s.useRef(Ge);s.useEffect(()=>{_a.current=Ge},[Ge]);const Fo=s.useRef(eo);s.useEffect(()=>{Fo.current=Mr},[Mr]);const _s=s.useRef(Ee);s.useEffect(()=>{_s.current=Ee},[Ee]);const jn=s.useRef([]);s.useEffect(()=>{jn.current=hn},[hn]);const Oa=s.useRef(vn);s.useEffect(()=>{Oa.current=vn},[vn]);const Ba=s.useRef(V);s.useEffect(()=>{Ba.current=V},[V]);const vr=s.useRef([]);s.useEffect(()=>{vr.current=ze},[ze]);const Fa=s.useRef(Ze);s.useEffect(()=>{Fa.current=Ze},[Ze]);const Qn=s.useRef([]);s.useEffect(()=>{Qn.current=Vt},[Vt]);const Ga=s.useRef(_t);s.useEffect(()=>{Ga.current=_t},[_t]);const er=s.useRef([]);s.useEffect(()=>{er.current=ts},[ts]);const Wa=s.useRef(ns);s.useEffect(()=>{Wa.current=ns},[ns]);const{handleRemoteSignal:of,remoteBusyDone:af}=hb({setSlides:ce}),lf=pb(of),{getState:cf,onHydrate:df,recentDocEditsRef:Ha,docsAdoptedRef:uf,onHydratedRef:ff,requestSave:rt,convId:hf,deckIdRef:pf,flushSave:mf}=zb({conversationId:e,demo:n,showToast:o,titleRef:Ps,slidesRef:Ot,docThemeRef:La,docsRef:jn,notesRef:vr,imagesRef:Qn,websRef:er,wiresRef:yt,groupsRef:Nt,agentDocsRef:H,deletedDocIdsRef:ae,designSystemsRef:Oe,activeDesignSystemIdRef:$e,brandKitBindingRef:mt,idRef:wr,fitAllRef:_o,setSlides:ce,setDocs:Mn,setNotes:et,setImages:Tn,setWebs:ma,setWires:_e,setGroups:Rt,setDesignSystems:je,setActiveDesignSystemId:ot,setTitle:G,setDocTheme:Ls,setDeckLoaded:Do,remoteBusyDone:af,handleRemoteSignal:lf}),gf=s.useCallback(E=>{var Se,Ce;const te=Date.now(),xe={id:nm(),name:((Se=E.name)==null?void 0:Se.trim())||"Design system",profile:E.profile,...E.sources?{sources:E.sources}:{},...(Ce=E.examples)!=null&&Ce.length?{examples:E.examples}:{},...E.layout?{layout:E.layout}:{},createdAt:te,updatedAt:te};return je(Fe=>[...Fe,xe]),ot(xe.id),rt(),xe.id},[rt]),Ua=s.useCallback(E=>{ot(E),rt()},[rt]),xf=s.useCallback((E,te)=>{je(xe=>xe.map(Se=>Se.id===E?{...Se,...te,id:Se.id,createdAt:Se.createdAt,updatedAt:Date.now()}:Se)),rt()},[rt]),[Go,Xa]=s.useState(new Set),yf=s.useCallback(E=>{const te=Oe.current.find(xe=>xe.id===E);!te||Go.has(E)||(Xa(xe=>new Set(xe).add(E)),(async()=>{try{const xe=await fetch("/brand-kits-api",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:te.name,profile:JSON.stringify(te.profile),...te.sources?{sources:JSON.stringify(te.sources)}:{}})});if(!xe.ok)throw new Error(`promote failed: ${xe.status}`);o({title:`"${te.name}" saved to your Brand Kits.`,variant:"success"})}catch(xe){console.warn("birtvy: promoting a design system failed",xe),Xa(Se=>{const Ce=new Set(Se);return Ce.delete(E),Ce}),o({title:"Could not save that style to your Brand Kits.",variant:"error"})}})())},[Go,o]),bf=s.useCallback(E=>{je(te=>te.filter(xe=>xe.id!==E)),ot(te=>te===E?null:te),rt()},[rt]),{runGenTitle:Ya,handleAgentWorkingChange:wf}=wb({conversationId:e,projectId:t,queryClient:f,titleRef:Ps,slidesRef:Ot,setTitle:G,requestSave:rt,deckLoaded:Ft,deckHydrated:Bn}),Os=s.useCallback((E,te)=>{To(te>0?E/te:1),Dn(te)},[]),vf=s.useCallback((E,te)=>{($.current||!Br())&&Os(E,te)},[Os]),os=s.useCallback(()=>{Kr(!1),window.setTimeout(()=>Yr(!1),420)},[]);s.useEffect(()=>{const E=window.setTimeout(()=>Rs(!0),Lt?400:650);return()=>window.clearTimeout(E)},[Lt]),s.useEffect(()=>{if(!fn||!Ft||!Vr||mr>0&&pr<1)return;const E=mr===0?Lt?350:550:Lt?120:200,te=window.setTimeout(()=>{const xe=Nn==="webgl"&&(Lt?Ot.current.length>0:Gn.current*100<fr);mr===0&&xe||os()},E);return()=>window.clearTimeout(te)},[fn,Ft,Vr,mr,pr,se,Nn,os,Lt]);const Wo=s.useRef(0);Wo.current=pr,s.useEffect(()=>{if(!Lt){const Ce=window.setTimeout(os,8e3);return()=>window.clearTimeout(Ce)}let E=-1,te=Date.now();const xe=Date.now(),Se=window.setInterval(()=>{const Ce=Date.now();Wo.current!==E&&(E=Wo.current,te=Ce),Ce-xe>=8e3&&Ce-te>=6e3&&(os(),window.clearInterval(Se))},500);return()=>window.clearInterval(Se)},[os,Lt]),Ly({getState:cf,onHydrate:df,requestSave:rt,isEmpty:E=>E.slides.length===0&&E.docs.length===0&&E.notes.length===0&&E.images.length===0&&E.webs.length===0,slides:J,docs:hn,notes:ze,images:Vt,webs:ts,wires:Ue,title:Q,designSystems:vt,activeDesignSystemId:tt,paused:Bt!=null||kt!=null}),s.useEffect(()=>{Bt&&!vt.some(E=>E.id===Bt)&&tn(null)},[Bt,vt]);
48const{apply:Ka,clientToWorld:Bs,syncZoomPct:kf,scheduleLodSync:Sf,pauseRasterDuringGesture:If,fitAll:Va,zoomToCenter:Fs,focusRect:Cf,focusCancelRef:Ef,hover:Rf,hoverKeep:Mf,hoverClearSoon:jf,resyncHoverSoon:Ho}=nb({pan:$s,zoom:Gn,viewportRef:Ts,worldRef:jr,overlayRef:zo,marqueeRectRef:Xe,glDrawRef:Ra,fitAllRef:_o,focusRectRef:Ea,slides:J,slidesRef:Ot,docsRef:jn,notesRef:vr,imagesRef:Qn,websRef:er,setLiveDocIds:me,liveDocIdsRef:he,liveZoomOnRef:Me,liveSyncTimerRef:He,zoomSettleRef:rf,setZoomPct:ne,setLod:F,hoverClearRef:Ms,setHoveredId:Jr,setHoveredDocId:v,setHoveredNoteId:Et,setHoveredImageId:pa,setHoveredWebId:ya,hoveredId:qr,hoveredDocId:Qr,hoveredNoteId:zt,hoveredImageId:es,hoveredWebId:xa,setHoveredGroupId:Mt,groupViewsRef:Gt,itemDragRef:Da}),Nf=s.useCallback(()=>{Qe(E=>E.size?new Set:E),Zr(E=>E.size?new Set:E),ft(E=>E.size?new Set:E),Fn(E=>E.size?new Set:E),ga(E=>E.size?new Set:E)},[]),Df=s.useCallback((E,te)=>{const xe=te==null?void 0:te.getBoundingClientRect();Le(xe?{x:xe.left,y:xe.top,width:xe.width,height:xe.height}:null),be(E)},[]),Nr=s.useCallback((E,te)=>{const xe=Ts.current,Se=te?te.x:xe?(xe.clientWidth/2-$s.current.x)/Gn.current:0,Ce=te?te.y:xe?(xe.clientHeight/2-$s.current.y)/Gn.current:0,Fe=[...Ot.current.map(We=>({x:We.x,y:We.y,width:Ke,height:Je})),...jn.current.map(We=>({x:We.x,y:We.y,width:We.width,height:We.height})),...vr.current.map(We=>({x:We.x,y:We.y,width:We.width,height:We.height})),...Qn.current.map(We=>({x:We.x,y:We.y,width:We.width,height:We.height})),...er.current.map(We=>({x:We.x,y:We.y,width:We.width,height:We.height}))],nt=Am({x:Se,y:Ce},E,Fe);return{x:Math.round(nt.x-E.width/2),y:Math.round(nt.y-E.height/2)}},[]),qa=s.useCallback(E=>{const{x:te,y:xe}=Nr({width:Ke,height:Je},E);ce(Se=>[...Se,{id:wr.current++,x:te,y:xe,status:"empty",prompt:""}]),rt()},[Nr,rt]),on=s.useCallback((E,te)=>{ce(xe=>xe.map(Se=>Se.id===E?{...Se,...te}:Se))},[]),Tf=s.useRef(()=>{}),Ut=fw({setSlides:ce,slidesRef:Ot,setDocs:Mn,docsRef:jn,setNotes:et,notesRef:vr,setImages:Tn,imagesRef:Qn,setWebs:ma,websRef:er,setWires:_e,wiresRef:yt,setGroups:Rt,groupsRef:Nt,setSelectedIds:Qe,selectedIdsRef:_a,setSelectedDocIds:Zr,selectedDocIdsRef:Oa,setSelectedNoteIds:ft,selectedNoteIdsRef:Fa,setSelectedImageIds:Fn,selectedImageIdsRef:Ga,setSelectedWebIds:ga,selectedWebIdsRef:Wa,clearSelection:Nf,idRef:wr,requestSave:rt,flushSave:mf,pan:$s,zoom:Gn,viewportRef:Ts,clientToWorld:Bs,fitAllRef:_o,focusRectRef:Ea,patch:on,placeInView:Nr,bringToFront:Lo,purgeDeletedDocsRef:Tf,showToast:o}),Ja=s.useCallback((E,te)=>{on(E,{docBaked:te}),rt()},[on,rt]);s.useEffect(()=>{if(!Ft)return;let E=null,te=0,xe=!1;const Se=window.setInterval(()=>{if(!E){const pt=Ot.current;if(pt.length===0){++te>13&&window.clearInterval(Se);return}const gt=pt.filter(It=>!It.docHtml&&It.html&&It.status!=="generating");if(Lt&&tc(gt.map(It=>({key:_n("b",It.html),html:It.html}))),nc(gt.map(It=>({id:"b",html:It.html}))),E={flowKeys:gt.map(It=>_n("b",It.html)),docsBaked:pt.filter(It=>It.docHtml&&It.docBaked).map(It=>It.docBaked),total:0},E.total=E.flowKeys.length+E.docsBaked.length,E.total===0){window.clearInterval(Se);return}}const Ce=Hr();let Fe=rc(E.flowKeys);if(Ce!=null){const pt=E.docsBaked.map(gt=>`<style>${Ce}</style>${gt}`);xe||(xe=!0,Lt&&tc(pt.map(gt=>({key:_n("b",gt),html:gt,doc:!0}))),nc(pt.map(gt=>({id:"b",html:gt,doc:!0})))),Fe+=rc(pt.map(gt=>_n("b",gt)))}const nt=$i(),We=Fe>=E.total&&nt===0;Os(We?E.total:Math.min(Fe,E.total-1),E.total),We&&window.clearInterval(Se)},150);return()=>window.clearInterval(Se)},[Ft,Os,Lt]);const Af=s.useCallback((E,te)=>{const xe=te.trim();ce(Se=>Se.map(Ce=>Ce.id===E&&Ce.docHtml?{...Ce,docMeta:{...Ce.docMeta,title:xe||void 0}}:Ce)),rt()},[rt]),$f=s.useCallback((E,te)=>{const xe=te.trim();xe&&(Mn(Se=>Se.map(Ce=>Ce.id===E?{...Ce,title:xe}:Ce)),rt())},[rt]),Pf=s.useCallback((E,te)=>{const xe=te.trim();Tn(Se=>Se.map(Ce=>Ce.id===E?{...Ce,label:xe||void 0}:Ce)),rt()},[rt]),{docWarmActive:Za,docSlideSets:Qa,docWarmHoldIds:Lf,onDocWarmBaked:el,onDocWarmGaveUp:tl}=Tb({slides:J,editingSlideId:Y,deckLoaded:Ft,onDocBaked:Ja}),An=s.useCallback((E,te,xe,Se)=>{var pt,gt,It,rr,qt;const Ce=Ot.current.find(pn=>pn.id===E);if(!Ce)return;const Fe=(Ce.docRev??0)+1,nt={by:xe,...(gt=(pt=Ce.docMeta)==null?void 0:pt.provenance)!=null&>.inboxKey?{inboxKey:Ce.docMeta.provenance.inboxKey}:{},...Se!=null&&Se.inboxKey?{inboxKey:Se.inboxKey}:{},...((rr=(It=Ce.docMeta)==null?void 0:It.provenance)==null?void 0:rr.parent)!=null?{parent:Ce.docMeta.provenance.parent}:{},...(Se==null?void 0:Se.parent)!=null?{parent:Se.parent}:{}},We={at:Date.now(),by:xe,rev:Fe,...Se!=null&&Se.prompt?{prompt:Se.prompt}:{},...(qt=Se==null?void 0:Se.flags)!=null&&qt.length?{flags:Se.flags}:{},...Se!=null&&Se.note?{note:Se.note}:{}};on(E,{docHtml:te,docBaked:void 0,docMeta:yo(te,nt),docRev:Fe,docLog:[...Ce.docLog??[],We].slice(-50),docPrevSource:Ce.docHtml,...xe==="chat"&&(Se!=null&&Se.prompt)?{prompt:Se.prompt}:{}}),rt()},[on,rt]),zf=s.useCallback(E=>{const te=Ot.current.find(xe=>xe.id===E);!(te!=null&&te.docHtml)||!te.docPrevSource||An(E,te.docPrevSource,"undo",{note:"reverted to the previous source"})},[An]),nl=s.useCallback((E,te,xe)=>
48{const Se=Ot.current.find(Ce=>Ce.id===E);!(Se!=null&&Se.docHtml)||te===Se.docHtml||An(E,te,"style",{note:xe})},[An]),rl=s.useCallback(async(E,te)=>{const xe=await Qm(te,async Ce=>{var pt,gt;const Fe=await fetch("/deckgen-image-search-api",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({logoDomain:Ce})});if(!Fe.ok)return null;const We=(gt=(pt=(await Fe.json()).results)==null?void 0:pt[0])==null?void 0:gt.url;return typeof We=="string"&&We?We:null});if(!xe||xe.html===te)return;const Se=Ot.current.find(Ce=>Ce.id===E);!Se||Se.docHtml!==te||Se.status==="generating"||Y===E||An(E,xe.html,"logos",{note:`${xe.resolved} verified logo${xe.resolved===1?"":"s"} placed${xe.removed?`, ${xe.removed} unverified removed`:""}`})},[Y,An]),sl=s.useCallback(E=>{var Ce;const te=/```tokens\s*\n([\s\S]*?)```/.exec(E);if(!te)return 0;const xe={};for(const Fe of te[1].split(` 49`)){const nt=/^\s*(--a-[a-z0-9-]+)\s*:\s*(.+?)\s*;?\s*$/i.exec(Fe);nt&&(xe[nt[1]]=nt[2])}if(Object.keys(xe).length===0)return 0;let Se=0;for(const Fe of Ot.current){if(!Fe.docHtml||((Ce=Fe.docMeta)==null?void 0:Ce.theme)==="own"||Fe.status==="generating"||Y===Fe.id)continue;const nt=Jm(Fe.docHtml,xe);nt!==Fe.docHtml&&(An(Fe.id,nt,"retheme",{note:"theme tokens applied"}),Se+=1)}return Se},[Y,An]),_f=s.useCallback(E=>{const{x:te,y:xe}=Nr({width:Ke,height:Je},E);ce(Se=>[...Se,{id:wr.current++,x:te,y:xe,status:"done",prompt:"",docHtml:Yd()}]),rt()},[Nr,rt]);Pb({store:Ut,conversationId:e,deckLoaded:Ft,editingSlideId:Y,writeDocSource:An,resolveDocLogos:rl});const{generateDocSlide:ol}
49=lw({store:Ut,editingSlideId:Y,setEditingSlideId:re,setEditStatus:b,setEditCodeTail:z,setEditStartedAt:M,editTailAtRef:q,docThemeRef:La,designSystemsRef:Oe,activeDesignSystemIdRef:$e,brandKitBindingRef:mt,writeDocSource:An,resolveDocLogos:rl}),[Of,Uo]=s.useState([]),Bf=s.useRef(0),Gs=s.useCallback((E,te)=>{if(te.length===0)return;const xe=te.map(Ce=>({key:++Bf.current,slideId:E,rect:Ce.rect,nodeIdx:Ce.nodeIdx}));Uo(Ce=>[...Ce,...xe]);const Se=new Set(xe.map(Ce=>Ce.key));window.setTimeout(()=>Uo(Ce=>Ce.filter(Fe=>!Se.has(Fe.key))),1200)},[]),Ff=s.useRef(new Map);s.useEffect(()=>{var xe,Se;const E=Ff.current;if(E.size===0&&!J.some(Ce=>Ce.status==="generating"))return;const te=new Map;for(const Ce of J){if(Ce.status!=="generating"||!Ce.html)continue;const Fe=(xe=jr.current)==null?void 0:xe.querySelector(`[data-slide-id="${Ce.id}"]`),nt=Fe==null?void 0:Fe.getBoundingClientRect();if(!Fe||!nt||nt.width===0)continue;const We=nt.width/Ke,pt=Array.from(Fe.querySelectorAll("[data-el]:not([data-bg-layer])")).filter(qt=>!qt.querySelector("[data-el]")),gt=qt=>{let pn=qt.getBoundingClientRect();if(qt.matches('[data-el="text"]')){const ls=document.createRange();ls.selectNodeContents(qt);const St=ls.getBoundingClientRect();St.width>0&&St.height>0&&(pn=St)}return pn.width<4||pn.height<4?null:{x:(pn.left-nt.left)/We,y:(pn.top-nt.top)/We,width:pn.width/We,height:pn.height/We,radius:parseFloat(qt.style.borderRadius)||8}};te.set(Ce.id,qt=>pt[qt]?gt(pt[qt]):null);const It=E.get(Ce.id)??{flashed:0,lastBox:null},rr=[];for(let qt=It.flashed;qt<pt.length-1;qt++){const pn=gt(pt[qt]);pn&&rr.push({rect:pn,nodeIdx:qt})}It.flashed=Math.max(It.flashed,pt.length-1),It.lastBox=pt.length>0?gt(pt[pt.length-1])??It.lastBox:It.lastBox,E.set(Ce.id,It),rr.length&&Gs(Ce.id,rr)}te.size&&Uo(Ce=>{let Fe=!1;const nt=Ce.map(We=>{var gt;if(We.nodeIdx==null)return We;const pt=(gt=te.get(We.slideId))==null?void 0:gt(We.nodeIdx);return!pt||pt.x===We.rect.x&&pt.y===We.rect.y&&pt.width===We.rect.width&&pt.height===We.rect.height?We:(Fe=!0,{...We,rect:pt})});return Fe?nt:Ce});for(const[Ce,Fe]of E)((Se=J.find(nt=>nt.id===Ce))==null?void 0:Se.status)!=="generating"&&(Fe.lastBox&&Gs(Ce,[{rect:Fe.lastBox}]),E.delete(Ce))},[J,Gs]);const is=s.useCallback(async(E,te)=>{try{const xe=await fetch("/birtvy-graphy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:te})}),Se=await xe.json();if(!xe.ok||!Se.config)throw new Error(Se.error||"Graphy generation failed");on(E,{graphyConfig:Se.config}),rt();try{const Ce=await fetch("/birtvy-graphy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:te,refineConfig:Se.config})}),Fe=await Ce.json();Ce.ok&&Fe.config&&(on(E,{graphyConfig:Fe.config}),rt())}catch(Ce){console.warn("birtvy: chart refine (phase 2) failed for slide",E,Ce)}}catch(xe){console.warn("birtvy: chart â Graphy failed for slide",E,xe)}},[on,rt]),{turn:Dr,handleMessageSent:Gf,resolveChatEditTarget:Wf,chatEditActivity:il,setChatEditActivity:al,persistedReceipts:ll,persistReceipt:cl}=Zb({store:Ut,openIdRef:_s,conversationId:e,chatMessagesRef:y}),Hf=s.useMemo(()=>{var nt;const E=g??[],te=new Set(E.map(We=>We.id)),xe=(nt=[...E].reverse().find(We=>We.role==="assistant"))==null?void 0:nt.id,Se={},Ce=new Set;for(const{anchor:We,state:pt}of ll){const gt=E.find(It=>It.role==="assistant"&&!Ce.has(It.id)&&(It.content??"").trim().startsWith(We));gt&&(Ce.add(gt.id),Se[gt.id]=r.jsx(ki,{state:pt,persisted:!0},`p-${gt.id}`))}const Fe=Object.entries(il);return Fe.forEach(([We,pt],gt)=>{if(te.has(We)){Se[We]=r.jsx(ki,{state:pt},We);return}gt===Fe.length-1&&xe&&(Se[xe]=r.jsx(ki,{state:pt},xe))}),Se},[il,g,ll]),Uf=s.useRef(new Map),dl=600*1e3,ul=s.useCallback((E,te,xe)=>
49{const Se=da(te,xe,void 0,dt());if(Se){on(E,{graphyConfig:Se}),rt();return}is(E,xe?`${te} 50 51Render it as a ${xe} chart.`:te)},[dt,on,rt,is]),as=s.useCallback(E=>{if(!E)return;const te=()=>{try{Fr(_n("b",E),E,512)}catch{}};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(te,{timeout:2e3}):setTimeout(te,300)},[]),fl=s.useCallback((E,te,xe)=>{var pt;const Se=Ot.current.find(gt=>gt.id===E),Ce=(pt=Se==null?void 0:Se.baked)==null?void 0:pt.elements.find(rn);if(!(Se!=null&&Se.baked)||!Ce||Ce.fillImage)return;const Fe=Se.baked.elements.map(gt=>{if(!rn(gt))return gt;const It=xe.w>0?Math.max(8,Math.round(gt.width*xe.h/xe.w)):gt.height;return{...gt,height:It,fillImage:te,shapeFillMode:"image",imageFit:"fill"}}),nt={...Se.baked,elements:Fe},We=gn(nt,E);on(E,{baked:nt,html:We}),as(We),rt()},[on,as,rt]),{chartPngRef:Ws,chartPrerenderedRef:Xf,chartPrerenderJobs:Yf,setChartPrerenderJobs:hl,startChartPrerender:pl}=ow({deckChartSeries:dt}),{conceptsSlideId:Xo,setConceptsSlideId:ml,conceptsLoading:gl,concepts:Hs,conceptsError:xl,conceptsAnchor:Yo,conceptPicking:yl,conceptsMoreLoading:bl,conceptsExhausted:wl,openConcepts:vl,loadMoreConcepts:kl,pickConcept:Sl}=Jb({slidesRef:Ot,conversationId:e,patch:on,prebakeThumb:as,requestSave:rt}),{generateSlide:Il,stopGenerate:Kf}=sw({store:Ut,turn:Dr,slideGenCreativity:ue,slideGenTextDensity:ee,designSystemsRef:Oe,activeDesignSystemIdRef:$e,brandKitBindingRef:mt,chartPngRef:Ws,chartPrerenderedRef:Xf,setChartPrerenderJobs:hl,startChartPrerender:pl,fillChart:ul,runGraphyForChart:is}),{editSlide:Cl,chatEditSlideId:Vf}
51=cw({store:Ut,turn:Dr,model:we,editingSlideId:Y,setEditingSlideId:re,setEditStatus:b,clearEditBarValue:ie,designSystemsRef:Oe,activeDesignSystemIdRef:$e,brandKitBindingRef:mt,chartPngRef:Ws,deckChartSeries:dt,runGraphyForChart:is,pushEditFlashes:Gs,setChatEditActivity:al,persistReceipt:cl});s.useEffect(()=>{var ls;if(!Ft||!Bn||!e)return;const E=_i(j);if(!E.length)return;const te=jn.current,xe=[],Se=new Map,Ce=Object.values(H.current).map(St=>te.find(mn=>mn.id===St)).filter(St=>!!St),Fe=Ot.current.length?Math.min(...Ot.current.map(St=>St.y)):0,nt=Ce.length?Math.min(...Ce.map(St=>St.y)):Fe-Cn-200,We=Ce.length?Math.min(...Ce.map(St=>St.x)):0,pt=En+120,gt=St=>H.current[St]==null,It=E.findIndex(St=>gt(St.key)),rr=E.reduce((St,mn,$r)=>gt(mn.key)?St:$r,-1),qt=It>=0&&It<rr;let pn=Ce.length?Math.max(...Ce.map(St=>St.x+St.width))+120:0;if(E.forEach((St,mn)=>{const $r=H.current[St.key];if($r!=null){const $n=te.find(fp=>fp.id===$r),Ql=qt&&(($n==null?void 0:$n.x)!==We+mn*pt||($n==null?void 0:$n.y)!==nt);$n&&($n.content!==St.content||$n.title!==St.title||Ql)&&Se.set($n.id,{title:St.title,content:St.content,...Ql?{x:We+mn*pt,y:nt}:{}});return}const Ks=wr.current++;H.current[St.key]=Ks;const kn=qt?We+mn*pt:pn;qt||(pn+=pt),xe.push({id:Ks,x:kn,y:nt,width:En,height:Cn,content:St.content,title:St.title})}),!(!xe.length&&!Se.size)&&(Mn(St=>[...St.map(mn=>Se.has(mn.id)?{...mn,...Se.get(mn.id)}:mn),...xe]),rt(),xe.length)){const St=Math.min(...xe.map(kn=>kn.x)),mn=Math.min(...xe.map(kn=>kn.y)),$r=Math.max(...xe.map(kn=>kn.x+kn.width)),Ks=Math.max(...xe.map(kn=>kn.y+kn.height));(ls=ge.current)==null||ls.call(ge,xe.map(kn=>kn.id),{x:St,y:mn,w:$r-St,h:Ks-mn})}},[j,Ft,Bn,e,rt]);const Us=s.useRef(!1),Ko=s.useRef(void 0);s.useEffect(()=>()=>{Ko.current!=null&&window.clearTimeout(Ko.current)},[]),s.useEffect(()=>{if(!e||!Bn||Us.current||$a.current||!J.some(te=>(te.baked||te.html)&&te.status!=="generating"))return;Us.current=!0;const E=window;Ko.current=window.setTimeout(()=>{const te=()=>{const xe=Ot.current.find(Se=>(Se.baked||Se.html)&&Se.status!=="generating");if(!xe){Us.current=!1;return}Bo(xe.id,{auto:!0}).then(()=>{$a.current||(Us.current=!1)}),Ya()};typeof E.requestIdleCallback=="function"?E.requestIdleCallback(te,{timeout:4e3}):te()},1500)},[J,Bn,e,Bo,Ya]);const El=s.useCallback((E,te,xe)=>
51Zy(E,te,xe,{slides:Ot.current,docs:jn.current,notes:vr.current,images:Qn.current,webs:er.current}),[]),qf=s.useCallback(E=>Qy(E,yt.current,jn.current,Ot.current),[]),{generateDeckFromPlan:Jf,generateVariantsFromToolbar:Zf}=rw({store:Ut,sections:j,planningModel:A,liveModelRef:O,model:we,agentDocsRef:H,titleRef:Ps,designSystemsRef:Oe,activeDesignSystemIdRef:$e,setActiveDesignSystem:Ua,brandKitBindingRef:mt,deckGenRunning:L,setDeckGenRunning:W,setGenDeckGid:Ju,setFlowModalOpen:X,flashGroup:un,fillChart:ul,startChartPrerender:pl,chartPngRef:Ws,runGraphyForChart:is,generateSlide:Il,generateDocSlide:ol,findClearRowY:El,slideGenCreativity:ue}),{handleChatCanvasEdit:Qf}=dw({store:Ut,turn:Dr,model:we,editingSlideId:Y,slideGenCreativity:ue,setSlideGenCreativity:ye,setSlideGenTextDensity:U,setRedesigningIds:N,setChatEditActivity:al,persistReceipt:cl,resolveChatEditTarget:Wf,editSlide:Cl,generateSlide:Il,findClearRowY:El,slidesFedByDocs:qf,openIdRef:_s,setOpenId:qe,chatMessagesRef:y,recentDocEditsRef:Ha,DOC_EDIT_MEMORY_MS:dl}),eh=s.useCallback(E=>{const te=Ot.current.find(Fe=>Fe.id===E);if(!te)return;const xe=wr.current++,Se=te.baked?Bd(te.baked,xe):void 0,Ce={...te,id:xe,x:te.x+64,y:te.y+64,baked:Se,html:Se?gn(Se,xe):te.html};ce(Fe=>[...Fe,Ce]),Qe(new Set([xe])),Lo([`slide:${xe}`]),rt()},[rt,Lo]),th=s.useCallback(E=>{ce(te=>te.filter(xe=>xe.id!==E)),Qe(te=>Cr(te,E)),Jr(te=>te===E?null:te),qe(te=>te===E?null:te),rt()},[rt]),nh=s.useCallback((E,te)=>{ce(xe=>xe.map(Se=>Se.id===E?{...Se,prompt:te}:Se)),Ot.current=Ot.current.map(xe=>xe.id===E?{...xe,prompt:te}:xe),rt()},[rt]),rh=s.useCallback(E=>{ce(te=>te.map(xe=>xe.id===E?{...xe,excludedFromPresentation:!xe.excludedFromPresentation}:xe)),rt()},[rt]),sh=s.useCallback((E,te)=>{if(E.length===0)return;const xe=new Set(E);ce(Se=>Se.map(Ce=>xe.has(Ce.id)?{...Ce,excludedFromPresentation:te}:Ce)),rt()},[rt]),{placeDoc:Vo,docDirtyRef:Rl,updateDoc:Ml,duplicateDoc:oh,deleteDoc:ih,removeDocsByDocumentId:ah}=hw({store:Ut,conversationId:e,deletedDocIdsRef:ae,setHoveredDocId:v,setOpenDocId:be}),{placeNote:Xs,updateNoteContent:lh,updateNoteColor:ch,updateNoteHeight:dh,duplicateNote:uh,deleteNote:fh}=pw({store:Ut,setHoveredNoteId:Et}),{placeImage:jl,placeImageFromSrc:qo,duplicateImage:hh,deleteImage:ph,setImageStyleStrength:mh}=mw({store:Ut,setHoveredImageId:pa}),{handlePlaceCanvasImages:gh}=bw({store:Ut,conversationId:e,placeImage:jl,flashGroup:un,placedLogoByUrlRef:Uf,turnPlacedImageIdsRef:Dr.turnPlacedImageIdsRef,turnSkippedLogosRef:Dr.turnSkippedLogosRef}),{createWebCard:xh,addEmptyWeb:Nl,updateWeb:yh,updateWebHeight:bh,deleteWeb:wh,duplicateWeb:vh,addBrandTiles:kh}=$x({store:Ut,setHoveredWebId:ya,setViewerWebId:Ns}),tr=Ox({conversationId:e,createWebCard:xh,updateWeb:yh,getWebs:()=>er.current,addBrandTiles:kh,findSpaceFor:Nr,addNoteAt:(E,te)=>Xs(te,E),addDocAt:(E,te,xe)=>Vo(E,void 0,te,xe),addImageAt:(E,te,xe,Se,Ce)=>{const Fe=jl(E,te,xe,Se);Ce&&Tn(nt=>nt.map(We=>We.id===Fe?{...We,sourceUrl:Ce}:We))}}),{ingestUrlIntoCard:Sh}=tr,{placeExternalItems:Jo}=gw({store:Ut,placeImageFromSrc:qo,placeDoc:Vo,placeNote:Xs,placeWebFromUrl:tr.placeWebFromUrl}),Wn=s.useCallback((E,te)=>{rs({id:E,text:te}),ss.current&&window.clearTimeout(ss.current),ss.current=window.setTimeout(()=>rs(null),1200)},[]),Ih=s.useCallback(async E=>{if(!xr){yr({id:E.id,kind:"images"}),rs(null);try{const te=await tr.extractImagesFromWeb(E);Wn(E.id,te>0?`Added ${te} image${te===1?"":"s"}`:"No images ⥠400px found")}catch{Wn(E.id,"Couldnât extract images")}finally{yr(null)}}},[xr,tr,Wn]),Ch=s.useCallback(async E=>{if(!xr){yr({id:E.id,kind:"text"}),rs(null);try{const te=await tr.extractTextFromWeb(E);Wn(E.id,te==="doc"?"Added a document":te==="note"?"Added a note":"No text found")}catch{Wn(E.id,"Couldnât extract text")}finally{yr(null)}}},[xr,tr,Wn]),Eh=s.useCallback(async E=>{if(!xr){yr({id:E.id,kind:"style"}),rs(null);try{const te=await tr.extractStyleFromWeb(E);Wn(E.id,te?"Added brand style":"No style found")}catch{Wn(E.id,"Couldnât extract style")}finally{yr(null)}}},[xr,tr,Wn]),{clipboardRef:Dl,placeClones:Tl,itemsForIds:Al,copySelection:$l,pasteClipboard:Pl,duplicateSelection:Ll,deleteSelection:zl,selectAll:_l,selectForContext:Ol}=xw({store:Ut,groupViewsRef:Gt,hiddenMemberKeysRef:gr,setOpenId:qe,setOpenD
51ocId:be,setViewerWebId:Ns});kw({store:Ut,slides:J,docs:hn,notes:ze,images:Vt,groups:bt});const{arrangeDeckRows:Rh,groupSelectedSlides:Bl,ungroupSelectedSlides:Fl,renameGroup:Mh,setGroupCols:jh,arrangeGroup:Nh,toggleGroupSnap:Dh,resizeGroup:Th,toggleGroupCollapsed:Ah,duplicateGroup:$h,deleteGroup:Ph}=ww({store:Ut,groupViewsRef:Gt,selectedGroupIdsRef:Fo,flashGroup:un,itemsForIds:Al,placeClones:Tl}),{exportGroup:Lh,exportSlide:zh,exportingGroupId:_h,exportingSlideId:Oh,exportLiveIds:Tr}=vw({store:Ut,snapshotChart:fl}),{revealingDocIds:Bh,revealDocsInPlace:Fh,revealDocs:Gl}=Ab({focusRect:Cf});Sw({store:Ut,demo:n,demoRef:i,isAgentOpen:a,AGENT_WIDTH:d,apply:Ka,setZoomPct:ne,setLod:F,focusCancelRef:Ef,revealDocsInPlace:Fh,setWebBusy:yr,setDemoBusyKinds:Ou}),ge.current=Gl;const{placeAgentDoc:Gh,updateDocByDocumentId:Wh,getDocumentContent:Hh,revealChapters:Uh}=$b({deletedDocIdsRef:ae,agentDocsRef:H,docsRef:jn,idRef:wr,docDirtyRef:Rl,recentDocEditsRef:Ha,DOC_EDIT_MEMORY_MS:dl,setDocs:Mn,requestSave:rt,showToast:o,revealDocs:Gl}),{flushDocToLibrary:Wl,syncDocsWithLibrary:Hl}=Lb({conversationId:e,docsRef:jn,docDirtyRef:Rl,docsAdoptedRef:uf,agentDocsRef:H,setDocs:Mn,requestSave:rt,showToast:o}),Xh=s.useCallback(()=>{Er(!0),Hl()},[Hl]);ff.current=Xh;const Ul=s.useMemo(()=>({getZoom:()=>Gn.current,zoomIn:()=>Fs(Gn.current*1.15),zoomOut:()=>Fs(Gn.current/1.15),zoomToFit:()=>Va(),setZoom:E=>Fs(E),frameWorldRect:()=>!1}),[Fs,Va]),Yh=s.useCallback(E=>{const te=Ot.current.find(Se=>Se.id===E);if(!te||te.status==="generating")return;if(te.docHtml){jt({id:E,html:te.docHtml});return}if(te.baked||te.graphyConfig){qe(E);return}const xe={background:"#ffffff",elements:[]};on(E,{baked:xe,html:gn(xe,E),status:"done"}),qe(E),rt()},[on,rt]),Xl=s.useCallback(()=>{rt()},[rt]),Yl=s.useCallback(()=>{qe(E=>{if(E!=null){const te=Ot.current.find(xe=>xe.id===E);if(te!=null&&te.baked){const xe=gn(te.baked,E);on(E,{html:xe}),as(xe)}}return null}),rt()},[on,as,rt]);db({store:Ut,demoRef:i,spaceRef:ja,overlayRef:zo,marqueeRectRef:Xe,marqueeSessionRef:Na,setMarqueeActive:xt,hiddenMemberKeysRef:gr,lodRef:$,setLod:F,apply:Ka,syncZoomPct:kf,scheduleLodSync:Sf,pauseRasterDuringGesture:If,resyncHoverSoon:Ho});const Zo=s.useCallback(E=>tb(E,{slides:Ot.current,docs:jn.current,notes:vr.current,images:Qn.current,webs:er.current}),[]),{deleteWire:Kh,commitWireMode:Vh,createSlideFromWire:qh,portSidesFor:Jh}=eb({store:Ut,wires:Ue,rectForRef:Zo,setWireDropMenu:Po}),{hideWirePreview:Zh,startWire:Qh,startImageResize:ep}=ub({store:Ut,worldRef:jr,spaceRef:ja,marqueeSessionRef:Na,openIdRef:_s,openDocIdRef:Ba,editingSystemIdRef:Ne,rectForRef:Zo,setWireDropMenu:Po,setWireModeMenu:Ia,clipboardRef:Dl,copySelection:$l,pasteClipboard:Pl,duplicateSelection:Ll,selectAll:_l,deleteSelection:zl,groupSelectedSlides:Bl,ungroupSelectedSlides:Fl,placeExternalItems:Jo}),{onCardPointerDown:tp,onDocPointerDown:np,onNotePointerDown:rp,onImagePointerDown:sp,onWebPointerDown:op,onGroupHeaderPointerDown:ip}=cb({store:Ut,itemDragRef:Da,snapSessionRef:sf,snapVGuideRef:Ta,snapHGuideRef:Aa,worldRef:jr,groupViewsRef:Gt,selectedGroupIdsRef:Fo,setDraggingGroupId:ut,rectForRef:Zo,placeClones:Tl,itemsForIds:Al,arrangeDeckRows:Rh,glActiveRef:Oo,glQuadIdsRef:As,glDragQuadsRef:Ma});s.useEffect(()=>{let E=!1;return sc(()=>{E||(E=!0,requestAnimationFrame(()=>{E=!1,wn(te=>te+1)}))}),()=>sc(null)},[]);const Kl=s.useCallback(E=>{G(E),rt()},[rt]),nr=Ee!=null?J.find(E=>E.id===Ee):void 0,Ys=kt!=null?J.find(E=>E.id===kt):void 0,Qo=Ee!=null||V!=null||kt!=null||js!=null,Vl=Ge.size+vn.size+Ze.size+_t.size+ns.size,ap=Vl===1,ql=se>=Dx,ei=!!n&&!n.agentSlot;s.useEffect(()=>{Ho()},[J,Ee,ql,Ho]);const Ar=Nn==="webgl",ti=Ar&&(Lt||de);Oo.current=ti,uw({slidesRef:Ot,groups:bt,hiddenMemberKeys:nn,images:Vt,zoom:Gn,zoomPct:se,lod:de,glMode:Ar,glActiveRef:Oo,glQuadIdsRef:As,farNext:Lt,renderer:Nn,liveDocIdsRef:he});const Jl=s.useMemo(()=>{const te=Ar&&(Lt?de:!0)?J.filter(Ce=>Ce.baked&&Ce.html):[],xe=te.map(Ce=>({kind:"slide",id:Ce.id})),Se=te.map(Ce=>({x:Ce.x,y:Ce.y,w:Ke,h:Je,html:Ce.html}));if(Ar&&Lt){const Ce=`<style>${Hr()??""}</style>`;for(const Fe of J)!Fe.docHtml||!Fe.docBaked||Fe.id===Y||(xe.push({kind:"slide",id:Fe.id}),Se.push({x:Fe.x,y:Fe.y,w:Ke,h:Je,html:Ce+Fe.docBaked,doc:!0}));if(de)for(const Fe of Vt)nn.has(Ye("image",Fe.id))||(xe.push({kind:"image",id:Fe.id}),Se.push({x:Fe.x,y:Fe.y,w:Fe.width,h:Fe.height,kind:"image",src:Fe.src}))}return As.current=xe,Se}
51,[J,Ar,Lt,Lt?de:null,Lt?Vt:null,Lt?nn:null,Lt?Y:null,Lt?bn:null]),lp=s.useMemo(()=>{if(!Lt||P.size===0&&!Tr)return null;const E=new Set;return As.current.forEach((te,xe)=>{te.kind==="slide"&&(P.has(te.id)||Tr!=null&&Tr.has(te.id))&&E.add(xe)}),E.size>0?E:null},[Jl,Lt,P,Tr]),cp=s.useMemo(()=>new Set(hn.map(E=>E.documentId).filter(E=>!!E)),[hn]),ni=V!=null?hn.find(E=>E.id===V):void 0,dp=Bt!=null?vt.find(E=>E.id===Bt):void 0,up={conversationId:e,projectId:t,demo:n,store:Ut,isAgentOpen:a,setIsAgentOpen:l,agentContentReady:u,setAgentContentReady:c,AGENT_WIDTH:d,AGENT_DOCK_GAP:p,AGENT_DOCK_MS:h,AGENT_DOCK_EASE:m,chatMessages:g,isLoadingMessages:k,initialMessage:w,onInitialMessageConsumed:Xu,onAgentMinimize:Yu,onCurrentModelChange:Ku,onOpenGenerateModal:Vu,handleSectionUpdate:S,handleMessageSent:Gf,handleAgentWorkingChange:wf,handleChatCanvasEdit:Qf,handlePlaceCanvasImages:gh,handleRemoveAttachmentCard:qu,attachmentCards:Wu,attachmentPrefix:Hu,messageAfterContent:Hf,resolveCanvasImageSrc:Uu,turn:Dr,chatEditSlideId:Vf,title:Q,onRename:Kl,convId:hf,deckIdRef:pf,captureThumbnail:Bo,loaderMounted:Rr,loaderVisible:fn,deckLoaded:Ft,bakeProgress:pr,slides:J,docs:hn,notes:ze,images:Vt,webs:ts,wires:Ue,groups:bt,groupViews:wt,hiddenMemberKeys:nn,zOrder:nf,placedDocIds:cp,selectedIds:Ge,selectedDocIds:vn,selectedNoteIds:Ze,selectedImageIds:_t,selectedWebIds:ns,selectedGroupIds:Mr,selectedGroupId:Fu,totalSelected:Vl,singleSelection:ap,marqueeActive:ht,marqueeRectRef:Xe,hoveredId:qr,hoveredDocId:Qr,hoveredNoteId:zt,hoveredImageId:es,hoveredWebId:xa,hover:Rf,hoverKeep:Mf,hoverClearSoon:jf,zoomPct:se,zoomControls:Ul,chromeVisible:ql,demoChrome:ei,demoBusyKinds:_u,lod:de,farNext:Lt,glMode:Ar,glActive:ti,glQuads:Jl,glSkipIndices:lp,glDrawRef:Ra,glDragQuadsRef:Ma,onGlProgress:vf,thumbTick:bn,worldRef:jr,overlayRef:zo,snapVGuideRef:Ta,snapHGuideRef:Aa,dragDepthRef:br,dropActive:Sa,setDropActive:Ds,onCardPointerDown:tp,onDocPointerDown:np,onNotePointerDown:rp,onImagePointerDown:sp,onWebPointerDown:op,onGroupHeaderPointerDown:ip,startImageResize:ep,portSidesFor:Jh,startWire:Qh,hideWirePreview:Zh,deleteWire:Kh,commitWireMode:Vh,createSlideFromWire:qh,wireModeMenu:Qu,setWireModeMenu:Ia,wireDropMenu:ef,setWireDropMenu:Po,ctxMenu:tf,setCtxMenu:Ca,clipboardRef:Dl,copySelection:$l,pasteClipboard:Pl,duplicateSelection:Ll,deleteSelection:zl,selectAll:_l,selectForContext:Ol,addSlide:qa,duplicateSlide:eh,deleteSlide:th,setSlidePrompt:nh,toggleSlideExcluded:rh,setSlidesExcluded:sh,openSlide:Yh,openId:Ee,setOpenId:qe,openSlideRecord:nr,onEditorChange:Xl,closeEditor:Yl,fullscreenEditorOpen:Qo,model:we,setModel:ve,generateDeckFromPlan:Jf,generateVariantsFromToolbar:Zf,stopGenerate:Kf,deckGenRunning:L,generatingCount:Z,redesigningIds:_,slideGenCreativity:ue,setSlideGenCreativity:ye,slideGenTextDensity:ee,setSlideGenTextDensity:U,flowModalOpen:T,setFlowModalOpen:X,editBarValues:oe,setEditBarValues:pe,clearEditBarValue:ie,barAttachments:K,setBarAttachments:fe,editSlide:Cl,editingSlideId:Y,editStatus:le,editCodeTail:C,editStartedAt:B,editFlashes:Of,openConcepts:vl,conceptsSlideId:Xo,setConceptsSlideId:ml,conceptsLoading:gl,concepts:Hs,conceptsError:xl,conceptsAnchor:Yo,conceptPicking:yl,conceptsMoreLoading:bl,conceptsExhausted:wl,loadMoreConcepts:kl,pickConcept:Sl,snapshotChart:fl,chartPngRef:Ws,chartPrerenderJobs:Yf,setChartPrerenderJobs:hl,placeDoc:Vo,updateDoc:Ml,duplicateDoc:oh,deleteDoc:ih,removeDocsByDocumentId:ah,openDoc:Df,openDocId:V,setOpenDocId:be,openDocOrigin:ke,openDocRecord:ni,documentMenuOpen:Ie,setDocumentMenuOpen:Pe,revealingDocIds:Bh,revealedGroupIds:Zu,flushDocToLibrary:Wl,placeAgentDoc:Gh,updateDocByDocumentId:Wh,renameDoc:$f,renameImage:Pf,getDocumentContent:Hh,revealChapters:Uh,addDocSlide:_f,generateDocSlide:ol,undoDocEdit:zf,commitArtifactSource:nl,openArtifact:Ae,setOpenArtifact:jt,openArtifactRecord:Ys,onDocBaked:Ja,docWarmActive:Za,docSlideSets:Qa,docWarmHoldIds:Lf,onDocWarmBaked:el,onDocWarmGaveUp:tl,liveDocIds:P,docTheme:Pa,setDocTheme:Ls,renameArtifact:Af,docThemeOpen:za,setDocThemeOpen:zs,applyThemeTokens:sl,placeNote:Xs,updateNoteContent:lh,updateNoteColor:ch,updateNoteHeight:dh,duplicateNote:uh,deleteNote:fh,placeImageFromSrc:qo,duplicateImage:hh,deleteImage:ph,setImageStyleStrength:mh,imageMenuOpen:zu,setImageMenuOpen:Ao,viewerImageId:$o,setViewerImageId:ka,placeExternalItems:Jo,addEmptyWeb:Nl,updateWebHe
51ight:bh,duplicateWeb:vh,deleteWeb:wh,ingestUrlIntoCard:Sh,viewerWebId:js,setViewerWebId:Ns,webBusy:xr,webResult:Bu,handleWebExtractText:Ch,handleWebExtractImages:Ih,handleWebExtractStyle:Eh,groupSelectedSlides:Bl,ungroupSelectedSlides:Fl,renameGroup:Mh,setGroupCols:jh,arrangeGroup:Nh,toggleGroupSnap:Dh,resizeGroup:Th,toggleGroupCollapsed:Ah,duplicateGroup:$h,deleteGroup:Ph,exportGroup:Lh,exportSlide:zh,exportingSlideId:Oh,exportingGroupId:_h,exportLiveIds:Tr,presentingGroupId:Be,setPresentingGroupId:ct,presentingSlideId:De,setPresentingSlideId:Ve,designSystems:vt,activeDesignSystemId:tt,setActiveDesignSystem:Ua,addDesignSystem:gf,updateDesignSystem:xf,removeDesignSystem:bf,promoteDesignSystem:yf,promotedSystemIds:Go,designSystemOpen:lt,setDesignSystemOpen:it,designSystemMenuOpen:Dt,setDesignSystemMenuOpen:en,editingSystem:dp,editingSystemId:Bt,setEditingSystemId:tn,editingSystemOrigin:sn,setEditingSystemOrigin:dn,editingSystemSwap:Jt,setEditingSystemSwap:Re};return r.jsx(cu.Provider,{value:up,children:r.jsxs("div",{style:{position:"fixed",inset:0,overflow:"hidden",background:a?"var(--color-default)":"#f4f4f5",transition:`background-color ${h}ms ${m}`,fontFamily:"Inter, system-ui, sans-serif",color:"#18181b"},children:[r.jsx(b0,{}),Rr?r.jsx(zy,{visible:fn,progress:Ft?ti?.2+.8*pr:1:.18}):null,Za?r.jsx(by,{targets:Qa.targets,onBaked:el,onGaveUp:tl}):null,r.jsx(rx,{title:Q,onRename:Kl,onGenerateDeck:()=>X(!0),isAgentOpen:a,onToggleAgent:()=>l(E=>!E),zoomPct:se,zoomControls:Ul,leftOffset:12+(a?p:0),rightOffset:a?d:0,topOffset:12+(a?p:0),hideAvatar:!!n,hideTrailing:ei,hideIdentity:!!n}),ei?null:r.jsx(sx,{onAddSlide:()=>qa(),onAddNote:()=>Xs(),onToggleImageMenu:()=>{Pe(!1),en(!1),Ao(E=>!E)},onToggleDocumentMenu:()=>{Ao(!1),en(!1),Pe(E=>!E)},onAddWebsite:()=>Nl(),leftOffset:12+(a?p:0)}),za?r.jsx(fg,{value:Pa,onSave:E=>{Ls(E),zs(!1),rt()},onApply:E=>{Ls(E),zs(!1),rt(),sl(E)},onClose:()=>zs(!1)}):null,(()=>{if($o==null)return null;const E=Vt.find(te=>te.id===$o);return E?r.jsx(kx,{src:E.src,aspect:E.width/E.height,onClose:()=>ka(null)}):null})(),(()=>{if(js==null)return null;const E=ts.find(te=>te.id===js);return E?r.jsx(Rx,{web:E,onClose:()=>Ns(null)}):null})(),r.jsx(Iw,{demo:!!n,selectedCount:Ge.size,bottom:12+(a?p:0),left:12+(a?p:0),dockMs:h,dockEase:m}),r.jsxs("div",{ref:Ts,"data-birtvy-bg":!0,style:{position:"absolute",inset:0,cursor:"default",touchAction:"none",background:"#f4f4f5",clipPath:a?`inset(${p}px ${d}px ${p}px ${p}px round var(--radius-lg))`:"inset(0px round 0px)",transition:`clip-path ${h}ms ${m}`},onDragEnter:E=>{Hi(E.dataTransfer.types)&&(E.preventDefault(),br.current+=1,br.current===1&&Ds(!0))},onDragOver:E=>{!E.dataTransfer.types.includes(zi)&&!Hi(E.dataTransfer.types)||(E.preventDefault(),E.dataTransfer.dropEffect="copy")},onDragLeave:()=>{br.current!==0&&(br.current-=1,br.current===0&&Ds(!1))},onDrop:E=>{br.current=0,Ds(!1);const te=E.dataTransfer,xe=te.getData(zi);if(xe){E.preventDefault(),qo(xe,Bs(E.clientX,E.clientY));return}if(E.preventDefault(),Qo)return;const Se=au(te);if(Se.length===0){o({title:"That file type isnât supported yet."});return}Jo(Se,Bs(E.clientX,E.clientY))},onContextMenu:E=>{if(E.preventDefault(),Qo)return;const te=E.target;if(te.closest("[data-birtvy-wire-layer], [data-ports-for]"))return;const xe=Bs(E.clientX,E.clientY),Se=te.closest("[data-slide-id], [data-doc-id], [data-note-id], [data-image-id], [data-web-id]");let Ce=null;Se&&(Se.dataset.slideId?Ce={kind:"slide",id:Number(Se.dataset.slideId)}:Se.dataset.docId?Ce={kind:"doc",id:Number(Se.dataset.docId)}:Se.dataset.noteId?Ce={kind:"note",id:Number(Se.dataset.noteId)}:Se.dataset.imageId?Ce={kind:"image",id:Number(Se.dataset.imageId)}:Se.dataset.webId&&(Ce={kind:"web",id:Number(Se.dataset.webId)})),Ce&&Ol(Ce.kind,Ce.id),Ca({client:{x:E.clientX,y:E.clientY},world:xe,target:Ce})},children:[Sa?r.jsx("div",{"aria-hidden":!0,style:{position:"absolute",inset:a?`${p}px ${d}px ${p}px ${p}px`:0,zIndex:90,pointerEvents:"none",borderRadius:"var(--radius-lg)",boxShadow:"inset 0 0 0 2px var(--color-state-primary)",background:"var(--color-state-primary)",o
51pacity:.06,transition:"opacity 120ms ease-out"}}):null,r.jsxs("div",{ref:jr,"data-birtvy-bg":!0,style:{position:"absolute",top:0,left:0,transformOrigin:"0 0",userSelect:"none"},children:[r.jsx(Ov,{}),r.jsx(Bv,{}),r.jsx(hv,{}),r.jsx(Mv,{}),r.jsx(Ux,{}),r.jsx(Fv,{})]}),r.jsx(Gv,{}),r.jsx(Wv,{})]}),r.jsx(Hv,{}),Ae&&Ys?r.jsx(jy,{html:Ae.html,title:(Zl=Ys.docMeta)==null?void 0:Zl.title,onSource:(E,te)=>nl(Ae.id,E,te),onClose:()=>jt(null),stageInsetEdge:a?p:0,stageInsetRight:a?d:0,isAgentOpen:a,onToggleAgent:()=>l(E=>!E),onPresent:()=>{const E=Ys.groupId,te=Ae.id;jt(null),E!=null?ct(E):Ve(te)}},Ae.id):null,Ee!=null&&(nr!=null&&nr.baked)?r.jsx(ex,{conversationId:e,shape:vc(nr),slides:J.filter(E=>E.baked).map(vc),excludedIds:new Set(J.filter(E=>E.excludedFromPresentation).map(E=>E.id)),presentIds:new Set((nr.groupId!=null?ua(J,bt,nr.groupId):J.filter(E=>E.groupId==null)).map(E=>E.id)),graphyConfig:nr.graphyConfig,graphyConfigById:Object.fromEntries(J.filter(E=>E.graphyConfig!=null).map(E=>[String(E.id),E.graphyConfig])),onSwitchSlide:E=>qe(E),onClose:Yl,onChange:Xl,stageInsetEdge:a?p:0,stageInsetRight:a?d:0,isAgentOpen:a,onToggleAgent:()=>l(E=>!E)},Ee):null,Xo!=null&&Yo?r.jsx(uy,{open:!0,loading:gl,concepts:Hs,error:xl,anchorRect:Yo,pickingIndex:yl,moreLoading:bl,canLoadMore:!wl&&Hs.length>0&&Hs.length<Fm.length,onMore:()=>void kl(),onPick:(E,te)=>void Sl(E,te),onRetry:()=>void vl(Xo),onClose:()=>ml(null)}):null,V!=null&&ni?r.jsx(ix,{doc:ni,origin:ke,onClose:()=>{Wl(V),be(null),rt()},onContentChange:E=>Ml(V,E),stageInsetEdge:a?p:0,stageInsetRight:a?d:0,isAgentOpen:a,onToggleAgent:()=>l(E=>!E)},V):null]})})}export{HS as BirtvyCanvas}; 52//# sourceMappingURL=BirtvyCanvas-CWQCIK4_.js.map 53 54//# chunkId=7f2d715c-599b-5076-a783-2d2245f7a562
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.