@augmentd-labs/canvas-web 2.26.7 → 2.26.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/NextShell-DNv3mVFo.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BQnKd3jw.js","assets/workspace-BYMC2sfI.js","assets/react-BzqgEMSQ.js","assets/alert-dialog-CDKOX-MP.js","assets/ui-NWo4bzrd.js","assets/utils-BxVxyehK.js","assets/utils-2pl1SbIp.js","assets/NextShell-BT6-_CFY.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{a,i as o,l as s,n as c,r as l,t as u,u as d}from"./code-editor-BQnKd3jw.js";import{_t as f,gt as p,vt as m,yt as h}from"./react-BzqgEMSQ.js";import{t as g}from"./preload-helper-Czpn1I53.js";import{$ as _,$n as v,$t as y,A as b,An as x,At as S,B as C,Bn as w,C as T,Cn as E,Ct as D,D as O,Dn as k,Dt as A,E as j,En as M,Et as N,F as P,Fn as ee,Ft as F,G as I,Gn as te,Gt as L,H as ne,Hn as R,I as re,In as z,It as ie,J as ae,Jn as B,Jt as oe,K as se,Kn as V,Kt as H,L as ce,Ln as le,Lt as ue,M as de,Mn as fe,Mt as pe,N as me,Nn as he,Nt as ge,O as _e,On as ve,Ot as ye,P as be,Pn as xe,Pt as U,Q as Se,Qn as W,Qt as G,R as Ce,Rn as we,Rt as Te,S as Ee,Sn as De,St as Oe,T as ke,Tn as Ae,Tt as je,U as Me,Un as Ne,Ut as Pe,V as Fe,Vn as K,W as Ie,Wn as Le,Wt as Re,X as ze,Xn as Be,Xt as Ve,Y as He,Yn as Ue,Yt as We,Z as Ge,Zn as Ke,Zt as qe,_ as Je,_n as Ye,_t as Xe,a as Ze,an as Qe,ar as $e,at as et,b as tt,bn as nt,bt as rt,c as it,cn as at,ct as ot,d as st,dn as ct,dt as lt,en as ut,er as dt,et as ft,f as pt,fn as mt,ft as ht,g as gt,gn as _t,gt as vt,h as yt,hn as bt,ht as xt,i as St,in as Ct,ir as wt,it as Tt,j as Et,jn as Dt,jt as Ot,k as kt,kn as At,kt as jt,l as Mt,ln as Nt,lt as Pt,m as Ft,mn as It,mt as Lt,n as Rt,nn as zt,nr as Bt,nt as Vt,o as Ht,on as Ut,ot as Wt,p as Gt,pt as Kt,q as qt,qn as Jt,qt as Yt,r as Xt,rn as Zt,rr as Qt,rt as $t,s as en,sn as tn,st as nn,t as rn,tn as an,tr as on,tt as sn,u as cn,un as ln,ut as un,v as dn,vn as fn,vt as pn,w as mn,wn as hn,wt as gn,x as _n,xn as vn,xt as yn,y as bn,yn as xn,yt as Sn,z as Cn,zn as wn,zt as Tn}from"./document-list-jSeA3hbj.js";import{$ as En,$n as Dn,$r as On,$t as kn,An,Ar as jn,At as Mn,B as Nn,Bn as Pn,Br as Fn,Bt as In,C as Ln,Cn as Rn,Cr as zn,Ct as Bn,Dn as Vn,Dr as Hn,Dt as Un,En as Wn,F as Gn,Fr as Kn,Ft as qn,G as Jn,Gn as Yn,Gr as Xn,H as Zn,Hn as Qn,Hr as $n,Ht as er,I as tr,J as nr,Jn as rr,Jr as ir,Jt as ar,K as or,Kn as sr,Kr as cr,Kt as lr,L as ur,Lr as dr,Lt as fr,Mn as pr,Mt as mr,Nn as hr,Nr as gr,Nt as _r,On as vr,Or as yr,Ot as br,P as xr,Pn as Sr,Pr as Cr,Pt as wr,Q as Tr,Qn as Er,Qr as Dr,Qt as Or,R as kr,Rn as Ar,Rr as jr,Rt as Mr,S as Nr,Sn as Pr,St as Fr,Tn as Ir,U as Lr,Ur as Rr,Ut as zr,V as Br,Vn as Vr,Vr as Hr,Vt as Ur,W as Wr,Wn as Gr,X as Kr,Xn as qr,Xt as Jr,Y as Yr,Yn as Xr,Yr as Zr,Yt as Qr,Z as $r,Zn as ei,Zr as ti,_ as ni,_n as ri,_r as ii,_t as ai,an as oi,ar as si,b as ci,bn as li,br as ui,bt as di,ci as fi,cn as pi,ct as mi,d as hi,dr as gi,dt as _i,ei as vi,en as yi,er as bi,et as xi,f as Si,fi as Ci,fn as wi,fr as Ti,ft as Ei,g as Di,gi as Oi,gn as ki,gr as Ai,gt as ji,h as Mi,hi as Ni,hn as Pi,ht as Fi,in as Ii,ir as Li,it as Ri,jr as zi,jt as Bi,kn as Vi,kr as Hi,kt as Ui,ln as Wi,lt as Gi,m as Ki,mi as qi,mn as Ji,mr as Yi,mt as Xi,ni as Zi,nn as Qi,oi as $i,on as ea,or as ta,ot as na,p as ra,pi as ia,pr as aa,pt as oa,q as sa,qn as ca,qt as la,ri as ua,rn as da,rr as fa,rt as pa,si as ma,sn as ha,sr as ga,st as _a,tn as va,tt as ya,u as ba,ui as xa,un as Sa,ur as Ca,ut as wa,v as Ta,vn as Ea,vr as Da,vt as Oa,w as ka,wr as Aa,wt as ja,x as Ma,xn as Na,xt as Pa,y as Fa,yn as Ia,yr as La,yt as Ra,z as za,zn as Ba,zr as Va,zt as Ha}from"./ui-NWo4bzrd.js";import{i as Ua,n as Wa,r as Ga}from"./utils-BxVxyehK.js";import{n as Ka,t as q}from"./utils-2pl1SbIp.js";import{_ as qa,a as Ja,b as J,c as Ya,d as Xa,f as Za,g as Qa,h as $a,i as eo,l as to,m as no,n as ro,o as io,p as ao,r as oo,s as so,t as co,u as Y,v as lo,x as X,y as uo}from"./alert-dialog-CDKOX-MP.js";import{t as fo}from"./socket-hM4c-ZSl.js";import{a as po,c as mo,l as Z,n as ho,o as go,r as _o,s as vo}from"./blobs-B3DY8Rsp.js";import{$ as yo,$t as bo,A as xo,At as So,B as Co,Bt as wo,C as To,Cn as Eo,Ct as Do,D as Oo,Dn as ko,Dt as Ao,E as jo,En as Mo,Et as No,F as Po,Ft as Fo,G as Io,Gn as Lo,Gt as Ro,H as zo,Ht as Bo,I as Vo,In as Ho,Jt as Uo,K as Wo,Kt as Go,L as Ko,Ln as qo,M as Jo,Mn as Yo,Mt as Xo,Nn as Zo,Nt as Qo,O as $o,On as es,Ot as ts,Pn as ns,Pt as rs,Q as is,Qt as as,R as os,Rn as ss,Rt as cs,S as ls,Sn as us,St as ds,T as fs,Tn as ps,U as ms,Un as hs,Ut as gs,V as _s,Vt as vs,Wt as ys,Xt as bs,Z as xs,Zt as Ss,_ as Cs,_n as ws,_t as Ts,a as Es,an as Ds,at as Os,b as ks,bn as As,bt as js,cn as Ms,ct as Ns,dn as Ps,dt as Fs,et as Is,f as Ls,fn as Rs,ft as zs,gn as Bs,gt as Vs,hn as Hs,ht as Us,i as Ws,in as Gs,it as Ks,j as qs,jn as Js,k as Ys,kt as Xs,ln as Zs,lt as Qs,m as $s,mt as ec,n as tc,nn as nc,nt as rc,o as ic,on as ac,ot as oc,p as sc,pt as cc,q as lc,qt as uc,r as dc,rt as fc,s as pc,sn as mc,st as hc,t as gc,tn as _c,tt as vc,u as yc,un as bc,ut as xc,v as Sc,vt as Cc,w as wc,wn as Tc,wt as Ec,x as Dc,xn as Oc,xt as kc,y as Ac,yn as jc,yt as Mc,z as Nc}from"./workspace-BYMC2sfI.js";import{_ as Pc,c as Fc,f as Ic,h as Lc,l as Rc,m as zc,o as Bc,p as Vc,s as Hc,u as Uc,v as Wc,y as Gc}from"./text-documents-F17vHvLW.js";import{n as Kc,t as qc}from"./map-BxCwdK0d.js";import{B as Jc,D as Yc,F as Xc,I as Zc,L as Qc,N as $c,O as el,P as tl,R as nl,T as rl,_ as il,a as al,b as ol,c as sl,d as cl,f as ll,g as ul,h as dl,i as fl,j as pl,m as ml,n as hl,o as gl,p as _l,r as vl,s as yl,t as bl,u as xl,w as Sl,y as Cl,z as wl}from"./useAddTarget-Bprwjjdn.js";import{t as Tl}from"./sha256-65KIjGvZ.js";import{n as El,t as Dl}from"./use-theme-Bd8sb5Ox.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Q=n(d(),1),Ol=m(),$=s(),kl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));kl.displayName=`Card`;var Al=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`flex flex-col space-y-1.5 p-6`,e),...t}));Al.displayName=`CardHeader`;var jl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`h3`,{ref:n,className:q(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));jl.displayName=`CardTitle`;var Ml=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`p`,{ref:n,className:q(`text-sm text-muted-foreground`,e),...t}));Ml.displayName=`CardDescription`;var Nl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`p-6 pt-0`,e),...t}));Nl.displayName=`CardContent`;var Pl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`flex items-center p-6 pt-0`,e),...t}));Pl.displayName=`CardFooter`;var Fl=`2.26.7`,Il=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Ll(e){(0,Q.useEffect)(()=>{if(window.particlesJS!==void 0)Il(e);else{if(document.getElementById(`particles-js-script`))return;let t=document.createElement(`script`);t.id=`particles-js-script`,t.src=`/js/particles.min.js`,t.onload=()=>{console.log(`particles.js loaded`),Il(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Rl=`session.open`,zl=`session.set`,Bl=`session.ids`,Vl=`session.materialize`,Hl=`session.close`,Ul=`session.delta`;function Wl(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await Y.get(`/ping`,{skipAuth:!0});e&&(n?.version?t(n.version):a(`Invalid server response`))}catch(t){e&&(console.error(`Failed to fetch server version:`,t),a(`Unable to connect to server`))}finally{e&&r(!1)}}n();let i=setInterval(n,3e4);return()=>{e=!1,clearInterval(i)}},[]),{serverVersion:e,isLoading:n,error:i}}var Gl=`https://github.com/canvas-ui/canvas-server`,Kl=null;function ql(){return Kl||=Y.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||Gl,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Kl=null,{sourceUrl:Gl,version:null,commit:null,license:null})),Kl}function Jl(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;return ql().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Yl({className:e=``}){let t=Jl();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function Xl({children:e}){Ll(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Wl();return(0,$.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,$.jsxs)(kl,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,$.jsxs)(Le,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,$.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,$.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,$.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Fl,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,$.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,$.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,$.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,$.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,$.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,$.jsx)(`span`,{children:`View on GitHub`})]}),(0,$.jsx)(Yl,{className:`mt-4 text-center`})]})]})})]})})}async function Zl(e,t,n=`auto`){try{let r=await Y.post(qa.login,{email:e,password:t,strategy:n},{skipAuth:!0});console.log(`Login response:`,r);let i=r;if(`token`in i)return console.log(`Setting auth token (direct):`,i.token.substring(0,10)+`...`),Y.setAuthToken(i.token),w.connect(i.token),r;if(i&&`payload`in i&&i.payload&&i.payload.token)return console.log(`Setting auth token (nested):`,i.payload.token.substring(0,10)+`...`),Y.setAuthToken(i.payload.token),w.connect(i.payload.token),r;throw console.error(`Invalid login response structure:`,r),Error(`Invalid login response: missing token`)}catch(e){throw console.error(`Login error:`,e),Y.clearAuthToken(),e}}async function Ql(e,t,n){try{return await Y.post(qa.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function $l(e){return e instanceof Error&&/^Network error/i.test(e.message)}function eu(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return Ga(e).exp*1e3>Date.now()}catch{return!1}}function tu(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=Ga(e);return t.exp*1e3<Date.now()?(Y.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),Y.clearAuthToken(),null}}async function nu(){try{if(!Y.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await Y.get(qa.me);return console.log(`Current user response:`,e),e&&e?(w.isConnected()||w.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),$l(e))throw e;return e instanceof Error&&(e.message.includes(`USER_NOT_FOUND_IN_DATABASE`)||e.message.includes(`Your session is invalid`)||e.message.includes(`Authentication required`)||e.message.includes(`user account no longer exists`))?(console.warn(`Authentication error detected, clearing token:`,e.message),Y.clearAuthToken(),w.disconnect(),null):null}}function ru(){return Y.isAuthenticated()}function iu(){let e=new URL(`${lo}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function au(e){let t=await Y.post(`${lo}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);Y.setAuthToken(t.token),w.connect(t.token)}async function ou(){try{let e=await Y.get(qa.authConfig,{skipAuth:!0});return e||e}catch(e){return console.error(`Failed to get auth config:`,e),{strategies:{local:{enabled:!0},imap:{enabled:!1,domains:[]}}}}}async function su(e){try{await Y.post(qa.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var cu=e=>e?.strategies?.local?.enabled!==!1,lu=e=>e?.allowUserRegistrations!==!1;function uu(){let e=Qt(),[t,n]=Q.useState(!1),[r,i]=Q.useState(``),[a,o]=Q.useState(``),[s,c]=Q.useState(!1),[l,u]=Q.useState({}),[d,p]=Q.useState(null),[m,h]=Q.useState({email:``,password:``,strategy:`auto`});Q.useEffect(()=>{eu()&&e(`/workspaces`),fetch(`${lo}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),ou().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let g=()=>{let e={};return m.email?/\S+@\S+\.\S+/.test(m.email)||(e.email=`Email is invalid`):e.email=`Email is required`,m.password||(e.password=`Password is required`),u(e),Object.keys(e).length===0},_=e=>{let{name:t,value:n}=e.target;h(e=>({...e,[t]:n}))};async function v(t){if(t.preventDefault(),g()){c(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await Zl(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),u({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}u({password:t})}finally{c(!1)}}}return t?(0,$.jsx)(Xl,{children:(0,$.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(Y.setAuthToken(r.trim()),!await nu())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){Y.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,$.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,$.jsx)(K,{htmlFor:`local-token`,children:`Local access token`}),(0,$.jsx)(J,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(X,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,$.jsx)(Xl,{children:(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,$.jsx)(`form`,{onSubmit:v,children:(0,$.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(K,{htmlFor:`strategy`,children:`Authentication Method`}),(0,$.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:m.strategy,onChange:_,disabled:s,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,$.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,$.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,$.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(K,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(J,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),l.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(K,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(J,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsx)(X,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,$.jsxs)(X,{type:`button`,variant:`outline`,disabled:s,onClick:()=>iu(),children:[(0,$.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),cu(d)&&lu(d)&&(0,$.jsx)(X,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function du(){let e=Qt(),{showToast:t}=Z(),[n,r]=Q.useState(!1),[i,a]=Q.useState({}),[o,s]=Q.useState({name:``,email:``,password:``}),[c,l]=Q.useState(!1),[u,d]=Q.useState(!1),[f,p]=Q.useState(null);Q.useEffect(()=>{(async()=>{let t=await ou(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=Q.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,$.jsxs)(Xl,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,$.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,$.jsx)(X,{asChild:!0,className:`w-full`,children:(0,$.jsx)(Le,{to:`/login`,children:`Go to Login`})})})]}):(0,$.jsxs)(Xl,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,$.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await Ql(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(K,{htmlFor:`name`,children:`Username`}),(0,$.jsx)(J,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(K,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(J,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(K,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(J,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,$.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,$.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,$.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,$.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,$.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,$.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,$.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,$.jsx)(X,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,$.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,$.jsx)(Le,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,$.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,$.jsx)(Le,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,$.jsx)(Le,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function fu(){let e=Qt(),[t]=$e(),[n,r]=Q.useState(t.get(`error`)),i=Q.useRef(!1);return Q.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,au(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,$.jsx)(Xl,{children:(0,$.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,$.jsx)(X,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function pu({children:e}){let[t,n]=(0,Q.useState)(`loading`);return(0,Q.useEffect)(()=>{(async()=>{try{if(!ru()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await nu();e?(console.log(`User authenticated:`,e.email),n(`authenticated`)):(console.log(`User not authenticated or token expired`),n(`unauthenticated`))}catch(e){if(console.error(`Authentication check failed:`,e),$l(e)){if(eu()){n(`authenticated`);return}Y.clearAuthToken(),n(`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),Y.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,$.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,$.jsx)(wn,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,$.jsx)(V,{to:`/login`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}function mu({children:e}){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{(async()=>{try{await Y.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),Y.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,$.jsx)(V,{to:`/workspaces`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}var hu=i(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n[`fast-equals`]={}))})(e,(function(e){function t(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function n(e){return function(t,n,r,i){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r,i);var a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);var s=e(t,n,r,i);return i.delete(t),i.delete(n),s}}function r(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function i(e){return e.constructor===Object||e.constructor==null}function a(e){return typeof e.then==`function`}function o(e,t){return e===t||e!==e&&t!==t}var s=Object.prototype.toString;function c(e){var t=e.areArraysEqual,n=e.areDatesEqual,r=e.areMapsEqual,c=e.areObjectsEqual,l=e.areRegExpsEqual,u=e.areSetsEqual,d=e.createIsNestedEqual,f=d(p);function p(e,d,p){if(e===d)return!0;if(!e||!d||typeof e!=`object`||typeof d!=`object`)return e!==e&&d!==d;if(i(e)&&i(d))return c(e,d,f,p);var m=Array.isArray(e),h=Array.isArray(d);if(m||h)return m===h&&t(e,d,f,p);var g=s.call(e);return g===s.call(d)?g===`[object Date]`?n(e,d,f,p):g===`[object RegExp]`?l(e,d,f,p):g===`[object Map]`?r(e,d,f,p):g===`[object Set]`?u(e,d,f,p):g===`[object Object]`||g===`[object Arguments]`?a(e)||a(d)?!1:c(e,d,f,p):g===`[object Boolean]`||g===`[object Number]`||g===`[object String]`?o(e.valueOf(),d.valueOf()):!1:!1}return p}function l(e,t,n,r){var i=e.length;if(t.length!==i)return!1;for(;i-->0;)if(!n(e[i],t[i],i,i,e,t,r))return!1;return!0}var u=n(l);function d(e,t){return o(e.valueOf(),t.valueOf())}function f(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={},o=0;return e.forEach(function(s,c){if(i){var l=!1,u=0;t.forEach(function(i,d){!l&&!a[u]&&(l=n(c,d,o,u,e,t,r)&&n(s,i,c,d,e,t,r))&&(a[u]=!0),u++}),o++,i=l}}),i}var p=n(f),m=`_owner`,h=Object.prototype.hasOwnProperty;function g(e,t,n,r){var i=Object.keys(e),a=i.length;if(Object.keys(t).length!==a)return!1;for(var o;a-->0;){if(o=i[a],o===m){var s=!!e.$$typeof,c=!!t.$$typeof;if((s||c)&&s!==c)return!1}if(!h.call(t,o)||!n(e[o],t[o],o,o,e,t,r))return!1}return!0}var _=n(g);function v(e,t){return e.source===t.source&&e.flags===t.flags}function y(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={};return e.forEach(function(o,s){if(i){var c=!1,l=0;t.forEach(function(i,u){!c&&!a[l]&&(c=n(o,i,s,u,e,t,r))&&(a[l]=!0),l++}),i=c}}),i}var b=n(y),x=Object.freeze({areArraysEqual:l,areDatesEqual:d,areMapsEqual:f,areObjectsEqual:g,areRegExpsEqual:v,areSetsEqual:y,createIsNestedEqual:t}),S=Object.freeze({areArraysEqual:u,areDatesEqual:d,areMapsEqual:p,areObjectsEqual:_,areRegExpsEqual:v,areSetsEqual:b,createIsNestedEqual:t}),C=c(x);function w(e,t){return C(e,t,void 0)}var T=c(r(x,{createIsNestedEqual:function(){return o}}));function E(e,t){return T(e,t,void 0)}var D=c(S);function O(e,t){return D(e,t,new WeakMap)}var k=c(r(S,{createIsNestedEqual:function(){return o}}));function A(e,t){return k(e,t,new WeakMap)}function j(e){return c(r(x,e(x)))}function M(e){var t=c(r(S,e(S)));return(function(e,n,r){return r===void 0&&(r=new WeakMap),t(e,n,r)})}e.circularDeepEqual=O,e.circularShallowEqual=A,e.createCustomCircularEqual=M,e.createCustomEqual=j,e.deepEqual=w,e.sameValueZeroEqual=o,e.shallowEqual=E,Object.defineProperty(e,"__esModule",{value:!0})}))})),gu=i(((e,t)=>{t.exports=function(e,t,n){return e===t||e.className===t.className&&n(e.style,t.style)&&e.width===t.width&&e.autoSize===t.autoSize&&e.cols===t.cols&&e.draggableCancel===t.draggableCancel&&e.draggableHandle===t.draggableHandle&&n(e.verticalCompact,t.verticalCompact)&&n(e.compactType,t.compactType)&&n(e.layout,t.layout)&&n(e.margin,t.margin)&&n(e.containerPadding,t.containerPadding)&&e.rowHeight===t.rowHeight&&e.maxRows===t.maxRows&&e.isBounded===t.isBounded&&e.isDraggable===t.isDraggable&&e.isResizable===t.isResizable&&e.allowOverlap===t.allowOverlap&&e.preventCollision===t.preventCollision&&e.useCSSTransforms===t.useCSSTransforms&&e.transformScale===t.transformScale&&e.isDroppable===t.isDroppable&&n(e.resizeHandles,t.resizeHandles)&&n(e.resizeHandle,t.resizeHandle)&&e.onLayoutChange===t.onLayoutChange&&e.onDragStart===t.onDragStart&&e.onDrag===t.onDrag&&e.onDragStop===t.onDragStop&&e.onResizeStart===t.onResizeStart&&e.onResize===t.onResize&&e.onResizeStop===t.onResizeStop&&e.onDrop===t.onDrop&&n(e.droppingItem,t.droppingItem)&&n(e.innerRef,t.innerRef)}})),_u=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=oe,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=L,e.setTopLeft=R,e.setTransform=ne,e.sortLayoutItems=re,e.sortLayoutItemsByColRow=ie,e.sortLayoutItemsByRowCol=z,e.synchronizeLayoutWithChildren=ae,e.validateLayout=B,e.withLayoutItem=p;var t=hu(),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:t+``}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){let t=0,n;for(let r=0,i=e.length;r<i;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function u(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=m(e[n]);return t}function f(e,t){let n=Array(e.length);for(let r=0,i=e.length;r<i;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function p(e,t,n){let r=C(e,t);return r?(r=n(m(r)),e=f(e,r),[e,r]):[e,null]}function m(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function h(e,r){return(0,t.deepEqual)(n.default.Children.map(e,e=>e?.key),n.default.Children.map(r,e=>e?.key))&&(0,t.deepEqual)(n.default.Children.map(e,e=>e?.props[`data-grid`]),n.default.Children.map(r,e=>e?.props[`data-grid`]))}e.fastRGLPropsEqual=gu();function g(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function _(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function v(e,t,n,r){let i=E(e),a=l(i),o=re(e,t),s=Array(e.length);for(let c=0,l=o.length;c<l;c++){let l=m(o[c]);l.static||(l=x(i,l,t,n,o,r,a),a=Math.max(a,l.y+l.h),i.push(l)),s[e.indexOf(o[c])]=l,l.moved=!1}return s}var y={x:`w`,y:`h`};function b(e,t,n,r){let i=y[r];t[r]+=1;let a=e.map(e=>e.i).indexOf(t.i);for(let o=a+1;o<e.length;o++){let a=e[o];if(!a.static){if(a.y>t.y+t.h)break;_(t,a)&&b(e,a,n+t[i],r)}}t[r]=n}function x(e,t,n,r,i,a,o){let s=n===`vertical`,c=n===`horizontal`;if(s)for(t.y=Math.min(typeof o==`number`?o:l(e),t.y);t.y>0&&!w(e,t);)t.y--;else if(c)for(;t.x>0&&!w(e,t);)t.x--;let u;for(;(u=w(e,t))&&!(n===null&&a);)if(c?b(i,t,u.x+u.w,`x`):b(i,t,u.y+u.h,`y`),c&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!w(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function S(e,t){let n=E(e);for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i.x+i.w>t.cols&&(i.x=t.cols-i.w),i.x<0&&(i.x=0,i.w=t.cols),!i.static)n.push(i);else for(;w(n,i);)i.y++}return e}function C(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function w(e,t){for(let n=0,r=e.length;n<r;n++)if(_(e[n],t))return e[n]}function T(e,t){return e.filter(e=>_(e,t))}function E(e){return e.filter(e=>e.static)}function D(e,t,n,r,i,a,o,s,c){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;let l=t.x,d=t.y;typeof n==`number`&&(t.x=n),typeof r==`number`&&(t.y=r),t.moved=!0;let f=re(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},te={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function L(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function ne(e){let{top:t,left:n,width:r,height:i}=e,a=`translate(${n}px,${t}px)`;return{transform:a,WebkitTransform:a,MozTransform:a,msTransform:a,OTransform:a,width:`${r}px`,height:`${i}px`,position:`absolute`}}function R(e){let{top:t,left:n,width:r,height:i}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${i}px`,position:`absolute`}}function re(e,t){return t===`horizontal`?ie(e):t===`vertical`?z(e):e}function z(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ie(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function ae(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function B(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function oe(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),vu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calcGridColWidth=t,e.calcGridItemPosition=r,e.calcGridItemWHPx=n,e.calcWH=a,e.calcXY=i,e.clamp=o;function t(e){let{margin:t,containerPadding:n,containerWidth:r,cols:i}=e;return(r-t[0]*(i-1)-n[0]*2)/i}function n(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function r(e,r,i,a,o,s){let{margin:c,containerPadding:l,rowHeight:u}=e,d=t(e),f={};return s&&s.resizing?(f.width=Math.round(s.resizing.width),f.height=Math.round(s.resizing.height)):(f.width=n(a,d,c[0]),f.height=n(o,u,c[1])),s&&s.dragging?(f.top=Math.round(s.dragging.top),f.left=Math.round(s.dragging.left)):s&&s.resizing&&typeof s.resizing.top==`number`&&typeof s.resizing.left==`number`?(f.top=Math.round(s.resizing.top),f.left=Math.round(s.resizing.left)):(f.top=Math.round((u+c[1])*i+l[1]),f.left=Math.round((d+c[0])*r+l[0])),f}function i(e,n,r,i,a){let{margin:s,containerPadding:c,cols:l,rowHeight:u,maxRows:d}=e,f=t(e),p=Math.round((r-c[0])/(f+s[0])),m=Math.round((n-c[1])/(u+s[1]));return p=o(p,0,l-i),m=o(m,0,d-a),{x:p,y:m}}function a(e,n,r,i,a,s){let{margin:c,maxRows:l,cols:u,rowHeight:d}=e,f=t(e),p=Math.round((n+c[0])/(f+c[0])),m=Math.round((r+c[1])/(d+c[1])),h=o(p,0,u-i),g=o(m,0,l-a);return[`sw`,`w`,`nw`].indexOf(s)!==-1&&(h=o(p,0,u)),[`nw`,`n`,`ne`].indexOf(s)!==-1&&(g=o(m,0,l)),{w:h,h:g}}function o(e,t,n){return Math.max(Math.min(e,n),t)}})),yu=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),bu=i(((e,t)=>{var n=yu();function r(){}function i(){}i.resetWarningCache=r,t.exports=function(){function e(e,t,r,i,a,o){if(o!==n){var s=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name=`Invariant Violation`,s}}e.isRequired=e;function t(){return e}var a={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:i,resetWarningCache:r};return a.PropTypes=a,a}})),xu=i(((e,t)=>{t.exports=bu()()})),Su=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},u=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{DraggableCore:()=>U,default:()=>Se}),t.exports=f(p);var m=u(d()),g=u(xu()),_=u(h()),v=Wa();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function te(e,t,n){let r=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect();return{x:(e.clientX+t.scrollLeft-r.left)/n,y:(e.clientY+t.scrollTop-r.top)/n}}function L(e,t){let n=R(e,t,`px`);return{[E(`transform`,O)]:n}}function ne(e,t){return R(e,t,``)}function R({x:e,y:t},n,r){let i=`translate(${e}${r},${t}${r})`;return n&&(i=`translate(${`${typeof n.x==`string`?n.x:n.x+r}`}, ${`${typeof n.y==`string`?n.y:n.y+r}`})`+i),i}function re(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function z(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ie(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ae(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ie();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
2
|
+
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{a,i as o,l as s,n as c,r as l,t as u,u as d}from"./code-editor-BQnKd3jw.js";import{_t as f,gt as p,vt as m,yt as h}from"./react-BzqgEMSQ.js";import{t as g}from"./preload-helper-Czpn1I53.js";import{$ as _,$n as v,$t as y,A as b,An as x,At as S,B as C,Bn as w,C as T,Cn as E,Ct as D,D as O,Dn as k,Dt as A,E as j,En as M,Et as N,F as P,Fn as ee,Ft as F,G as I,Gn as te,Gt as L,H as ne,Hn as R,I as re,In as z,It as ie,J as ae,Jn as B,Jt as oe,K as se,Kn as V,Kt as H,L as ce,Ln as le,Lt as ue,M as de,Mn as fe,Mt as pe,N as me,Nn as he,Nt as ge,O as _e,On as ve,Ot as ye,P as be,Pn as xe,Pt as U,Q as Se,Qn as W,Qt as G,R as Ce,Rn as we,Rt as Te,S as Ee,Sn as De,St as Oe,T as ke,Tn as Ae,Tt as je,U as Me,Un as Ne,Ut as Pe,V as Fe,Vn as K,W as Ie,Wn as Le,Wt as Re,X as ze,Xn as Be,Xt as Ve,Y as He,Yn as Ue,Yt as We,Z as Ge,Zn as Ke,Zt as qe,_ as Je,_n as Ye,_t as Xe,a as Ze,an as Qe,ar as $e,at as et,b as tt,bn as nt,bt as rt,c as it,cn as at,ct as ot,d as st,dn as ct,dt as lt,en as ut,er as dt,et as ft,f as pt,fn as mt,ft as ht,g as gt,gn as _t,gt as vt,h as yt,hn as bt,ht as xt,i as St,in as Ct,ir as wt,it as Tt,j as Et,jn as Dt,jt as Ot,k as kt,kn as At,kt as jt,l as Mt,ln as Nt,lt as Pt,m as Ft,mn as It,mt as Lt,n as Rt,nn as zt,nr as Bt,nt as Vt,o as Ht,on as Ut,ot as Wt,p as Gt,pt as Kt,q as qt,qn as Jt,qt as Yt,r as Xt,rn as Zt,rr as Qt,rt as $t,s as en,sn as tn,st as nn,t as rn,tn as an,tr as on,tt as sn,u as cn,un as ln,ut as un,v as dn,vn as fn,vt as pn,w as mn,wn as hn,wt as gn,x as _n,xn as vn,xt as yn,y as bn,yn as xn,yt as Sn,z as Cn,zn as wn,zt as Tn}from"./document-list-CZRqD2Up.js";import{$ as En,$n as Dn,$r as On,$t as kn,An,Ar as jn,At as Mn,B as Nn,Bn as Pn,Br as Fn,Bt as In,C as Ln,Cn as Rn,Cr as zn,Ct as Bn,Dn as Vn,Dr as Hn,Dt as Un,En as Wn,F as Gn,Fr as Kn,Ft as qn,G as Jn,Gn as Yn,Gr as Xn,H as Zn,Hn as Qn,Hr as $n,Ht as er,I as tr,J as nr,Jn as rr,Jr as ir,Jt as ar,K as or,Kn as sr,Kr as cr,Kt as lr,L as ur,Lr as dr,Lt as fr,Mn as pr,Mt as mr,Nn as hr,Nr as gr,Nt as _r,On as vr,Or as yr,Ot as br,P as xr,Pn as Sr,Pr as Cr,Pt as wr,Q as Tr,Qn as Er,Qr as Dr,Qt as Or,R as kr,Rn as Ar,Rr as jr,Rt as Mr,S as Nr,Sn as Pr,St as Fr,Tn as Ir,U as Lr,Ur as Rr,Ut as zr,V as Br,Vn as Vr,Vr as Hr,Vt as Ur,W as Wr,Wn as Gr,X as Kr,Xn as qr,Xt as Jr,Y as Yr,Yn as Xr,Yr as Zr,Yt as Qr,Z as $r,Zn as ei,Zr as ti,_ as ni,_n as ri,_r as ii,_t as ai,an as oi,ar as si,b as ci,bn as li,br as ui,bt as di,ci as fi,cn as pi,ct as mi,d as hi,dr as gi,dt as _i,ei as vi,en as yi,er as bi,et as xi,f as Si,fi as Ci,fn as wi,fr as Ti,ft as Ei,g as Di,gi as Oi,gn as ki,gr as Ai,gt as ji,h as Mi,hi as Ni,hn as Pi,ht as Fi,in as Ii,ir as Li,it as Ri,jr as zi,jt as Bi,kn as Vi,kr as Hi,kt as Ui,ln as Wi,lt as Gi,m as Ki,mi as qi,mn as Ji,mr as Yi,mt as Xi,ni as Zi,nn as Qi,oi as $i,on as ea,or as ta,ot as na,p as ra,pi as ia,pr as aa,pt as oa,q as sa,qn as ca,qt as la,ri as ua,rn as da,rr as fa,rt as pa,si as ma,sn as ha,sr as ga,st as _a,tn as va,tt as ya,u as ba,ui as xa,un as Sa,ur as Ca,ut as wa,v as Ta,vn as Ea,vr as Da,vt as Oa,w as ka,wr as Aa,wt as ja,x as Ma,xn as Na,xt as Pa,y as Fa,yn as Ia,yr as La,yt as Ra,z as za,zn as Ba,zr as Va,zt as Ha}from"./ui-NWo4bzrd.js";import{i as Ua,n as Wa,r as Ga}from"./utils-BxVxyehK.js";import{n as Ka,t as q}from"./utils-2pl1SbIp.js";import{_ as qa,a as Ja,b as J,c as Ya,d as Xa,f as Za,g as Qa,h as $a,i as eo,l as to,m as no,n as ro,o as io,p as ao,r as oo,s as so,t as co,u as Y,v as lo,x as X,y as uo}from"./alert-dialog-CDKOX-MP.js";import{t as fo}from"./socket-hM4c-ZSl.js";import{a as po,c as mo,l as Z,n as ho,o as go,r as _o,s as vo}from"./blobs-B3DY8Rsp.js";import{$ as yo,$t as bo,A as xo,At as So,B as Co,Bt as wo,C as To,Cn as Eo,Ct as Do,D as Oo,Dn as ko,Dt as Ao,E as jo,En as Mo,Et as No,F as Po,Ft as Fo,G as Io,Gn as Lo,Gt as Ro,H as zo,Ht as Bo,I as Vo,In as Ho,Jt as Uo,K as Wo,Kt as Go,L as Ko,Ln as qo,M as Jo,Mn as Yo,Mt as Xo,Nn as Zo,Nt as Qo,O as $o,On as es,Ot as ts,Pn as ns,Pt as rs,Q as is,Qt as as,R as os,Rn as ss,Rt as cs,S as ls,Sn as us,St as ds,T as fs,Tn as ps,U as ms,Un as hs,Ut as gs,V as _s,Vt as vs,Wt as ys,Xt as bs,Z as xs,Zt as Ss,_ as Cs,_n as ws,_t as Ts,a as Es,an as Ds,at as Os,b as ks,bn as As,bt as js,cn as Ms,ct as Ns,dn as Ps,dt as Fs,et as Is,f as Ls,fn as Rs,ft as zs,gn as Bs,gt as Vs,hn as Hs,ht as Us,i as Ws,in as Gs,it as Ks,j as qs,jn as Js,k as Ys,kt as Xs,ln as Zs,lt as Qs,m as $s,mt as ec,n as tc,nn as nc,nt as rc,o as ic,on as ac,ot as oc,p as sc,pt as cc,q as lc,qt as uc,r as dc,rt as fc,s as pc,sn as mc,st as hc,t as gc,tn as _c,tt as vc,u as yc,un as bc,ut as xc,v as Sc,vt as Cc,w as wc,wn as Tc,wt as Ec,x as Dc,xn as Oc,xt as kc,y as Ac,yn as jc,yt as Mc,z as Nc}from"./workspace-BYMC2sfI.js";import{_ as Pc,c as Fc,f as Ic,h as Lc,l as Rc,m as zc,o as Bc,p as Vc,s as Hc,u as Uc,v as Wc,y as Gc}from"./text-documents-F17vHvLW.js";import{n as Kc,t as qc}from"./map-BxCwdK0d.js";import{B as Jc,D as Yc,F as Xc,I as Zc,L as Qc,N as $c,O as el,P as tl,R as nl,T as rl,_ as il,a as al,b as ol,c as sl,d as cl,f as ll,g as ul,h as dl,i as fl,j as pl,m as ml,n as hl,o as gl,p as _l,r as vl,s as yl,t as bl,u as xl,w as Sl,y as Cl,z as wl}from"./useAddTarget-Bprwjjdn.js";import{t as Tl}from"./sha256-65KIjGvZ.js";import{n as El,t as Dl}from"./use-theme-Bd8sb5Ox.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Q=n(d(),1),Ol=m(),$=s(),kl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));kl.displayName=`Card`;var Al=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`flex flex-col space-y-1.5 p-6`,e),...t}));Al.displayName=`CardHeader`;var jl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`h3`,{ref:n,className:q(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));jl.displayName=`CardTitle`;var Ml=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`p`,{ref:n,className:q(`text-sm text-muted-foreground`,e),...t}));Ml.displayName=`CardDescription`;var Nl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`p-6 pt-0`,e),...t}));Nl.displayName=`CardContent`;var Pl=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:q(`flex items-center p-6 pt-0`,e),...t}));Pl.displayName=`CardFooter`;var Fl=`2.26.8`,Il=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Ll(e){(0,Q.useEffect)(()=>{if(window.particlesJS!==void 0)Il(e);else{if(document.getElementById(`particles-js-script`))return;let t=document.createElement(`script`);t.id=`particles-js-script`,t.src=`/js/particles.min.js`,t.onload=()=>{console.log(`particles.js loaded`),Il(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Rl=`session.open`,zl=`session.set`,Bl=`session.ids`,Vl=`session.materialize`,Hl=`session.close`,Ul=`session.delta`;function Wl(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await Y.get(`/ping`,{skipAuth:!0});e&&(n?.version?t(n.version):a(`Invalid server response`))}catch(t){e&&(console.error(`Failed to fetch server version:`,t),a(`Unable to connect to server`))}finally{e&&r(!1)}}n();let i=setInterval(n,3e4);return()=>{e=!1,clearInterval(i)}},[]),{serverVersion:e,isLoading:n,error:i}}var Gl=`https://github.com/canvas-ui/canvas-server`,Kl=null;function ql(){return Kl||=Y.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||Gl,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Kl=null,{sourceUrl:Gl,version:null,commit:null,license:null})),Kl}function Jl(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;return ql().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Yl({className:e=``}){let t=Jl();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function Xl({children:e}){Ll(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Wl();return(0,$.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,$.jsxs)(kl,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,$.jsxs)(Le,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,$.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,$.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,$.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Fl,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,$.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,$.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,$.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,$.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,$.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,$.jsx)(`span`,{children:`View on GitHub`})]}),(0,$.jsx)(Yl,{className:`mt-4 text-center`})]})]})})]})})}async function Zl(e,t,n=`auto`){try{let r=await Y.post(qa.login,{email:e,password:t,strategy:n},{skipAuth:!0});console.log(`Login response:`,r);let i=r;if(`token`in i)return console.log(`Setting auth token (direct):`,i.token.substring(0,10)+`...`),Y.setAuthToken(i.token),w.connect(i.token),r;if(i&&`payload`in i&&i.payload&&i.payload.token)return console.log(`Setting auth token (nested):`,i.payload.token.substring(0,10)+`...`),Y.setAuthToken(i.payload.token),w.connect(i.payload.token),r;throw console.error(`Invalid login response structure:`,r),Error(`Invalid login response: missing token`)}catch(e){throw console.error(`Login error:`,e),Y.clearAuthToken(),e}}async function Ql(e,t,n){try{return await Y.post(qa.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function $l(e){return e instanceof Error&&/^Network error/i.test(e.message)}function eu(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return Ga(e).exp*1e3>Date.now()}catch{return!1}}function tu(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=Ga(e);return t.exp*1e3<Date.now()?(Y.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),Y.clearAuthToken(),null}}async function nu(){try{if(!Y.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await Y.get(qa.me);return console.log(`Current user response:`,e),e&&e?(w.isConnected()||w.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),$l(e))throw e;return e instanceof Error&&(e.message.includes(`USER_NOT_FOUND_IN_DATABASE`)||e.message.includes(`Your session is invalid`)||e.message.includes(`Authentication required`)||e.message.includes(`user account no longer exists`))?(console.warn(`Authentication error detected, clearing token:`,e.message),Y.clearAuthToken(),w.disconnect(),null):null}}function ru(){return Y.isAuthenticated()}function iu(){let e=new URL(`${lo}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function au(e){let t=await Y.post(`${lo}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);Y.setAuthToken(t.token),w.connect(t.token)}async function ou(){try{let e=await Y.get(qa.authConfig,{skipAuth:!0});return e||e}catch(e){return console.error(`Failed to get auth config:`,e),{strategies:{local:{enabled:!0},imap:{enabled:!1,domains:[]}}}}}async function su(e){try{await Y.post(qa.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var cu=e=>e?.strategies?.local?.enabled!==!1,lu=e=>e?.allowUserRegistrations!==!1;function uu(){let e=Qt(),[t,n]=Q.useState(!1),[r,i]=Q.useState(``),[a,o]=Q.useState(``),[s,c]=Q.useState(!1),[l,u]=Q.useState({}),[d,p]=Q.useState(null),[m,h]=Q.useState({email:``,password:``,strategy:`auto`});Q.useEffect(()=>{eu()&&e(`/workspaces`),fetch(`${lo}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),ou().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let g=()=>{let e={};return m.email?/\S+@\S+\.\S+/.test(m.email)||(e.email=`Email is invalid`):e.email=`Email is required`,m.password||(e.password=`Password is required`),u(e),Object.keys(e).length===0},_=e=>{let{name:t,value:n}=e.target;h(e=>({...e,[t]:n}))};async function v(t){if(t.preventDefault(),g()){c(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await Zl(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),u({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}u({password:t})}finally{c(!1)}}}return t?(0,$.jsx)(Xl,{children:(0,$.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(Y.setAuthToken(r.trim()),!await nu())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){Y.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,$.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,$.jsx)(K,{htmlFor:`local-token`,children:`Local access token`}),(0,$.jsx)(J,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(X,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,$.jsx)(Xl,{children:(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,$.jsx)(`form`,{onSubmit:v,children:(0,$.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(K,{htmlFor:`strategy`,children:`Authentication Method`}),(0,$.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:m.strategy,onChange:_,disabled:s,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,$.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,$.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,$.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(K,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(J,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),l.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(K,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(J,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsx)(X,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,$.jsxs)(X,{type:`button`,variant:`outline`,disabled:s,onClick:()=>iu(),children:[(0,$.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),cu(d)&&lu(d)&&(0,$.jsx)(X,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function du(){let e=Qt(),{showToast:t}=Z(),[n,r]=Q.useState(!1),[i,a]=Q.useState({}),[o,s]=Q.useState({name:``,email:``,password:``}),[c,l]=Q.useState(!1),[u,d]=Q.useState(!1),[f,p]=Q.useState(null);Q.useEffect(()=>{(async()=>{let t=await ou(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=Q.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,$.jsxs)(Xl,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,$.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,$.jsx)(X,{asChild:!0,className:`w-full`,children:(0,$.jsx)(Le,{to:`/login`,children:`Go to Login`})})})]}):(0,$.jsxs)(Xl,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,$.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await Ql(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(K,{htmlFor:`name`,children:`Username`}),(0,$.jsx)(J,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(K,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(J,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(K,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(J,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,$.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,$.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,$.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,$.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,$.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,$.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,$.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,$.jsx)(X,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,$.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,$.jsx)(Le,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,$.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,$.jsx)(Le,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,$.jsx)(Le,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function fu(){let e=Qt(),[t]=$e(),[n,r]=Q.useState(t.get(`error`)),i=Q.useRef(!1);return Q.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,au(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,$.jsx)(Xl,{children:(0,$.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,$.jsx)(X,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function pu({children:e}){let[t,n]=(0,Q.useState)(`loading`);return(0,Q.useEffect)(()=>{(async()=>{try{if(!ru()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await nu();e?(console.log(`User authenticated:`,e.email),n(`authenticated`)):(console.log(`User not authenticated or token expired`),n(`unauthenticated`))}catch(e){if(console.error(`Authentication check failed:`,e),$l(e)){if(eu()){n(`authenticated`);return}Y.clearAuthToken(),n(`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),Y.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,$.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,$.jsx)(wn,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,$.jsx)(V,{to:`/login`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}function mu({children:e}){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{(async()=>{try{await Y.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),Y.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,$.jsx)(V,{to:`/workspaces`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}var hu=i(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n[`fast-equals`]={}))})(e,(function(e){function t(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function n(e){return function(t,n,r,i){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r,i);var a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);var s=e(t,n,r,i);return i.delete(t),i.delete(n),s}}function r(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n}function i(e){return e.constructor===Object||e.constructor==null}function a(e){return typeof e.then==`function`}function o(e,t){return e===t||e!==e&&t!==t}var s=Object.prototype.toString;function c(e){var t=e.areArraysEqual,n=e.areDatesEqual,r=e.areMapsEqual,c=e.areObjectsEqual,l=e.areRegExpsEqual,u=e.areSetsEqual,d=e.createIsNestedEqual,f=d(p);function p(e,d,p){if(e===d)return!0;if(!e||!d||typeof e!=`object`||typeof d!=`object`)return e!==e&&d!==d;if(i(e)&&i(d))return c(e,d,f,p);var m=Array.isArray(e),h=Array.isArray(d);if(m||h)return m===h&&t(e,d,f,p);var g=s.call(e);return g===s.call(d)?g===`[object Date]`?n(e,d,f,p):g===`[object RegExp]`?l(e,d,f,p):g===`[object Map]`?r(e,d,f,p):g===`[object Set]`?u(e,d,f,p):g===`[object Object]`||g===`[object Arguments]`?a(e)||a(d)?!1:c(e,d,f,p):g===`[object Boolean]`||g===`[object Number]`||g===`[object String]`?o(e.valueOf(),d.valueOf()):!1:!1}return p}function l(e,t,n,r){var i=e.length;if(t.length!==i)return!1;for(;i-->0;)if(!n(e[i],t[i],i,i,e,t,r))return!1;return!0}var u=n(l);function d(e,t){return o(e.valueOf(),t.valueOf())}function f(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={},o=0;return e.forEach(function(s,c){if(i){var l=!1,u=0;t.forEach(function(i,d){!l&&!a[u]&&(l=n(c,d,o,u,e,t,r)&&n(s,i,c,d,e,t,r))&&(a[u]=!0),u++}),o++,i=l}}),i}var p=n(f),m=`_owner`,h=Object.prototype.hasOwnProperty;function g(e,t,n,r){var i=Object.keys(e),a=i.length;if(Object.keys(t).length!==a)return!1;for(var o;a-->0;){if(o=i[a],o===m){var s=!!e.$$typeof,c=!!t.$$typeof;if((s||c)&&s!==c)return!1}if(!h.call(t,o)||!n(e[o],t[o],o,o,e,t,r))return!1}return!0}var _=n(g);function v(e,t){return e.source===t.source&&e.flags===t.flags}function y(e,t,n,r){var i=e.size===t.size;if(!i)return!1;if(!e.size)return!0;var a={};return e.forEach(function(o,s){if(i){var c=!1,l=0;t.forEach(function(i,u){!c&&!a[l]&&(c=n(o,i,s,u,e,t,r))&&(a[l]=!0),l++}),i=c}}),i}var b=n(y),x=Object.freeze({areArraysEqual:l,areDatesEqual:d,areMapsEqual:f,areObjectsEqual:g,areRegExpsEqual:v,areSetsEqual:y,createIsNestedEqual:t}),S=Object.freeze({areArraysEqual:u,areDatesEqual:d,areMapsEqual:p,areObjectsEqual:_,areRegExpsEqual:v,areSetsEqual:b,createIsNestedEqual:t}),C=c(x);function w(e,t){return C(e,t,void 0)}var T=c(r(x,{createIsNestedEqual:function(){return o}}));function E(e,t){return T(e,t,void 0)}var D=c(S);function O(e,t){return D(e,t,new WeakMap)}var k=c(r(S,{createIsNestedEqual:function(){return o}}));function A(e,t){return k(e,t,new WeakMap)}function j(e){return c(r(x,e(x)))}function M(e){var t=c(r(S,e(S)));return(function(e,n,r){return r===void 0&&(r=new WeakMap),t(e,n,r)})}e.circularDeepEqual=O,e.circularShallowEqual=A,e.createCustomCircularEqual=M,e.createCustomEqual=j,e.deepEqual=w,e.sameValueZeroEqual=o,e.shallowEqual=E,Object.defineProperty(e,"__esModule",{value:!0})}))})),gu=i(((e,t)=>{t.exports=function(e,t,n){return e===t||e.className===t.className&&n(e.style,t.style)&&e.width===t.width&&e.autoSize===t.autoSize&&e.cols===t.cols&&e.draggableCancel===t.draggableCancel&&e.draggableHandle===t.draggableHandle&&n(e.verticalCompact,t.verticalCompact)&&n(e.compactType,t.compactType)&&n(e.layout,t.layout)&&n(e.margin,t.margin)&&n(e.containerPadding,t.containerPadding)&&e.rowHeight===t.rowHeight&&e.maxRows===t.maxRows&&e.isBounded===t.isBounded&&e.isDraggable===t.isDraggable&&e.isResizable===t.isResizable&&e.allowOverlap===t.allowOverlap&&e.preventCollision===t.preventCollision&&e.useCSSTransforms===t.useCSSTransforms&&e.transformScale===t.transformScale&&e.isDroppable===t.isDroppable&&n(e.resizeHandles,t.resizeHandles)&&n(e.resizeHandle,t.resizeHandle)&&e.onLayoutChange===t.onLayoutChange&&e.onDragStart===t.onDragStart&&e.onDrag===t.onDrag&&e.onDragStop===t.onDragStop&&e.onResizeStart===t.onResizeStart&&e.onResize===t.onResize&&e.onResizeStop===t.onResizeStop&&e.onDrop===t.onDrop&&n(e.droppingItem,t.droppingItem)&&n(e.innerRef,t.innerRef)}})),_u=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=oe,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=L,e.setTopLeft=R,e.setTransform=ne,e.sortLayoutItems=re,e.sortLayoutItemsByColRow=ie,e.sortLayoutItemsByRowCol=z,e.synchronizeLayoutWithChildren=ae,e.validateLayout=B,e.withLayoutItem=p;var t=hu(),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e){var t=c(e,`string`);return typeof t==`symbol`?t:t+``}function c(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){let t=0,n;for(let r=0,i=e.length;r<i;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function u(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=m(e[n]);return t}function f(e,t){let n=Array(e.length);for(let r=0,i=e.length;r<i;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function p(e,t,n){let r=C(e,t);return r?(r=n(m(r)),e=f(e,r),[e,r]):[e,null]}function m(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function h(e,r){return(0,t.deepEqual)(n.default.Children.map(e,e=>e?.key),n.default.Children.map(r,e=>e?.key))&&(0,t.deepEqual)(n.default.Children.map(e,e=>e?.props[`data-grid`]),n.default.Children.map(r,e=>e?.props[`data-grid`]))}e.fastRGLPropsEqual=gu();function g(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function _(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function v(e,t,n,r){let i=E(e),a=l(i),o=re(e,t),s=Array(e.length);for(let c=0,l=o.length;c<l;c++){let l=m(o[c]);l.static||(l=x(i,l,t,n,o,r,a),a=Math.max(a,l.y+l.h),i.push(l)),s[e.indexOf(o[c])]=l,l.moved=!1}return s}var y={x:`w`,y:`h`};function b(e,t,n,r){let i=y[r];t[r]+=1;let a=e.map(e=>e.i).indexOf(t.i);for(let o=a+1;o<e.length;o++){let a=e[o];if(!a.static){if(a.y>t.y+t.h)break;_(t,a)&&b(e,a,n+t[i],r)}}t[r]=n}function x(e,t,n,r,i,a,o){let s=n===`vertical`,c=n===`horizontal`;if(s)for(t.y=Math.min(typeof o==`number`?o:l(e),t.y);t.y>0&&!w(e,t);)t.y--;else if(c)for(;t.x>0&&!w(e,t);)t.x--;let u;for(;(u=w(e,t))&&!(n===null&&a);)if(c?b(i,t,u.x+u.w,`x`):b(i,t,u.y+u.h,`y`),c&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!w(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function S(e,t){let n=E(e);for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i.x+i.w>t.cols&&(i.x=t.cols-i.w),i.x<0&&(i.x=0,i.w=t.cols),!i.static)n.push(i);else for(;w(n,i);)i.y++}return e}function C(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function w(e,t){for(let n=0,r=e.length;n<r;n++)if(_(e[n],t))return e[n]}function T(e,t){return e.filter(e=>_(e,t))}function E(e){return e.filter(e=>e.static)}function D(e,t,n,r,i,a,o,s,c){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;let l=t.x,d=t.y;typeof n==`number`&&(t.x=n),typeof r==`number`&&(t.y=r),t.moved=!0;let f=re(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},te={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function L(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function ne(e){let{top:t,left:n,width:r,height:i}=e,a=`translate(${n}px,${t}px)`;return{transform:a,WebkitTransform:a,MozTransform:a,msTransform:a,OTransform:a,width:`${r}px`,height:`${i}px`,position:`absolute`}}function R(e){let{top:t,left:n,width:r,height:i}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${i}px`,position:`absolute`}}function re(e,t){return t===`horizontal`?ie(e):t===`vertical`?z(e):e}function z(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ie(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function ae(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function B(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function oe(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),vu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calcGridColWidth=t,e.calcGridItemPosition=r,e.calcGridItemWHPx=n,e.calcWH=a,e.calcXY=i,e.clamp=o;function t(e){let{margin:t,containerPadding:n,containerWidth:r,cols:i}=e;return(r-t[0]*(i-1)-n[0]*2)/i}function n(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function r(e,r,i,a,o,s){let{margin:c,containerPadding:l,rowHeight:u}=e,d=t(e),f={};return s&&s.resizing?(f.width=Math.round(s.resizing.width),f.height=Math.round(s.resizing.height)):(f.width=n(a,d,c[0]),f.height=n(o,u,c[1])),s&&s.dragging?(f.top=Math.round(s.dragging.top),f.left=Math.round(s.dragging.left)):s&&s.resizing&&typeof s.resizing.top==`number`&&typeof s.resizing.left==`number`?(f.top=Math.round(s.resizing.top),f.left=Math.round(s.resizing.left)):(f.top=Math.round((u+c[1])*i+l[1]),f.left=Math.round((d+c[0])*r+l[0])),f}function i(e,n,r,i,a){let{margin:s,containerPadding:c,cols:l,rowHeight:u,maxRows:d}=e,f=t(e),p=Math.round((r-c[0])/(f+s[0])),m=Math.round((n-c[1])/(u+s[1]));return p=o(p,0,l-i),m=o(m,0,d-a),{x:p,y:m}}function a(e,n,r,i,a,s){let{margin:c,maxRows:l,cols:u,rowHeight:d}=e,f=t(e),p=Math.round((n+c[0])/(f+c[0])),m=Math.round((r+c[1])/(d+c[1])),h=o(p,0,u-i),g=o(m,0,l-a);return[`sw`,`w`,`nw`].indexOf(s)!==-1&&(h=o(p,0,u)),[`nw`,`n`,`ne`].indexOf(s)!==-1&&(g=o(m,0,l)),{w:h,h:g}}function o(e,t,n){return Math.max(Math.min(e,n),t)}})),yu=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),bu=i(((e,t)=>{var n=yu();function r(){}function i(){}i.resetWarningCache=r,t.exports=function(){function e(e,t,r,i,a,o){if(o!==n){var s=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name=`Invariant Violation`,s}}e.isRequired=e;function t(){return e}var a={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:i,resetWarningCache:r};return a.PropTypes=a,a}})),xu=i(((e,t)=>{t.exports=bu()()})),Su=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},u=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{DraggableCore:()=>U,default:()=>Se}),t.exports=f(p);var m=u(d()),g=u(xu()),_=u(h()),v=Wa();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function te(e,t,n){let r=t===t.ownerDocument.body?{left:0,top:0}:t.getBoundingClientRect();return{x:(e.clientX+t.scrollLeft-r.left)/n,y:(e.clientY+t.scrollTop-r.top)/n}}function L(e,t){let n=R(e,t,`px`);return{[E(`transform`,O)]:n}}function ne(e,t){return R(e,t,``)}function R({x:e,y:t},n,r){let i=`translate(${e}${r},${t}${r})`;return n&&(i=`translate(${`${typeof n.x==`string`?n.x:n.x+r}`}, ${`${typeof n.y==`string`?n.y:n.y+r}`})`+i),i}function re(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function z(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ie(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ae(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ie();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
3
3
|
`,n.innerHTML+=`.react-draggable-transparent-selection *::selection {all: inherit;}
|
|
4
4
|
`,e.getElementsByTagName(`head`)[0].appendChild(n)}e.body&&se(e.body,`react-draggable-transparent-selection`)}function B(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{oe(e)}):oe(e)}function oe(e){if(e)try{e.body&&V(e.body,`react-draggable-transparent-selection`);let t=e.selection;if(t)t.empty();else{let t=(e.defaultView||window).getSelection();t&&t.type!==`Caret`&&t.removeAllRanges()}}catch{}}function se(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function V(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function H(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:me(r);let i=he(e);if(typeof r==`string`){let{ownerDocument:e}=i,t=e.defaultView;if(!t)throw Error(`Cannot resolve the owner window of the draggable node.`);let n;if(n=r===`parent`?i.parentNode:i.getRootNode().querySelector(r),!(n instanceof t.HTMLElement))throw Error(`Bounds selector "`+r+`" could not find an element.`);let a=n,o=t.getComputedStyle(i),s=t.getComputedStyle(a);r={left:-i.offsetLeft+S(s.paddingLeft)+S(o.marginLeft),top:-i.offsetTop+S(s.paddingTop)+S(o.marginTop),right:I(a)-ee(i)-i.offsetLeft+S(s.paddingRight)-S(o.marginRight),bottom:F(a)-P(i)-i.offsetTop+S(s.paddingBottom)-S(o.marginBottom)}}return x(r.right)&&(t=Math.min(t,r.right)),x(r.bottom)&&(n=Math.min(n,r.bottom)),x(r.left)&&(t=Math.max(t,r.left)),x(r.top)&&(n=Math.max(n,r.top)),[t,n]}function ce(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function le(e){return e.props.axis===`both`||e.props.axis===`x`}function ue(e){return e.props.axis===`both`||e.props.axis===`y`}function de(e,t,n){let r=typeof t==`number`?re(e,t):null;if(typeof t==`number`&&!r)return null;let i=he(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return te(r||e,a,n.props.scale)}function fe(e,t,n){let r=!x(e.lastX),i=he(e);return r?{node:i,deltaX:0,deltaY:0,lastX:t,lastY:n,x:t,y:n}:{node:i,deltaX:t-e.lastX,deltaY:n-e.lastY,lastX:e.lastX,lastY:e.lastY,x:t,y:n}}function pe(e,t){let n=e.props.scale;return{node:t.node,x:e.state.x+t.deltaX/n,y:e.state.y+t.deltaY/n,deltaX:t.deltaX/n,deltaY:t.deltaY/n,lastX:e.state.x,lastY:e.state.y}}function me(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function he(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var ge=u(d()),_e=u(xu()),ve=u(h()),ye=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},be={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},xe=be.mouse,U=class extends ge.Component{constructor(){super(...arguments),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,this.touchIdentifier=null,this.mounted=!1,this.handleDragStart=e=>{if(this.props.onMouseDown(e),!this.props.allowAnyClick&&(typeof e.button==`number`&&e.button!==0||e.ctrlKey))return!1;let t=this.findDOMNode();if(!t||!t.ownerDocument||!t.ownerDocument.body)throw Error(`<DraggableCore> not mounted on DragStart!`);let{ownerDocument:n}=t;if(this.props.disabled||!(e.target instanceof n.defaultView.Node)||this.props.handle&&!j(e.target,this.props.handle,t)||this.props.cancel&&j(e.target,this.props.cancel,t))return;e.type===`touchstart`&&!this.props.allowMobileScroll&&e.preventDefault();let r=z(e);this.touchIdentifier=r;let i=de(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=fe(this,a,o);ye(`DraggableCore: handleDragStart: %j`,s),ye(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&ae(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,xe.move,this.handleDrag),M(n,xe.stop,this.handleDragStop))},this.handleDrag=e=>{let t=de(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX,t=r-this.lastY;if([e,t]=ce(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=fe(this,n,r);if(ye(`DraggableCore: handleDrag: %j`,i),this.props.onDrag(e,i)===!1||this.mounted===!1){try{this.handleDragStop(new MouseEvent(`mouseup`))}catch{let e=document.createEvent(`MouseEvents`);e.initMouseEvent(`mouseup`,!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null),this.handleDragStop(e)}return}this.lastX=n,this.lastY=r},this.handleDragStop=e=>{if(!this.dragging)return;let t=de(e,this.touchIdentifier,this);if(t==null)return;let{x:n,y:r}=t;if(Array.isArray(this.props.grid)){let e=n-this.lastX||0,t=r-this.lastY||0;[e,t]=ce(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=fe(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&B(a.ownerDocument),ye(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(ye(`DraggableCore: Removing handlers`),N(a.ownerDocument,xe.move,this.handleDrag),N(a.ownerDocument,xe.stop,this.handleDragStop))},this.onMouseDown=e=>(xe=be.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(xe=be.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(xe=be.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(xe=be.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,be.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,be.mouse.move,this.handleDrag),N(t,be.touch.move,this.handleDrag),N(t,be.mouse.stop,this.handleDragStop),N(t,be.touch.stop,this.handleDragStop),N(e,be.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&B(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=ve.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(ye(`react-draggable: ReactDOM.findDOMNode is not available in React 19+. You must provide a nodeRef prop. See: https://github.com/react-grid-layout/react-draggable#noderef`),null)}render(){return ge.cloneElement(ge.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};U.displayName=`DraggableCore`,U.propTypes={allowAnyClick:_e.default.bool,allowMobileScroll:_e.default.bool,children:_e.default.node.isRequired,disabled:_e.default.bool,enableUserSelectHack:_e.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:_e.default.arrayOf(_e.default.number),handle:_e.default.string,cancel:_e.default.string,nodeRef:_e.default.object,nonce:_e.default.string,onStart:_e.default.func,onDrag:_e.default.func,onStop:_e.default.func,onMouseDown:_e.default.func,scale:_e.default.number,className:C,style:C,transform:C},U.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var Se=class extends m.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(ye(`Draggable: onDragStart: %j`,t),this.props.onStart(e,pe(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;ye(`Draggable: onDrag: %j`,t);let n=pe(this,t),r={x:n.x,y:n.y,slackX:0,slackY:0};if(this.props.bounds){let{x:e,y:t}=r;r.x+=this.state.slackX,r.y+=this.state.slackY;let[i,a]=H(this,r.x,r.y);r.x=i,r.y=a,r.slackX=this.state.slackX+(e-r.x),r.slackY=this.state.slackY+(t-r.y),n.x=r.x,n.y=r.y,n.deltaX=r.x-this.state.x,n.deltaY=r.y-this.state.y}if(this.props.onDrag(e,n)===!1)return!1;this.setState(r)},this.onDragStop=(e,t)=>{if(!this.state.dragging||this.props.onStop(e,pe(this,t))===!1)return!1;ye(`Draggable: onDragStop: %j`,t);let n={dragging:!1,slackX:0,slackY:0};if(this.props.position){let{x:e,y:t}=this.props.position;n.x=e,n.y=t}this.setState(n)},this.state={dragging:!1,dragged:!1,x:e.position?e.position.x:e.defaultPosition.x,y:e.position?e.position.y:e.defaultPosition.y,prevPropsPosition:{...e.position},slackX:0,slackY:0,isElementSVG:!1},e.position&&!(e.onDrag||e.onStop)&&console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.")}static getDerivedStateFromProps({position:e},{prevPropsPosition:t}){return e&&(!t||e.x!==t.x||e.y!==t.y)?(ye(`Draggable: getDerivedStateFromProps %j`,{position:e,prevPropsPosition:t}),{x:e.x,y:e.y,prevPropsPosition:{...e}}):null}componentDidMount(){window.SVGElement!==void 0&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.state.dragging&&this.setState({dragging:!1})}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=_.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):null}render(){let{axis:e,bounds:t,children:n,defaultPosition:r,defaultClassName:i,defaultClassNameDragging:a,defaultClassNameDragged:o,position:s,positionOffset:c,scale:l,...u}=this.props,d={},f=null,p=!s||this.state.dragging,h=s||r,g={x:le(this)&&p?this.state.x:h.x,y:ue(this)&&p?this.state.y:h.y};this.state.isElementSVG?f=ne(g,c):d=L(g,c);let _=m.Children.only(n),y=(0,v.clsx)(_.props.className||``,i,{[a]:this.state.dragging,[o]:this.state.dragged});return m.createElement(U,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},m.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};Se.displayName=`Draggable`,Se.propTypes={...U.propTypes,axis:g.default.oneOf([`both`,`x`,`y`,`none`]),bounds:g.default.oneOfType([g.default.shape({left:g.default.number,right:g.default.number,top:g.default.number,bottom:g.default.number}),g.default.string,g.default.oneOf([!1])]),defaultClassName:g.default.string,defaultClassNameDragging:g.default.string,defaultClassNameDragged:g.default.string,defaultPosition:g.default.shape({x:g.default.number,y:g.default.number}),positionOffset:g.default.shape({x:g.default.oneOfType([g.default.number,g.default.string]),y:g.default.oneOfType([g.default.number,g.default.string])}),position:g.default.shape({x:g.default.number,y:g.default.number}),className:C,style:C,transform:C},Se.defaultProps={...U.defaultProps,axis:`both`,bounds:!1,defaultClassName:`react-draggable`,defaultClassNameDragging:`react-draggable-dragging`,defaultClassNameDragged:`react-draggable-dragged`,defaultPosition:{x:0,y:0},scale:1},0&&(t.exports={DraggableCore:U})})),Cu=i(((e,t)=>{var n=Su(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),wu=i((e=>{e.__esModule=!0,e.cloneElement=c;var t=n(d());function n(e){return e&&e.__esModule?e:{default:e}}function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return(t=o(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){var t=s(e,`string`);return typeof t==`symbol`?t:t+``}function s(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function c(e,n){return n.style&&e.props.style&&(n.style=i(i({},e.props.style),n.style)),n.className&&e.props.className&&(n.className=e.props.className+` `+n.className),t.default.cloneElement(e,n)}})),Tu=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(xu());Cu();function n(e){return e&&e.__esModule?e:{default:e}}e.resizableProps={axis:t.default.oneOf([`both`,`x`,`y`,`none`]),className:t.default.string,children:t.default.element.isRequired,draggableOpts:t.default.shape({allowAnyClick:t.default.bool,cancel:t.default.string,children:t.default.node,disabled:t.default.bool,enableUserSelectHack:t.default.bool,offsetParent:typeof Element<`u`?t.default.instanceOf(Element):t.default.any,grid:t.default.arrayOf(t.default.number),handle:t.default.string,nodeRef:t.default.object,onStart:t.default.func,onDrag:t.default.func,onStop:t.default.func,onMouseDown:t.default.func,scale:t.default.number}),height:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`y`?t.default.number.isRequired(...e):t.default.number(...e)},handle:t.default.oneOfType([t.default.node,t.default.func]),handleSize:t.default.arrayOf(t.default.number),lockAspectRatio:t.default.bool,maxConstraints:t.default.arrayOf(t.default.number),minConstraints:t.default.arrayOf(t.default.number),onResizeStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,resizeHandles:t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),transformScale:t.default.number,width:function(){var e=[...arguments];let n=e[0];return n.axis===`both`||n.axis===`x`?t.default.number.isRequired(...e):t.default.number(...e)}}})),Eu=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=Cu(),r=wu(),i=Tu(),a=[`children`,`className`,`draggableOpts`,`width`,`height`,`handle`,`handleSize`,`lockAspectRatio`,`axis`,`minConstraints`,`maxConstraints`,`onResize`,`onResizeStop`,`onResizeStart`,`resizeHandles`,`transformScale`];function o(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(o=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s.apply(null,arguments)}function c(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var h=class extends t.Component{constructor(){super(...arguments),this.handleRefs={},this.lastHandleRect=null,this.slack=null,this.lastSize=null}componentWillUnmount(){this.resetData()}resetData(){this.lastHandleRect=this.slack=this.lastSize=null}runConstraints(e,t){let n=this.props,r=n.minConstraints,i=n.maxConstraints,a=n.lockAspectRatio;if(!r&&!i&&!a)return[e,t];if(a){let n=this.props.width/this.props.height,r=e-this.props.width,i=t-this.props.height;Math.abs(r)>Math.abs(i*n)?t=e/n:e=t*n}let o=e,s=t,c=this.slack||[0,0],l=c[0],u=c[1];return e+=l,t+=u,r&&(e=Math.max(r[0],e),t=Math.max(r[1],t)),i&&(e=Math.min(i[0],e),t=Math.min(i[1],t)),this.slack=[l+(o-e),u+(s-t)],[e,t]}resizeHandler(e,t){return(n,r)=>{let i=r.node,a=r.deltaX,o=r.deltaY;e===`onResizeStart`&&this.resetData();let s=(this.props.axis===`both`||this.props.axis===`x`)&&t!==`n`&&t!==`s`,c=(this.props.axis===`both`||this.props.axis===`y`)&&t!==`e`&&t!==`w`;if(!s&&!c)return;let l=t[0],u=t[t.length-1],d=i.getBoundingClientRect();if(this.lastHandleRect!=null){if(u===`w`){let e=d.left-this.lastHandleRect.left;a+=e}if(l===`n`){let e=d.top-this.lastHandleRect.top;o+=e}}this.lastHandleRect=d,u===`w`&&(a=-a),l===`n`&&(o=-o);let f=this.lastSize?.width??this.props.width,p=this.lastSize?.height??this.props.height,m=f+(s?a/this.props.transformScale:0),h=p+(c?o/this.props.transformScale:0);var g=this.runConstraints(m,h);if(m=g[0],h=g[1],e===`onResizeStop`&&this.lastSize){var _=this.lastSize;m=_.width,h=_.height}let v=m!==f||h!==p;e!==`onResizeStop`&&(this.lastSize={width:m,height:h});let y=typeof this.props[e]==`function`?this.props[e]:null;y&&!(e===`onResize`&&!v)&&(n.persist==null||n.persist(),y(n,{node:i,size:{width:m,height:h},handle:t})),e===`onResizeStop`&&this.resetData()}}renderResizeHandle(e,n){let r=this.props.handle;if(!r)return t.createElement(`span`,{className:`react-resizable-handle react-resizable-handle-`+e,ref:n});if(typeof r==`function`)return r(e,n);let i=typeof r.type==`string`,a=u({ref:n},i?{}:{handleAxis:e});return t.cloneElement(r,a)}render(){let e=this.props,i=e.children,o=e.className,l=e.draggableOpts;e.width,e.height,e.handle,e.handleSize,e.lockAspectRatio,e.axis,e.minConstraints,e.maxConstraints,e.onResize,e.onResizeStop,e.onResizeStart;let d=e.resizeHandles;e.transformScale;let f=c(e,a);return(0,r.cloneElement)(i,u(u({},f),{},{className:(o?o+` `:``)+`react-resizable`,children:[...t.Children.toArray(i.props.children),...d.map(e=>{let r=this.handleRefs[e]??(this.handleRefs[e]=t.createRef());return t.createElement(n.DraggableCore,s({},l,{nodeRef:r,key:`resizableHandle-`+e,onStop:this.resizeHandler(`onResizeStop`,e),onStart:this.resizeHandler(`onResizeStart`,e),onDrag:this.resizeHandler(`onResize`,e)}),this.renderResizeHandle(e,r))})]}))}};e.default=h,h.propTypes=i.resizableProps,h.defaultProps={axis:`both`,handleSize:[20,20],lockAspectRatio:!1,minConstraints:[20,20],maxConstraints:[1/0,1/0],resizeHandles:[`se`],transformScale:1}})),Du=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(xu()),r=o(Eu()),i=Tu(),a=[`handle`,`handleSize`,`onResize`,`onResizeStart`,`onResizeStop`,`draggableOpts`,`minConstraints`,`maxConstraints`,`lockAspectRatio`,`axis`,`width`,`height`,`resizeHandles`,`style`,`transformScale`];function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(s=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(null,arguments)}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function p(e){var t=m(e,`string`);return typeof t==`symbol`?t:t+``}function m(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function h(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var g=class extends t.Component{constructor(){super(...arguments),this.state={width:this.props.width,height:this.props.height,propsWidth:this.props.width,propsHeight:this.props.height},this.onResize=(e,t)=>{let n=t.size;this.props.onResize?(e.persist==null||e.persist(),this.setState(n,()=>this.props.onResize&&this.props.onResize(e,t))):this.setState(n)}}static getDerivedStateFromProps(e,t){return t.propsWidth!==e.width||t.propsHeight!==e.height?{width:e.width,height:e.height,propsWidth:e.width,propsHeight:e.height}:null}render(){let e=this.props,n=e.handle,i=e.handleSize;e.onResize;let o=e.onResizeStart,s=e.onResizeStop,l=e.draggableOpts,d=e.minConstraints,f=e.maxConstraints,p=e.lockAspectRatio,m=e.axis;e.width,e.height;let g=e.resizeHandles,_=e.style,v=e.transformScale,y=h(e,a);return t.createElement(r.default,{axis:m,draggableOpts:l,handle:n,handleSize:i,height:this.state.height,lockAspectRatio:p,maxConstraints:f,minConstraints:d,onResizeStart:o,onResize:this.onResize,onResizeStop:s,resizeHandles:g,transformScale:v,width:this.state.width},t.createElement(`div`,c({},y,{style:u(u({},_),{},{width:this.state.width+`px`,height:this.state.height+`px`})})))}};e.default=g,g.propTypes=u(u({},i.resizableProps),{},{children:n.default.element})})),Ou=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=Eu().default,t.exports.ResizableBox=Du().default})),ku=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(xu()),n=r(d());function r(e){return e&&e.__esModule?e:{default:e}}var i=e.resizeHandleAxesType=t.default.arrayOf(t.default.oneOf([`s`,`w`,`e`,`n`,`sw`,`nw`,`se`,`ne`])),a=e.resizeHandleType=t.default.oneOfType([t.default.node,t.default.func]);e.default={className:t.default.string,style:t.default.object,width:t.default.number,autoSize:t.default.bool,cols:t.default.number,draggableCancel:t.default.string,draggableHandle:t.default.string,verticalCompact:function(e){e.verticalCompact},compactType:t.default.oneOf([`vertical`,`horizontal`]),layout:function(e){var t=e.layout;t!==void 0&&_u().validateLayout(t,`layout`)},margin:t.default.arrayOf(t.default.number),containerPadding:t.default.arrayOf(t.default.number),rowHeight:t.default.number,maxRows:t.default.number,isBounded:t.default.bool,isDraggable:t.default.bool,isResizable:t.default.bool,allowOverlap:t.default.bool,preventCollision:t.default.bool,useCSSTransforms:t.default.bool,transformScale:t.default.number,isDroppable:t.default.bool,resizeHandles:i,resizeHandle:a,onLayoutChange:t.default.func,onDragStart:t.default.func,onDrag:t.default.func,onDragStop:t.default.func,onResizeStart:t.default.func,onResize:t.default.func,onResizeStop:t.default.func,onDrop:t.default.func,droppingItem:t.default.shape({i:t.default.string.isRequired,w:t.default.number.isRequired,h:t.default.number.isRequired}),children:function(e,t){let r=e[t],i={};n.default.Children.forEach(r,function(e){if(e?.key!=null){if(i[e.key])throw Error(`Duplicate child key "`+e.key+`" found! This will cause problems in ReactGridLayout.`);i[e.key]=!0}})},innerRef:t.default.any}})),Au=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=u(d()),n=h(),r=u(xu()),i=Cu(),a=Ou(),o=_u(),s=vu(),c=ku(),l=u(Wa());function u(e){return e&&e.__esModule?e:{default:e}}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?f(Object(n),!0).forEach(function(t){m(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function m(e,t,n){return(t=g(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e){var t=_(e,`string`);return typeof t==`symbol`?t:t+``}function _(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var v=class extends t.default.Component{constructor(){super(...arguments),m(this,`state`,{resizing:null,dragging:null,className:``}),m(this,`elementRef`,t.default.createRef()),m(this,`onDragStart`,(e,t)=>{let{node:n}=t,{onDragStart:r,transformScale:i}=this.props;if(!r)return;let a={top:0,left:0},{offsetParent:o}=n;if(!o)return;let c=o.getBoundingClientRect(),l=n.getBoundingClientRect(),u=l.left/i,d=c.left/i,f=l.top/i,p=c.top/i;a.left=u-d+o.scrollLeft,a.top=f-p+o.scrollTop,this.setState({dragging:a});let{x:m,y:h}=(0,s.calcXY)(this.getPositionParams(),a.top,a.left,this.props.w,this.props.h);return r.call(this,this.props.i,m,h,{e,node:n,newPosition:a})}),m(this,`onDrag`,(e,t,r)=>{let{node:i,deltaX:a,deltaY:o}=t,{onDrag:c}=this.props;if(!c)return;if(!this.state.dragging)throw Error(`onDrag called before onDragStart.`);let l=this.state.dragging.top+o,u=this.state.dragging.left+a,{isBounded:d,i:f,w:p,h:m,containerWidth:h}=this.props,g=this.getPositionParams();if(d){let{offsetParent:e}=i;if(e){let{margin:t,rowHeight:n}=this.props,r=e.clientHeight-(0,s.calcGridItemWHPx)(m,n,t[1]);l=(0,s.clamp)(l,0,r);let i=(0,s.calcGridColWidth)(g),a=h-(0,s.calcGridItemWHPx)(p,i,t[0]);u=(0,s.clamp)(u,0,a)}}let _={top:l,left:u};r?this.setState({dragging:_}):(0,n.flushSync)(()=>{this.setState({dragging:_})});let{x:v,y}=(0,s.calcXY)(g,l,u,p,m);return c.call(this,f,v,y,{e,node:i,newPosition:_})}),m(this,`onDragStop`,(e,t)=>{let{node:n}=t,{onDragStop:r}=this.props;if(!r)return;if(!this.state.dragging)throw Error(`onDragEnd called before onDragStart.`);let{w:i,h:a,i:o}=this.props,{left:c,top:l}=this.state.dragging,u={top:l,left:c};this.setState({dragging:null});let{x:d,y:f}=(0,s.calcXY)(this.getPositionParams(),l,c,i,a);return r.call(this,o,d,f,{e,node:n,newPosition:u})}),m(this,`onResizeStop`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStop`)),m(this,`onResizeStart`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStart`)),m(this,`onResize`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResize`))}shouldComponentUpdate(e,t){if(this.props.children!==e.children||this.props.droppingPosition!==e.droppingPosition)return!0;let n=(0,s.calcGridItemPosition)(this.getPositionParams(this.props),this.props.x,this.props.y,this.props.w,this.props.h,this.state),r=(0,s.calcGridItemPosition)(this.getPositionParams(e),e.x,e.y,e.w,e.h,t);return!(0,o.fastPositionEqual)(n,r)||this.props.useCSSTransforms!==e.useCSSTransforms}componentDidMount(){this.moveDroppingItem({})}componentDidUpdate(e){this.moveDroppingItem(e)}moveDroppingItem(e){let{droppingPosition:t}=this.props;if(!t)return;let n=this.elementRef.current;if(!n)return;let r=e.droppingPosition||{left:0,top:0},{dragging:i}=this.state,a=i&&t.left!==r.left||t.top!==r.top;if(!i)this.onDragStart(t.e,{node:n,deltaX:t.left,deltaY:t.top});else if(a){let e=t.left-i.left,r=t.top-i.top;this.onDrag(t.e,{node:n,deltaX:e,deltaY:r},!0)}}getPositionParams(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.props;return{cols:e.cols,containerPadding:e.containerPadding,containerWidth:e.containerWidth,margin:e.margin,maxRows:e.maxRows,rowHeight:e.rowHeight}}createStyle(e){let{usePercentages:t,containerWidth:n,useCSSTransforms:r}=this.props,i;return r?i=(0,o.setTransform)(e):(i=(0,o.setTopLeft)(e),t&&(i.left=(0,o.perc)(e.left/n),i.width=(0,o.perc)(e.width/n))),i}mixinDraggable(e,n){return t.default.createElement(i.DraggableCore,{disabled:!n,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,handle:this.props.handle,cancel:`.react-resizable-handle`+(this.props.cancel?`,`+this.props.cancel:``),scale:this.props.transformScale,nodeRef:this.elementRef},e)}curryResizeHandler(e,t){return(n,r)=>t(n,r,e)}mixinResizable(e,n,r){let{cols:i,minW:o,minH:c,maxW:l,maxH:u,transformScale:d,resizeHandles:f,resizeHandle:p}=this.props,m=this.getPositionParams(),h=(0,s.calcGridItemPosition)(m,0,0,i,0).width,g=(0,s.calcGridItemPosition)(m,0,0,o,c),_=(0,s.calcGridItemPosition)(m,0,0,l,u),v=[g.width,g.height],y=[Math.min(_.width,h),Math.min(_.height,1/0)];return t.default.createElement(a.Resizable,{draggableOpts:{disabled:!r},className:r?void 0:`react-resizable-hide`,width:n.width,height:n.height,minConstraints:v,maxConstraints:y,onResizeStop:this.curryResizeHandler(n,this.onResizeStop),onResizeStart:this.curryResizeHandler(n,this.onResizeStart),onResize:this.curryResizeHandler(n,this.onResize),transformScale:d,resizeHandles:f,handle:p},e)}onResizeHandler(e,t,r,i){let{node:a,size:c,handle:l}=t,u=this.props[i];if(!u)return;let{x:d,y:f,i:p,maxH:m,minH:h,containerWidth:g}=this.props,{minW:_,maxW:v}=this.props,y=c;a&&(y=(0,o.resizeItemInDirection)(l,r,c,g),(0,n.flushSync)(()=>{this.setState({resizing:i===`onResizeStop`?null:y})}));let{w:b,h:x}=(0,s.calcWH)(this.getPositionParams(),y.width,y.height,d,f,l);b=(0,s.clamp)(b,Math.max(_,1),v),x=(0,s.clamp)(x,h,m),u.call(this,p,b,x,{e,node:a,size:y,handle:l})}render(){let{x:e,y:n,w:r,h:i,isDraggable:a,isResizable:o,droppingPosition:c,useCSSTransforms:u}=this.props,d=(0,s.calcGridItemPosition)(this.getPositionParams(),e,n,r,i,this.state),f=t.default.Children.only(this.props.children),m=t.default.cloneElement(f,{ref:this.elementRef,className:(0,l.default)(`react-grid-item`,f.props.className,this.props.className,{static:this.props.static,resizing:!!this.state.resizing,"react-draggable":a,"react-draggable-dragging":!!this.state.dragging,dropping:!!c,cssTransforms:u}),style:p(p(p({},this.props.style),f.props.style),this.createStyle(d))});return m=this.mixinResizable(m,d,o),m=this.mixinDraggable(m,a),m}};e.default=v,m(v,`propTypes`,{children:r.default.element,cols:r.default.number.isRequired,containerWidth:r.default.number.isRequired,rowHeight:r.default.number.isRequired,margin:r.default.array.isRequired,maxRows:r.default.number.isRequired,containerPadding:r.default.array.isRequired,x:r.default.number.isRequired,y:r.default.number.isRequired,w:r.default.number.isRequired,h:r.default.number.isRequired,minW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minWidth not Number`);if(n>e.w||n>e.maxW)return Error(`minWidth larger than item width/maxWidth`)},maxW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxWidth not Number`);if(n<e.w||n<e.minW)return Error(`maxWidth smaller than item width/minWidth`)},minH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minHeight not Number`);if(n>e.h||n>e.maxH)return Error(`minHeight larger than item height/maxHeight`)},maxH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxHeight not Number`);if(n<e.h||n<e.minH)return Error(`maxHeight smaller than item height/minHeight`)},i:r.default.string.isRequired,resizeHandles:c.resizeHandleAxesType,resizeHandle:c.resizeHandleType,onDragStop:r.default.func,onDragStart:r.default.func,onDrag:r.default.func,onResizeStop:r.default.func,onResizeStart:r.default.func,onResize:r.default.func,isDraggable:r.default.bool.isRequired,isResizable:r.default.bool.isRequired,isBounded:r.default.bool.isRequired,static:r.default.bool,useCSSTransforms:r.default.bool.isRequired,transformScale:r.default.number,className:r.default.string,handle:r.default.string,cancel:r.default.string,droppingPosition:r.default.shape({e:r.default.object.isRequired,left:r.default.number.isRequired,top:r.default.number.isRequired})}),m(v,`defaultProps`,{className:``,cancel:``,handle:``,minH:1,minW:1,maxH:1/0,maxW:1/0,transformScale:1})})),ju=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=hu(),r=c(Wa()),i=_u(),a=vu(),o=c(Au()),s=c(ku());function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){p(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`,_=!1;try{_=/firefox/i.test(navigator.userAgent)}catch{}var v=class extends t.Component{constructor(){super(...arguments),p(this,`state`,{activeDrag:null,layout:(0,i.synchronizeLayoutWithChildren)(this.props.layout,this.props.children,this.props.cols,(0,i.compactType)(this.props),this.props.allowOverlap),mounted:!1,oldDragItem:null,oldLayout:null,oldResizeItem:null,resizing:!1,droppingDOMNode:null,children:[]}),p(this,`dragEnterCounter`,0),p(this,`onDragStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);if(!c)return;let l={w:c.w,h:c.h,x:c.x,y:c.y,placeholder:!0,i:e};return this.setState({oldDragItem:(0,i.cloneLayoutItem)(c),oldLayout:s,activeDrag:l}),this.props.onDragStart(s,c,c,null,a,o)}),p(this,`onDrag`,(e,t,n,r)=>{let{e:a,node:o}=r,{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,allowOverlap:u,preventCollision:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;let p={w:f.w,h:f.h,x:f.x,y:f.y,placeholder:!0,i:e};c=(0,i.moveElement)(c,f,t,n,!0,d,(0,i.compactType)(this.props),l,u),this.props.onDrag(c,s,f,p,a,o),this.setState({layout:u?c:(0,i.compact)(c,(0,i.compactType)(this.props),l),activeDrag:p})}),p(this,`onDragStop`,(e,t,n,r)=>{let{e:a,node:o}=r;if(!this.state.activeDrag)return;let{oldDragItem:s}=this.state,{layout:c}=this.state,{cols:l,preventCollision:u,allowOverlap:d}=this.props,f=(0,i.getLayoutItem)(c,e);if(!f)return;c=(0,i.moveElement)(c,f,t,n,!0,u,(0,i.compactType)(this.props),l,d);let p=d?c:(0,i.compact)(c,(0,i.compactType)(this.props),l);this.props.onDragStop(p,s,f,null,a,o);let{oldLayout:m}=this.state;this.setState({activeDrag:null,layout:p,oldDragItem:null,oldLayout:null}),this.onLayoutMaybeChanged(p,m)}),p(this,`onResizeStart`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s}=this.state,c=(0,i.getLayoutItem)(s,e);c&&(this.setState({oldResizeItem:(0,i.cloneLayoutItem)(c),oldLayout:this.state.layout,resizing:!0}),this.props.onResizeStart(s,c,c,null,a,o))}),p(this,`onResize`,(e,t,n,r)=>{let{e:a,node:o,size:s,handle:c}=r,{oldResizeItem:l}=this.state,{layout:u}=this.state,{cols:d,preventCollision:p,allowOverlap:m}=this.props,h=!1,g,_,v,[y,b]=(0,i.withLayoutItem)(u,e,e=>{let r;return _=e.x,v=e.y,[`sw`,`w`,`nw`,`n`,`ne`].indexOf(c)!==-1&&([`sw`,`nw`,`w`].indexOf(c)!==-1&&(_=e.x+(e.w-t),t=e.x!==_&&_<0?e.w:t,_=_<0?0:_),[`ne`,`n`,`nw`].indexOf(c)!==-1&&(v=e.y+(e.h-n),n=e.y!==v&&v<0?e.h:n,v=v<0?0:v),h=!0),p&&!m&&(r=(0,i.getAllCollisions)(u,f(f({},e),{},{w:t,h:n,x:_,y:v})).filter(t=>t.i!==e.i).length>0,r&&(v=e.y,n=e.h,_=e.x,t=e.w,h=!1)),e.w=t,e.h=n,e});if(!b)return;g=y,h&&(g=(0,i.moveElement)(y,b,_,v,!0,this.props.preventCollision,(0,i.compactType)(this.props),d,m));let x={w:b.w,h:b.h,x:b.x,y:b.y,static:!0,i:e};this.props.onResize(g,l,b,x,a,o),this.setState({layout:m?g:(0,i.compact)(g,(0,i.compactType)(this.props),d),activeDrag:x})}),p(this,`onResizeStop`,(e,t,n,r)=>{let{e:a,node:o}=r,{layout:s,oldResizeItem:c}=this.state,{cols:l,allowOverlap:u}=this.props,d=(0,i.getLayoutItem)(s,e),f=u?s:(0,i.compact)(s,(0,i.compactType)(this.props),l);this.props.onResizeStop(f,c,d,null,a,o);let{oldLayout:p}=this.state;this.setState({activeDrag:null,layout:f,oldResizeItem:null,oldLayout:null,resizing:!1}),this.onLayoutMaybeChanged(f,p)}),p(this,`onDragOver`,e=>{var n;if(e.preventDefault(),e.stopPropagation(),_&&!((n=e.nativeEvent.target)!=null&&n.classList.contains(g)))return!1;let{droppingItem:r,onDropDragOver:i,margin:o,cols:s,rowHeight:c,maxRows:l,width:u,containerPadding:d,transformScale:p}=this.props,m=i?.(e);if(m===!1)return this.state.droppingDOMNode&&this.removeDroppingPlaceholder(),!1;let h=f(f({},r),m),{layout:v}=this.state,y=e.currentTarget.getBoundingClientRect(),b=e.clientX-y.left,x=e.clientY-y.top,S={left:b/p,top:x/p,e};if(!this.state.droppingDOMNode){let e={cols:s,margin:o,maxRows:l,rowHeight:c,containerWidth:u,containerPadding:d||o},n=(0,a.calcXY)(e,x,b,h.w,h.h);this.setState({droppingDOMNode:t.createElement(`div`,{key:h.i}),droppingPosition:S,layout:[...v,f(f({},h),{},{x:n.x,y:n.y,static:!1,isDraggable:!0})]})}else if(this.state.droppingPosition){let{left:e,top:t}=this.state.droppingPosition;(e!=b||t!=x)&&this.setState({droppingPosition:S})}}),p(this,`removeDroppingPlaceholder`,()=>{let{droppingItem:e,cols:t}=this.props,{layout:n}=this.state,r=(0,i.compact)(n.filter(t=>t.i!==e.i),(0,i.compactType)(this.props),t,this.props.allowOverlap);this.setState({layout:r,droppingDOMNode:null,activeDrag:null,droppingPosition:void 0})}),p(this,`onDragLeave`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter--,this.dragEnterCounter===0&&this.removeDroppingPlaceholder()}),p(this,`onDragEnter`,e=>{e.preventDefault(),e.stopPropagation(),this.dragEnterCounter++}),p(this,`onDrop`,e=>{e.preventDefault(),e.stopPropagation();let{droppingItem:t}=this.props,{layout:n}=this.state,r=n.find(e=>e.i===t.i);this.dragEnterCounter=0,this.removeDroppingPlaceholder(),this.props.onDrop(n,r,e)})}componentDidMount(){this.setState({mounted:!0}),this.onLayoutMaybeChanged(this.state.layout,this.props.layout)}static getDerivedStateFromProps(e,t){let r;return t.activeDrag?null:(!(0,n.deepEqual)(e.layout,t.propsLayout)||e.compactType!==t.compactType?r=e.layout:(0,i.childrenEqual)(e.children,t.children)||(r=t.layout),r?{layout:(0,i.synchronizeLayoutWithChildren)(r,e.children,e.cols,(0,i.compactType)(e),e.allowOverlap),compactType:e.compactType,children:e.children,propsLayout:e.layout}:null)}shouldComponentUpdate(e,t){return this.props.children!==e.children||!(0,i.fastRGLPropsEqual)(this.props,e,n.deepEqual)||this.state.activeDrag!==t.activeDrag||this.state.mounted!==t.mounted||this.state.droppingPosition!==t.droppingPosition}componentDidUpdate(e,t){if(!this.state.activeDrag){let e=this.state.layout,n=t.layout;this.onLayoutMaybeChanged(e,n)}}containerHeight(){if(!this.props.autoSize)return;let e=(0,i.bottom)(this.state.layout),t=this.props.containerPadding?this.props.containerPadding[1]:this.props.margin[1];return e*this.props.rowHeight+(e-1)*this.props.margin[1]+t*2+`px`}onLayoutMaybeChanged(e,t){t||=this.state.layout,(0,n.deepEqual)(t,e)||this.props.onLayoutChange(e)}placeholder(){let{activeDrag:e}=this.state;if(!e)return null;let{width:n,cols:r,margin:i,containerPadding:a,rowHeight:s,maxRows:c,useCSSTransforms:l,transformScale:u}=this.props;return t.createElement(o.default,{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,className:`react-grid-placeholder ${this.state.resizing?`placeholder-resizing`:``}`,containerWidth:n,cols:r,margin:i,containerPadding:a||i,maxRows:c,rowHeight:s,isDraggable:!1,isResizable:!1,isBounded:!1,useCSSTransforms:l,transformScale:u},t.createElement(`div`,null))}processGridItem(e,n){if(!e||!e.key)return;let r=(0,i.getLayoutItem)(this.state.layout,String(e.key));if(!r)return null;let{width:a,cols:s,margin:c,containerPadding:l,rowHeight:u,maxRows:d,isDraggable:f,isResizable:p,isBounded:m,useCSSTransforms:h,transformScale:g,draggableCancel:_,draggableHandle:v,resizeHandles:y,resizeHandle:b}=this.props,{mounted:x,droppingPosition:S}=this.state,C=typeof r.isDraggable==`boolean`?r.isDraggable:!r.static&&f,w=typeof r.isResizable==`boolean`?r.isResizable:!r.static&&p,T=r.resizeHandles||y,E=C&&m&&r.isBounded!==!1;return t.createElement(o.default,{containerWidth:a,cols:s,margin:c,containerPadding:l||c,maxRows:d,rowHeight:u,cancel:_,handle:v,onDragStop:this.onDragStop,onDragStart:this.onDragStart,onDrag:this.onDrag,onResizeStart:this.onResizeStart,onResize:this.onResize,onResizeStop:this.onResizeStop,isDraggable:C,isResizable:w,isBounded:E,useCSSTransforms:h&&x,usePercentages:!x,transformScale:g,w:r.w,h:r.h,x:r.x,y:r.y,i:r.i,minH:r.minH,minW:r.minW,maxH:r.maxH,maxW:r.maxW,static:r.static,droppingPosition:n?S:void 0,resizeHandles:T,resizeHandle:b},e)}render(){let{className:e,style:n,isDroppable:a,innerRef:o}=this.props,s=(0,r.default)(g,e),c=f({height:this.containerHeight()},n);return t.createElement(`div`,{ref:o,className:s,style:c,onDrop:a?this.onDrop:i.noop,onDragLeave:a?this.onDragLeave:i.noop,onDragEnter:a?this.onDragEnter:i.noop,onDragOver:a?this.onDragOver:i.noop},t.Children.map(this.props.children,e=>this.processGridItem(e)),a&&this.state.droppingDOMNode&&this.processGridItem(this.state.droppingDOMNode,!0),this.placeholder())}};e.default=v,p(v,`displayName`,`ReactGridLayout`),p(v,`propTypes`,s.default),p(v,`defaultProps`,{autoSize:!0,cols:12,className:``,style:{},draggableHandle:``,draggableCancel:``,containerPadding:null,rowHeight:150,maxRows:1/0,layout:[],margin:[10,10],isBounded:!1,isDraggable:!0,isResizable:!0,allowOverlap:!1,isDroppable:!1,useCSSTransforms:!0,transformScale:1,verticalCompact:!0,compactType:`vertical`,preventCollision:!1,droppingItem:{i:`__dropping-elem__`,h:1,w:1},resizeHandles:[`se`],onLayoutChange:i.noop,onDragStart:i.noop,onDrag:i.noop,onDragStop:i.noop,onResizeStart:i.noop,onResize:i.noop,onResizeStop:i.noop,onDrop:i.noop,onDropDragOver:i.noop})})),Mu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=_u();function n(e,t){let n=a(e),r=n[0];for(let i=1,a=n.length;i<a;i++){let a=n[i];t>e[a]&&(r=a)}return r}function r(e,t){if(!t[e])throw Error("ResponsiveReactGridLayout: `cols` entry for breakpoint "+e+` is missing!`);return t[e]}function i(e,n,r,i,o,s){if(e[r])return(0,t.cloneLayout)(e[r]);let c=e[i],l=a(n),u=l.slice(l.indexOf(r));for(let t=0,n=u.length;t<n;t++){let n=u[t];if(e[n]){c=e[n];break}}return c=(0,t.cloneLayout)(c||[]),(0,t.compact)((0,t.correctBounds)(c,{cols:o}),s,o)}function a(e){return Object.keys(e).sort(function(t,n){return e[t]-e[n]})}})),Nu=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(xu()),r=hu(),i=_u(),a=Mu(),o=c(ju()),s=[`breakpoint`,`breakpoints`,`cols`,`layouts`,`margin`,`containerPadding`,`onBreakpointChange`,`onLayoutChange`,`onWidthChange`];function c(e){return e&&e.__esModule?e:{default:e}}function l(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(l=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u.apply(null,arguments)}function f(e,t){if(e==null)return{};var n,r,i=p(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function p(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?m(Object(n),!0).forEach(function(t){g(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function g(e,t,n){return(t=_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _(e){var t=v(e,`string`);return typeof t==`symbol`?t:t+``}function v(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var y=e=>Object.prototype.toString.call(e);function b(e,t){return e==null?null:Array.isArray(e)?e:e[t]}var x=class extends t.Component{constructor(){super(...arguments),g(this,`state`,this.generateInitialState()),g(this,`onLayoutChange`,e=>{this.props.onLayoutChange(e,h(h({},this.props.layouts),{},{[this.state.breakpoint]:e}))})}generateInitialState(){let{width:e,breakpoints:t,layouts:n,cols:r}=this.props,i=(0,a.getBreakpointFromWidth)(t,e),o=(0,a.getColsFromBreakpoint)(i,r),s=this.props.verticalCompact===!1?null:this.props.compactType;return{layout:(0,a.findOrGenerateResponsiveLayout)(n,t,i,i,o,s),breakpoint:i,cols:o}}static getDerivedStateFromProps(e,t){if(!(0,r.deepEqual)(e.layouts,t.layouts)){let{breakpoint:n,cols:r}=t;return{layout:(0,a.findOrGenerateResponsiveLayout)(e.layouts,e.breakpoints,n,n,r,e.compactType),layouts:e.layouts}}return null}componentDidUpdate(e){(this.props.width!=e.width||this.props.breakpoint!==e.breakpoint||!(0,r.deepEqual)(this.props.breakpoints,e.breakpoints)||!(0,r.deepEqual)(this.props.cols,e.cols))&&this.onWidthChange(e)}onWidthChange(e){let{breakpoints:t,cols:n,layouts:r,compactType:o}=this.props,s=this.props.breakpoint||(0,a.getBreakpointFromWidth)(this.props.breakpoints,this.props.width),c=this.state.breakpoint,l=(0,a.getColsFromBreakpoint)(s,n),u=h({},r);if(c!==s||e.breakpoints!==t||e.cols!==n){c in u||(u[c]=(0,i.cloneLayout)(this.state.layout));let e=(0,a.findOrGenerateResponsiveLayout)(u,t,s,c,l,o);e=(0,i.synchronizeLayoutWithChildren)(e,this.props.children,l,o,this.props.allowOverlap),u[s]=e,this.props.onBreakpointChange(s,l),this.props.onLayoutChange(e,u),this.setState({breakpoint:s,layout:e,cols:l})}let d=b(this.props.margin,s),f=b(this.props.containerPadding,s);this.props.onWidthChange(this.props.width,d,l,f)}render(){let e=this.props,{breakpoint:n,breakpoints:r,cols:i,layouts:a,margin:c,containerPadding:l,onBreakpointChange:d,onLayoutChange:p,onWidthChange:m}=e,h=f(e,s);return t.createElement(o.default,u({},h,{margin:b(c,this.state.breakpoint),containerPadding:b(l,this.state.breakpoint),onLayoutChange:this.onLayoutChange,layout:this.state.layout,cols:this.state.cols}))}};e.default=x,g(x,`propTypes`,{breakpoint:n.default.string,breakpoints:n.default.object,allowOverlap:n.default.bool,cols:n.default.object,margin:n.default.oneOfType([n.default.array,n.default.object]),containerPadding:n.default.oneOfType([n.default.array,n.default.object]),layouts(e,t){if(y(e[t])!==`[object Object]`)throw Error(`Layout property must be an object. Received: `+y(e[t]));Object.keys(e[t]).forEach(t=>{if(!(t in e.breakpoints))throw Error(`Each key in layouts must align with a key in breakpoints.`);(0,i.validateLayout)(e.layouts[t],`layouts.`+t)})},width:n.default.number.isRequired,onBreakpointChange:n.default.func,onLayoutChange:n.default.func,onWidthChange:n.default.func}),g(x,`defaultProps`,{breakpoints:{lg:1200,md:996,sm:768,xs:480,xxs:0},cols:{lg:12,md:10,sm:6,xs:4,xxs:2},containerPadding:{lg:null,md:null,sm:null,xs:null,xxs:null},layouts:{},margin:[10,10],allowOverlap:!1,onBreakpointChange:i.noop,onLayoutChange:i.noop,onWidthChange:i.noop})})),Pu=r({default:()=>ld});function Fu(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){Ju(a)}function s(){var e=Date.now();if(n){if(e-i<Yu)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function Iu(e){return parseFloat(e)||0}function Lu(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+Iu(r)},0)}function Ru(e){for(var t=[`top`,`right`,`bottom`,`left`],n={},r=0,i=t;r<i.length;r++){var a=i[r],o=e[`padding-`+a];n[a]=Iu(o)}return n}function zu(e){var t=e.getBBox();return Wu(0,0,t.width,t.height)}function Bu(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return nd;var r=td(e).getComputedStyle(e),i=Ru(r),a=i.left+i.right,o=i.top+i.bottom,s=Iu(r.width),c=Iu(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=Lu(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=Lu(r,`top`,`bottom`)+o)),!Vu(e)){var l=Math.round(s+a)-t,u=Math.round(c+o)-n;Math.abs(l)!==1&&(s-=l),Math.abs(u)!==1&&(c-=u)}return Wu(i.left,i.top,s,c)}function Vu(e){return e===td(e).document.documentElement}function Hu(e){return Ku?rd(e)?zu(e):Bu(e):nd}function Uu(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return ed(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function Wu(e,t,n,r){return{x:e,y:t,width:n,height:r}}var Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud=t((()=>{Gu=(function(){if(typeof Map<`u`)return Map;function e(e,t){var n=-1;return e.some(function(e,r){return e[0]===t&&(n=r,!0)}),n}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(t){var n=e(this.__entries__,t),r=this.__entries__[n];return r&&r[1]},t.prototype.set=function(t,n){var r=e(this.__entries__,t);~r?this.__entries__[r][1]=n:this.__entries__.push([t,n])},t.prototype.delete=function(t){var n=this.__entries__,r=e(n,t);~r&&n.splice(r,1)},t.prototype.has=function(t){return!!~e(this.__entries__,t)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(e,t){t===void 0&&(t=null);for(var n=0,r=this.__entries__;n<r.length;n++){var i=r[n];e.call(t,i[1],i[0])}},t}()})(),Ku=typeof window<`u`&&typeof document<`u`&&window.document===document,qu=(function(){return typeof global<`u`&&global.Math===Math?global:typeof self<`u`&&self.Math===Math?self:typeof window<`u`&&window.Math===Math?window:Function(`return this`)()})(),Ju=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(qu):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),Yu=2,Xu=20,Zu=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],Qu=typeof MutationObserver<`u`,$u=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=Fu(this.refresh.bind(this),Xu)}return e.prototype.addObserver=function(e){~this.observers_.indexOf(e)||this.observers_.push(e),this.connected_||this.connect_()},e.prototype.removeObserver=function(e){var t=this.observers_,n=t.indexOf(e);~n&&t.splice(n,1),!t.length&&this.connected_&&this.disconnect_()},e.prototype.refresh=function(){this.updateObservers_()&&this.refresh()},e.prototype.updateObservers_=function(){var e=this.observers_.filter(function(e){return e.gatherActive(),e.hasActive()});return e.forEach(function(e){return e.broadcastActive()}),e.length>0},e.prototype.connect_=function(){!Ku||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),Qu?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener(`DOMSubtreeModified`,this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!Ku||!this.connected_||(document.removeEventListener(`transitionend`,this.onTransitionEnd_),window.removeEventListener(`resize`,this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener(`DOMSubtreeModified`,this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(e){var t=e.propertyName,n=t===void 0?``:t;Zu.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),ed=(function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];Object.defineProperty(e,i,{value:t[i],enumerable:!1,writable:!1,configurable:!0})}return e}),td=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||qu}),nd=Wu(0,0,0,0),rd=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof td(e).SVGGraphicsElement}:function(e){return e instanceof td(e).SVGElement&&typeof e.getBBox==`function`}})(),id=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=Wu(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=Hu(this.target);return this.contentRect_=e,e.width!==this.broadcastWidth||e.height!==this.broadcastHeight},e.prototype.broadcastRect=function(){var e=this.contentRect_;return this.broadcastWidth=e.width,this.broadcastHeight=e.height,e},e}(),ad=function(){function e(e,t){var n=Uu(t);ed(this,{target:e,contentRect:n})}return e}(),od=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new Gu,typeof e!=`function`)throw TypeError(`The callback provided as parameter 1 is not a function.`);this.callback_=e,this.controller_=t,this.callbackCtx_=n}return e.prototype.observe=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof td(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new id(e)),this.controller_.addObserver(this),this.controller_.refresh())}},e.prototype.unobserve=function(e){if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);if(!(typeof Element>`u`||!(Element instanceof Object))){if(!(e instanceof td(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)&&(t.delete(e),t.size||this.controller_.removeObserver(this))}},e.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},e.prototype.gatherActive=function(){var e=this;this.clearActive(),this.observations_.forEach(function(t){t.isActive()&&e.activeObservations_.push(t)})},e.prototype.broadcastActive=function(){if(this.hasActive()){var e=this.callbackCtx_,t=this.activeObservations_.map(function(e){return new ad(e.target,e.broadcastRect())});this.callback_.call(e,t,e),this.clearActive()}},e.prototype.clearActive=function(){this.activeObservations_.splice(0)},e.prototype.hasActive=function(){return this.activeObservations_.length>0},e}(),sd=typeof WeakMap<`u`?new WeakMap:new Gu,cd=function(){function e(t){if(!(this instanceof e))throw TypeError(`Cannot call a class as a function.`);if(!arguments.length)throw TypeError(`1 argument required, but only 0 present.`);var n=new od(t,$u.getInstance(),this);sd.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){cd.prototype[e]=function(){var t;return(t=sd.get(this))[e].apply(t,arguments)}}),ld=(function(){return qu.ResizeObserver===void 0?cd:qu.ResizeObserver})()})),dd=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(xu()),i=s((ud(),e(Pu))),a=s(Wa()),o=[`measureBeforeMount`];function s(e){return e&&e.__esModule?e:{default:e}}function c(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(c=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(null,arguments)}function u(e,t){if(e==null)return{};var n,r,i=f(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function f(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`;function _(e){var t;return t=class extends n.Component{constructor(){super(...arguments),p(this,`state`,{width:1280}),p(this,`elementRef`,n.createRef()),p(this,`mounted`,!1),p(this,`resizeObserver`,void 0)}componentDidMount(){this.mounted=!0,this.resizeObserver=new i.default(e=>{if(this.elementRef.current instanceof HTMLElement){let t=e[0].contentRect.width;this.setState({width:t})}});let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.observe(e)}componentWillUnmount(){this.mounted=!1;let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.unobserve(e),this.resizeObserver.disconnect()}render(){let t=this.props,{measureBeforeMount:r}=t,i=u(t,o);return r&&!this.mounted?n.createElement(`div`,{className:(0,a.default)(this.props.className,g),style:this.props.style,ref:this.elementRef}):n.createElement(e,l({innerRef:this.elementRef},i,this.state))}},p(t,`defaultProps`,{measureBeforeMount:!1}),p(t,`propTypes`,{measureBeforeMount:r.default.bool}),t}})),fd=n(i(((e,t)=>{t.exports=ju().default,t.exports.utils=_u(),t.exports.calculateUtils=vu(),t.exports.Responsive=Nu().default,t.exports.Responsive.utils=Mu(),t.exports.WidthProvider=dd().default}))(),1),pd=new Map;function md(e){pd.set(e.type,e)}function hd(e){return pd.get(e)}function gd(){return[...pd.values()]}function _d(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,Q.useState)(e.canvasQueries??[]),a=(0,Q.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,Q.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,Q.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,Q.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,Q.useCallback)(()=>o([]),[o])}}function vd({config:e,canvas:t}){let n=typeof e.pageSize==`number`?e.pageSize:50,r=e.viewMode===`card`||e.viewMode===`tile`||e.viewMode===`table`?e.viewMode:`table`,[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(1),[u,d]=(0,Q.useState)(!0),f=t.canvasSort??gt,{queries:p,runSearch:m,removeQuery:h}=_d(t,()=>l(1));(0,Q.useEffect)(()=>{let e=!1;return(async()=>{d(!0);try{let r=await t.fetchDocuments({limit:n,page:c,sortBy:f.sortBy,order:f.order,queries:p.length?p:void 0});if(e)return;a(r.payload||[]),s(r.totalCount||r.count||0)}catch{e||(a([]),s(0))}finally{e||d(!1)}})(),()=>{e=!0}},[t,n,c,f.sortBy,f.order,p]);let g=(0,Q.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,$.jsx)(yt,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,$.jsx)(rn,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,serverSort:f,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}md({type:`documents-table`,name:`Documents`,icon:En,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:vd});function yd({config:e,setConfig:t,canvas:n}){let[r,i]=(0,Q.useState)(()=>new Date),a=e.format!==`24`;return(0,Q.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,$.jsx)(`div`,{className:`text-3xl font-semibold tabular-nums`,children:r.toLocaleTimeString(void 0,{hour12:a,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>t({...e,format:a?`24`:`12`}),className:`mt-1 px-2 py-0.5 text-[10px] border rounded-md text-muted-foreground hover:bg-accent`,children:a?`12h`:`24h`})]})}md({type:`clock`,name:`Clock`,icon:Hn,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:yd});var bd=450,xd=10;function Sd(e,t){let{open:n}=re(),r=(0,Q.useRef)(null),i=(0,Q.useRef)(null),a=(0,Q.useRef)(!1),o=()=>{e&&n(e,t)},s=()=>{r.current&&=(clearTimeout(r.current),null)};return{activationProps:{role:`button`,tabIndex:0,onClick:()=>{if(a.current){a.current=!1;return}o()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},onContextMenu:e=>{e.preventDefault(),o()},onPointerDown:e=>{e.pointerType===`touch`&&(i.current={x:e.clientX,y:e.clientY},a.current=!1,s(),r.current=setTimeout(()=>{a.current=!0,o()},bd))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>xd&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function Cd({doc:e,workspaceId:t}){let n=ns(e),{activationProps:r}=Sd(e,t);return(0,$.jsxs)(`li`,{...r,title:`Open details`,className:`canvas-no-drag cursor-pointer py-1.5 min-w-0 rounded px-1 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,$.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,$.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function wd({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!1;return(async()=>{o(!0);try{let r=await t.fetchDocuments({limit:n});if(e)return;i(r.payload||[]),c(null)}catch(t){if(e)return;c(t instanceof Error?t.message:`Failed to load documents`),i([])}finally{e||o(!1)}})(),()=>{e=!0}},[t,n]),a?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,$.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,$.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,$.jsx)(Cd,{doc:e,workspaceId:t.workspaceId},e.id))})}md({type:`recent-documents`,name:`Recent documents`,icon:si,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:wd});function Td({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,$.jsx)(`textarea`,{value:r,readOnly:n.readOnly,onChange:n=>t({...e,text:n.target.value}),placeholder:n.readOnly?``:`Jot something down…`,className:`canvas-no-drag w-full h-full resize-none bg-transparent text-sm leading-6 outline-none`})}md({type:`note`,name:`Note`,icon:ya,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:Td});var Ed=`data/schema/file`,Dd=`data/schema/drawing`;function Od(e){return(e.schema===Ed||e.schema===Dd)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function kd(e){return e.schema===Ed&&String(e.metadata?.contentType||``).startsWith(`video/`)}var Ad=`data/mime/image`;function jd(e,t,n=!1){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(0),[s,c]=(0,Q.useState)(1),[l,u]=(0,Q.useState)(!0),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=_d(e,()=>c(1)),y=e.canvasSort??gt;(0,Q.useEffect)(()=>{let r=!1,a=async()=>{u(!0),f(null);try{let a=await e.fetchDocuments({limit:t,page:s,queries:h.length?h:void 0,sortBy:y.sortBy,order:y.order,...n?{anyOf:[Ad,`data/mime/video`]}:{allOf:[Ad]}});if(r)return;i((a.payload||[]).filter(e=>Od(e)||n&&kd(e))),o(a.totalCount||a.count||0)}catch(e){if(r)return;i([]),o(0),f(e instanceof Error?e.message:`Failed to load images`)}finally{r||u(!1)}};return a(),window.addEventListener(`workspace:documents:refresh`,a),()=>{r=!0,window.removeEventListener(`workspace:documents:refresh`,a)}},[e,t,s,h,y.sortBy,y.order,n]);let b=(0,Q.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,Q.useCallback)(()=>{m(``),v()},[v]),S=(0,Q.useCallback)(e=>{_(e)},[_]),C=(0,Q.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,Q.useMemo)(()=>Math.max(1,Math.ceil(a/t)),[a,t]),input:p,setInput:m,submit:b,clearSearch:x,removeQuery:S,activeQueries:h,sort:y,setSort:C}}var Md=n(h(),1);function Nd({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=Tt(e,t.id,512,{blobFallback:!kd(t),version:t.checksumArray?.[0]??null}),c=Ho(t)||`image-${t.id}`,l=Zo(t),u=l!==``&&i!==`off`;return(0,$.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-(--card-radius) border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,$.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!kd(t)&&(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,$.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-normal group-hover:scale-105`}),kd(t)&&(0,$.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,$.jsx)(_r,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,$.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,$.jsx)(`span`,{className:`pointer-events-none absolute inset-x-0 bottom-0 px-1.5 pb-1 pt-4 text-left text-[11px] leading-snug text-white bg-gradient-to-t from-black/75 via-black/45 to-transparent ${i===`reveal`?`caption-reveal`:``}`,children:(0,$.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,$.jsx)(`span`,{className:`pointer-events-none absolute right-1 top-1 rounded-full bg-black/55 p-1 text-white transition-opacity ${i===`reveal`?`hidden [@media(hover:hover)]:block [@media(hover:hover)]:group-hover:opacity-0`:``}`,title:`Has a comment`,children:(0,$.jsx)(Or,{className:`h-3 w-3`})})]})}function Pd({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Ic(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!kd(a)}),l=Ho(a)||`image-${a.id}`,u=Zo(a),[d,f]=(0,Q.useState)(!1);return ln(r),(0,Q.useEffect)(()=>{let e=e=>{e.target?.closest(`video`)||(e.key===`ArrowLeft`&&n>0&&i(n-1),e.key===`ArrowRight`&&n<t.length-1&&i(n+1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,t.length,i]),(0,Md.createPortal)((0,$.jsxs)(`div`,{"data-scheme":`dark`,className:`fixed inset-0 z-fullscreen flex flex-col bg-scrim p-0 sm:p-4`,onClick:r,children:[(0,$.jsx)(`button`,{type:`button`,onClick:r,className:`canvas-no-drag absolute right-2 top-2 z-10 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20 touch-target sm:right-4 sm:top-4`,title:`Close`,children:(0,$.jsx)(ur,{className:`h-5 w-5`})}),n>0&&!d&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n-1)},className:`canvas-no-drag absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Previous`,children:(0,$.jsx)(Fn,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n+1)},className:`canvas-no-drag absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Next`,children:(0,$.jsx)(Va,{className:`h-6 w-6 touch-target`})}),(0,$.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,$.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,$.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),kd(a)&&(0,$.jsx)(Id,{workspaceId:e,doc:a},a.id),o&&(0,$.jsx)(nn,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,$.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,$.jsx)(`span`,{className:`mx-auto mb-1 block max-w-2xl whitespace-pre-wrap text-sm text-foreground`,children:u}),l,` · `,n+1,`/`,t.length,!d&&!kd(a)&&(0,$.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function Fd({workspaceId:e,state:t,comments:n,onToggleComments:r}){let{input:i,setInput:a,submit:o,clearSearch:s,removeQuery:c,activeQueries:l,sort:u,setSort:d,page:f,setPage:p,totalPages:m,totalCount:h,isLoading:g}=t,_=l.length>0;return(0,$.jsxs)(`div`,{className:`canvas-no-drag flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b px-1 pb-1.5`,children:[(0,$.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,$.jsx)(Oa,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()},placeholder:_?`Refine: add another query (Enter)…`:`Search media (Enter)…`,className:`h-7 w-full rounded-md border bg-background pl-7 pr-7 text-xs`}),_&&(0,$.jsx)(`button`,{type:`button`,onClick:s,title:`Clear search`,className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]}),_&&(0,$.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,$.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,$.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(t),title:`Remove "${e}"`,className:`rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,$.jsx)(ur,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,$.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-pressed":n!==`off`,title:n===`off`?`Show comments on tiles`:`Hide comments on tiles`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border touch-target ${n===`off`?`text-muted-foreground hover:bg-accent`:`border-primary/30 bg-primary/15 text-primary hover:bg-primary/25`}`,children:(0,$.jsx)(Or,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(yt,{workspaceId:e,value:u,onChange:d}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,$.jsx)(wn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,$.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(Math.max(1,f-1)),disabled:f<=1,title:`Previous page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,$.jsx)(Fn,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(Math.min(m,f+1)),disabled:f>=m,title:`Next page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,$.jsx)(Va,{className:`h-3.5 w-3.5`})})]})]})]})}function Id({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=Vc(e,t.id);return(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`span`,{children:`Loading video…`}),i&&(0,$.jsx)(`span`,{role:`alert`,children:i}),n&&(0,$.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function Ld({config:e,setConfig:t,canvas:n}){let r=jd(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=Pc()==null&&(n.interactive??!n.readOnly),[a,o]=(0,Q.useState)(new Set),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),p=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[m,h]=(0,Q.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,$.jsx)(Fd,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,$.jsx)(X,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,$.jsx)(X,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,$.jsxs)(X,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,$.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,$.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:_?`Loading media…`:y.length?`No images or videos match your search.`:`No images or videos in this canvas' context.`}):(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(min(120px,100%),1fr))] gap-2 sm:grid-cols-[repeat(auto-fill,minmax(min(200px,100%),1fr))] sm:gap-3`,children:g.map((e,t)=>(0,$.jsxs)(`div`,{className:`relative`,onContextMenu:t=>{i&&(t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,ids:a.has(e.id)?[...a]:[e.id]}))},children:[(0,$.jsx)(Nd,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select document ${e.id}`,checked:a.has(e.id),onChange:()=>p(e.id),className:`canvas-no-drag absolute left-2 top-2 h-4 w-4 accent-primary`})]},e.id))})}),d&&(0,$.jsx)(qe,{anchor:d,onClose:()=>f(null),label:`${d.ids.length} image${d.ids.length===1?``:`s`}`,items:[{id:`bulk-edit`,label:`Bulk edit… (${d.ids.length})`,icon:fr,run:()=>u(d.ids)}]}),l&&(0,$.jsx)(A,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,$.jsx)(Pd,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}md({type:`gallery`,name:`Gallery`,icon:vr,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Ld});var Rd=150;function zd(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function Bd(e){let t=e.metadata??{},n=e.data??{};return{w:zd(t.width)||zd(t.imageWidth)||zd(n.width)||zd(n.imageWidth),h:zd(t.height)||zd(t.imageHeight)||zd(n.height)||zd(n.imageHeight)}}function Vd(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=Bd(e),i=n&&r?n/r:0;return i>=1.5?{cols:2,rows:1}:i>0&&i<=.66?{cols:1,rows:2}:!i&&t%7==3?{cols:2,rows:1}:{cols:1,rows:1}}function Hd({config:e,setConfig:t,canvas:n}){let r=jd(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,Q.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,$.jsx)(Fd,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,$.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,$.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:s?`Loading images…`:l.length?`No images match your search.`:`No images in this canvas' context.`}):(0,$.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${Rd}px, 1fr))`,gridAutoRows:`${Rd}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=Vd(e,t);return(0,$.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,$.jsx)(Nd,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,$.jsx)(Pd,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}md({type:`mosaic`,name:`Mosaic`,icon:ri,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Hd});var Ud=`data/schema/task`;function Wd({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=ae(e),[a,o]=(0,Q.useState)(!1),{replicating:s,label:c}=es(e),l=i.status===`completed`,u=i.status??`pending`,d=se(i),{activationProps:f,stopRowActivation:p}=Sd(e,t),m=async()=>{if(!(n||a)){o(!0);try{await qt(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,$.jsxs)(`div`,{...f,title:`Open details`,className:`canvas-no-drag flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-2.5 py-2 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${s?`opacity-60`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{p(e),m()},disabled:n||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`canvas-no-drag mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${n?`cursor-default opacity-70`:``}`,children:a?(0,$.jsx)(Sa,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,$.jsx)($n,{className:`h-3 w-3`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,$.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,$.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${Ie[u]}`,children:He[u]}),i.dueDate&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,$.jsx)(cr,{className:`h-3 w-3`}),I(i.dueDate)]}),typeof i.priority==`number`&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,$.jsx)(bi,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,$.jsx)(Sa,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function Gd({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!0),[c,l]=(0,Q.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,Q.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,Q.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[Ud],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===Lo))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,Q.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,Q.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>ae(e).status!==`completed`):i,v=i.filter(e=>{let t=ae(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,$.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,$.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,$.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,$.jsx)(Wd,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}md({type:`todos`,name:`Todos`,icon:wi,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:Gd});function Kd(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var qd=`context`;function Jd(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:qd,path:`/`};if(n[2]===`trees`&&n[3]){let e=t(n[3]);if(n[4]!==`path`)return{treeName:e,path:`/`};let r=n.slice(5).map(t).join(`/`);return{treeName:e,path:r?`/${r}`:`/`}}if(n[2]===`path`){let e=n.slice(3).map(t).join(`/`);return{treeName:qd,path:e?`/${e}`:`/`}}return{treeName:qd,path:`/`}}function Yd(e,t,n){let r=n&&n!==qd?`/trees/${encodeURIComponent(n)}`:``,i=Kd(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function Xd({canvas:e}){return Pc()!=null||!ru()?(0,$.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,$.jsx)(Zd,{workspaceId:e.workspaceId},e.workspaceId)}function Zd({workspaceId:e}){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(`Workspace`),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([yo(e),ts(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),c(null)}catch{if(t||a!==r)return;n([]),c(`Workspace pins are unavailable. Check your workspace access or try again.`)}finally{!t&&a===r&&o(!1)}},s=()=>{document.visibilityState===`visible`&&a()};a(),window.addEventListener(`focus`,s),document.addEventListener(`visibilitychange`,s);let l=w.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),l?.(),window.clearInterval(u)}},[e,l]),(0,$.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,$.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>u(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,$.jsx)(Un,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,$.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,$.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=Tn(t.color),i=(0,$.jsxs)($.Fragment,{children:[n?(0,$.jsx)(nr,{className:`h-5 w-5 shrink-0 text-warning`}):(0,$.jsx)(f,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,$.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,$.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,$.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-(--card-radius) border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,$.jsx)(`li`,{children:n?(0,$.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,$.jsx)(Le,{to:Yd(e,t.path,t.tree),title:`Open ${t.tree}:${t.path}`,className:`${a} transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,style:o,children:i})},t.id)})}):(0,$.jsx)(`p`,{className:`p-2 text-sm text-muted-foreground`,children:a?`Loading pins…`:`No workspace pins yet. Pin a folder from the workspace tree menu.`})})]})}md({type:`workspace-pins`,name:`Workspace pins`,icon:wr,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:Xd});function Qd({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,Q.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,$.jsxs)(`div`,{className:c?u?`absolute inset-0 z-40 flex flex-col bg-background`:`fixed inset-0 z-50 flex flex-col bg-background`:`flex flex-col h-full rounded-(--card-radius) border bg-background overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`canvas-drag-handle flex items-center gap-2 px-2 py-1 border-b bg-muted/30 select-none ${o?``:`cursor-move`}`,children:[t&&(0,$.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,$.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)($d,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:sa}),(0,$.jsx)($d,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:or})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-accent touch-target`,title:c?`Restore`:`Full screen`,children:c?(0,$.jsx)(Qr,{className:`w-3.5 h-3.5`}):(0,$.jsx)(Qi,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 touch-target`,title:`Remove widget`,children:(0,$.jsx)(ur,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,Md.createPortal)(d,u??document.body):d}function $d({on:e,onClick:t,label:n,icon:r}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-pressed":e,title:e?`${n} (on)`:n,className:`canvas-no-drag shrink-0 p-0.5 rounded touch-target ${e?`bg-primary/15 text-primary hover:bg-primary/25`:`text-muted-foreground hover:text-foreground hover:bg-accent`}`,children:(0,$.jsx)(r,{className:`w-3.5 h-3.5`})})}var ef=(0,fd.WidthProvider)(fd.default),tf=12,nf=80,rf=40,af=[12,12],of=[8,8],sf={w:!1,h:!1};function cf(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function lf(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function uf(e){let t=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t;return{...e,x:t(e.x,0),y:t(e.y,0),w:t(e.w,1),h:t(e.h,1)}}function df(e,t,n=0){let r=n>0?n:cf(e);return e.map(e=>{let n=t[e.i]??sf;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?tf:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var ff=4;function pf(e,t,n=af[1]){return Math.max(1,Math.ceil((e-n-ff)/(t+n)))}var mf=45,hf=640;function gf(e,t,n=0,r){let i=[...df(e,t,n)].sort((e,t)=>e.y-t.y||e.x-t.x),a=0;return i.map(e=>{let t=r?.(e.i)??0,n=Math.max(e.h,e.minH??1,t),i={...e,x:0,w:tf,y:a,h:n};return a+=n,i})}var _f=e=>e&&e.trim()?[e]:[];function vf(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(uf):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=tf,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function yf({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,metadata:a,isLocked:o=!1,readOnly:s=!1,interactive:c=!0,fetchDocuments:l,onSaved:u}){let d=!s,f=(0,Q.useMemo)(()=>vf(a),[a]),[p,m]=(0,Q.useState)(f.layout),[h,g]=(0,Q.useState)(f.widgets),[_,v]=(0,Q.useState)(f.fills),y=(0,Q.useRef)(f.fills),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(0),M=(0,Q.useRef)(0),N=(0,Q.useCallback)(e=>{y.current=e,v(e)},[]),[P,ee]=(0,Q.useState)(()=>mn(i?.sort)),F=(0,Q.useRef)(!1),[I,te]=(0,Q.useState)(()=>_f(i?.query)),L=(0,Q.useRef)(!1),ne=(0,Q.useRef)(null),R=(0,Q.useRef)(f),re=(0,Q.useCallback)(e=>{let t=hd(h[e]?.type??``)?.mobileHeight;if(!(!t||A<=0))return Math.max(1,Math.round(A*t))},[h,A]),z=(0,Q.useMemo)(()=>O?gf(p,_,A,re):df(p,_,A),[p,_,O,A,re]),ie=O?rf:nf,ae=(0,Q.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,Q.useEffect)(()=>{let e=vf(a);m(e.layout),g(e.widgets),N(e.fills),R.current=e,ee(mn(i?.sort)),F.current=!1,te(_f(i?.query)),L.current=!1,C(!1)},[n,r]),(0,Q.useEffect)(()=>{if(!s)return;let e=vf(a);m(e.layout),g(e.widgets),N(e.fills),R.current=e},[s,ae,a,N]),(0,Q.useEffect)(()=>{let e=ne.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<hf;k(n),M.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?of:af;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&j(pf(t,n?rf:nf,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let B=(0,Q.useCallback)(e=>{ee(e),F.current=!0,C(!0)},[]),oe=(0,Q.useCallback)(e=>{te(e),L.current=!0,C(!0)},[]),se=(0,Q.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:P,setCanvasSort:d?B:void 0,canvasQueries:I,setCanvasQueries:d?oe:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await lc(e,n,t,{anyOf:r.anyOf,limit:0,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!i.length))return{payload:[],count:0,totalCount:0};let a=await lc(e,n,t,{...r,anyOf:void 0,ids:i});return{payload:a.payload||[],count:a.count??void 0,totalCount:a.totalCount??void 0}})}),[e,t,n,r,i,d,c,l,P,B,I,oe]),V=(0,Q.useCallback)((e,t,n)=>{R.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),H=(0,Q.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:R.current.widgets,layout:R.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};R.current={...r,fills:y.current};let o=F.current||L.current?{...i||{},...F.current?{sort:P.sortBy?P:null}:{},...L.current?{query:I.join(` `).trim()||null}:{}}:void 0;await mc(e,n,t,{...a||{},ui:r},o),F.current=!1,L.current=!1,C(!1),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t}})),u?.()}catch(e){let t=e instanceof Error?e.message:`Save failed`;D(t),console.error(`Failed to save canvas layout:`,e)}finally{T(!1)}}},[d,w,e,n,t,a,u,i,P,I]),ce=(0,Q.useCallback)(e=>{!d||O||m(t=>{let n=e.map(e=>{let n=t.find(t=>t.i===e.i),r=y.current[e.i];return n?{...e,x:r?.w?n.x:e.x,w:r?.w?n.w:e.w,y:r?.h?n.y:e.y,h:r?.h?n.h:e.h}:e});return V(n,h),n})},[d,O,V,h]),le=(0,Q.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??sf,i=af[1]+(n.y+n.h)*(nf+af[1]),a={w:n.x+n.w>=tf,h:M.current>0&&i>=M.current-mf};if(a.w||=r.w&&n.w===t.w,a.h||=r.h&&n.h===t.h,a.w===r.w&&a.h===r.h)return;let o={...y.current,[n.i]:a};N(o),V(R.current.layout,h,o)},[d,N,V,h]),ue=(0,Q.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??sf,r={...y.current,[e]:{...n,[t]:!n[t]}};N(r),V(p,h,r)},[d,N,V,p,h]),de=(0,Q.useCallback)(e=>{let t=hd(e);if(!t)return;let n=crypto.randomUUID(),{w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}=t.defaultSize,l=[...p,{i:n,x:0,y:lf(z),w:r,h:i,minW:a,minH:o,maxW:s,maxH:c}],u={...h,[n]:{type:e,config:{...t.defaultConfig||{}}}},d={...y.current,[n]:{w:r>=tf,h:!1}};m(l),g(u),N(d),x(!1),V(l,u,d)},[p,z,h,N,V]),fe=(0,Q.useCallback)(e=>{let t=p.filter(t=>t.i!==e),n={...h};delete n[e];let r={...y.current};delete r[e],m(t),g(n),N(r),V(t,n,r)},[p,h,N,V]),pe=(0,Q.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return V(p,r),r})},[p,V]),me=Object.keys(h);return(0,$.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,$.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>x(e=>!e),className:`flex items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:[(0,$.jsx)(Bi,{className:`w-3.5 h-3.5`}),`Add`,(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,$.jsx)(`div`,{className:`absolute left-0 top-full mt-1 z-20 w-48 rounded-md border bg-popover shadow-elevation-2 py-1`,children:gd().map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>de(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,$.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:H,disabled:!S||w,className:q(`flex shrink-0 items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs rounded-md transition-colors disabled:opacity-50`,S?`bg-primary text-primary-foreground hover:bg-primary`:`border hover:bg-accent`),children:[(0,$.jsx)(Fr,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,$.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[me.length,` widget`,me.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,$.jsx)(`div`,{ref:ne,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:me.length===0?(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,$.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,$.jsx)(ef,{className:`layout`,layout:z,cols:tf,rowHeight:ie,margin:O?of:af,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:ce,onResizeStop:le,compactType:`vertical`,children:me.map(e=>{let t=h[e],n=hd(t.type),r=_[e]??sf,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,$.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,$.jsx)(Qd,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>fe(e),fill:_[e]??sf,onToggleFill:d?t=>ue(e,t):void 0,children:(0,$.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>pe(e,t),canvas:se})}):(0,$.jsx)(Qd,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>fe(e),children:(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var bf=`data/schema/file`;function xf(e){return String(e.locations?.[0]?.url||``).trim()}function Sf(e){let t=xf(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function Cf(e){return e.schema===bf&&String(e.metadata?.contentType||``).startsWith(`image/`)}function wf(e){let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Tf(e){if(e.schema!==bf)return ns(e);let t=Sf(e),n=String(e.metadata?.contentType||``).trim(),r=wf(e.metadata?.size);return{...ns(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:xf(e),schemaLabel:`file`}}function Ef(e){return/^https?:\/\/[^\s]+$/i.test(e)}function Df(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return Ef(t)?t:null}return t.isExternal&&Ef(t.subtitle)?t.subtitle:Ef(t.title)?t.title:null}function Of(e,t,n=!1){return Lc(e,t,{download:n})}function kf(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>Ef(e)?(0,$.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`underline decoration-muted-foreground underline-offset-2 hover:text-primary`,children:e},`${e}-${t}`):e)}function Af(e){return e?new Date(e).toLocaleString():``}function jf(){let{code:e=``}=wt(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=(0,Q.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,Q.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=Tf(t);return[t.schema,n.title,n.preview,n.subtitle,Sf(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,Q.useCallback)(async()=>{if(e){i(!0);try{let t=await Y.get(`${lo}/pub/c/${encodeURIComponent(e)}`,{skipAuth:!0});n(t),o(null)}catch(e){n(null),o(e instanceof Error?e.message:`Failed to load public canvas`)}finally{i(!1)}}},[e]);(0,Q.useEffect)(()=>{p()},[p]),(0,Q.useEffect)(()=>{if(!e)return;let t=fo(`${uo}/pub`,{transports:[`websocket`],auth:{code:e},reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1500});return t.on(`connect`,()=>c(!0)),t.on(`disconnect`,()=>c(!1)),t.on(`connect_error`,()=>c(!1)),t.on(`canvas:changed`,()=>p()),()=>{t?.disconnect(),t=null}},[e,p]);let m=(0,Q.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,Q.useCallback)(()=>{u(``)},[]),g=(0,Q.useCallback)(async e=>({payload:Js(e?.sortBy)?Yo(d,e.sortBy,e?.order):d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,$.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,$.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,$.jsxs)(kl,{className:`max-w-md bg-card`,children:[(0,$.jsx)(Al,{children:(0,$.jsx)(jl,{children:`Canvas unavailable`})}),(0,$.jsx)(Nl,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,$.jsx)(Yl,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,$.jsx)(zc.Provider,{value:e,children:(0,$.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,$.jsxs)(kl,{className:`bg-card shadow-elevation-3`,children:[(0,$.jsx)(Al,{className:`border-b p-3 sm:p-6`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,$.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-accent text-primary sm:mt-1 sm:h-12 sm:w-12 sm:rounded-2xl`,style:t.canvas.color?{borderLeft:`4px solid ${t.canvas.color}`}:void 0,children:(0,$.jsx)(ri,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground md:hidden`,children:[s?(0,$.jsx)(za,{className:`h-3 w-3 text-success`}):(0,$.jsx)(Nn,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,$.jsx)(jl,{className:`mt-0.5 truncate text-2xl sm:mt-1 sm:text-3xl md:text-5xl`,children:t.canvas.label||t.canvas.name||`Canvas`}),t.canvas.description&&(0,$.jsx)(`p`,{className:`mt-1.5 max-w-3xl text-sm text-muted-foreground sm:mt-3 sm:text-base`,children:t.canvas.description})]})]}),(0,$.jsxs)(`div`,{className:`hidden shrink-0 items-center gap-2 rounded-full border px-3 py-1 text-xs text-muted-foreground md:flex`,children:[s?(0,$.jsx)(za,{className:`h-3.5 w-3.5 text-success`}):(0,$.jsx)(Nn,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,$.jsxs)(Nl,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,$.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,$.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,$.jsxs)(`span`,{className:`truncate`,children:[`· `,Af(t.stats.refreshedAt)]})]}),(0,$.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,$.jsx)(Mf,{label:`Path`,value:t.share.path,mono:!0}),(0,$.jsx)(Mf,{label:`Documents`,value:String(t.stats.documentCount)}),(0,$.jsx)(Mf,{label:`Shown`,value:String(f.length)}),(0,$.jsx)(Mf,{label:`Refreshed`,value:Af(t.stats.refreshedAt)})]}),v&&(0,$.jsx)(`section`,{id:`content-area`,className:`flex w-full flex-col overflow-hidden rounded-2xl border h-viewport-card min-h-[420px] md:h-viewport-pane`,children:(0,$.jsx)(yf,{workspaceId:t.workspace.name,treeName:t.share.treeName,path:t.share.path,layerId:t.canvas.id,querySpec:t.canvas.querySpec,metadata:t.canvas.metadata,readOnly:!0,interactive:!1,fetchDocuments:g},JSON.stringify(_))}),!v&&(0,$.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 border-b px-4 py-3 md:flex-row md:items-center md:justify-between`,children:[(0,$.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,$.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,$.jsx)(Oa,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{type:`search`,value:l,onChange:e=>u(e.target.value),placeholder:`Search loaded documents...`,className:`w-full rounded-md border py-1.5 pl-9 pr-8 text-sm md:w-72`}),l&&(0,$.jsx)(`button`,{type:`button`,onClick:h,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,$.jsx)(ur,{className:`h-4 w-4`})})]}),(0,$.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:p,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,$.jsx)(Un,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,$.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,$.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,$.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,$.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:l.trim()?`No loaded documents match your search.`:`No documents yet.`}):f.map(t=>{let n=Tf(t),r=Df(t,n),i=t.schema===bf,a=i?Of(e,t.id):null,o=a||r;return(0,$.jsxs)(`article`,{className:`p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,$.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,$.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,$.jsxs)(`a`,{href:Of(e,t.id,!0),download:n.title,className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(Ai,{className:`h-3.5 w-3.5`}),`Download`]}),(0,$.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:Af(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,$.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:kf(n.preview)}),Cf(t)&&(0,$.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,$.jsx)(`img`,{src:a||void 0,alt:n.title,loading:`lazy`,className:`max-h-64 max-w-full rounded border bg-muted object-contain transition-opacity hover:opacity-90`})})]},t.id)})})]})]})]}),(0,$.jsx)(Yl,{className:`mt-6 text-center`})]})})})}function Mf({label:e,value:t,mono:n=!1}){return(0,$.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,$.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,$.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var Nf={title:``,content:``,comment:``,tags:[]};function Pf(e,t,n=`add`){let r=sn(),i=Uc(`new:${n}:${e?.mode===`workspace`?`${e.workspaceName}:${e.treeName}:${e.path}`:e?.contextId??`home`}`),a=e=>async(n,i,a)=>{let o=typeof i.workspace==`string`?i.workspace:(await al(e)).workspaceName,s=await r.capture(),c={schema:`data/schema/note`,schemaVersion:`2.0`,comment:n.comment,data:{title:n.title.trim(),content:n.content},metadata:{features:Gc(n.tags),...s?{geo:s}:{}}},l=typeof i.id==`number`?i.id:void 0;if(l==null){let t=await gl(e,[c],{refresh:!1});if(!t.length)throw Error(`The server did not return the saved note`);l=t[0],a({id:l,workspace:o})}else await Tc(o,{...c,id:l});await t?.([l]),vl(e)},o=Rc(i,Nf,{retainAfterSave:!0,valid:e=>!!e.content.trim(),save:e?a(e):void 0});async function s(e){await o.saveWith(a(e));let t=o.getSnapshot().meta.id;if(typeof t!=`number`)throw Error(`Write a note before saving`);return[t]}return{...o.value,status:o.status,error:o.error,storageError:o.storageError,setTitle:e=>o.update({title:e}),setContent:e=>o.update({content:e}),setComment:e=>o.update({comment:e}),setTags:e=>o.update({tags:e}),saving:o.status===`saving`,canSave:!!o.value.content.trim()&&o.status!==`saving`,save:s,finish:o.clear,retry:o.flush,geotag:r}}var Ff=(0,Q.createContext)(void 0);function If(){let e=(0,Q.useContext)(Ff),t=nl()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,Q.useMemo)(()=>e===void 0?n?r===`context`&&i?{mode:`context`,contextId:i}:a&&o?{mode:`workspace`,workspaceName:a,path:o,treeName:s||`context`,treeType:s===`directory`||s===`backends`?`directory`:`context`}:null:null:e,[e,n,r,i,a,o,s])}function Lf({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,Q.useRef)(null),o=(0,Q.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,Q.useEffect)(()=>{o()},[e,o]),(0,$.jsx)(`textarea`,{ref:e=>{a.current=e,i?.(e)},value:e,onChange:e=>t(e.target.value),onBlur:n,placeholder:r,rows:1,spellCheck:!1,className:`w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-sm leading-relaxed text-foreground outline-none placeholder:text-muted-foreground/60`})}function Rf({onLinkTo:e,onDelete:t}){return(0,$.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Link to…`,title:`Link to…`,children:(0,$.jsx)(Pi,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-destructive`,"aria-label":`Delete`,title:`Delete (moves to trash)`,children:(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`})})]})}function zf({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=vo(),[a,o]=(0,Q.useState)(!1);return(0,$.jsx)(zt,{onClose:n,children:(0,$.jsx)(pe,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await vs(a.workspaceName,n,[e],a.treeName,a.treeType);r(`Linked to ${t.length} path${t.length>1?`s`:``}`),n()}catch(e){i(e instanceof Error?e.message:`Failed to link document`),o(!1)}}},documentCount:1,saving:a,sizeClassName:an,tabs:t?[`context`,`directory`,`relations`]:[`context`,`directory`],relationWorkspaceName:t,relationExcludeIds:new Set([e]),onConfirmRelation:async({predicate:a,direction:s,targetIds:c})=>{if(!(!t||!c.length)){o(!0);try{await Sc(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Lt(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var Bf=1200;function Vf(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})+` `+t.toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function Hf(e,t){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([ml(n,[t]),_l(n)]).then(([e,t])=>{r(Array.isArray(e)?e:[]);let n=t.workspaceName||t.workspaceId;l(n?{workspaceName:n,path:t.path||`/`,treeName:t.treeId||`context`,treeType:`context`}:null)}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))}let{workspaceName:n,path:i,treeName:o,treeType:c}=e;return Ks(n,i,[t],{treeName:o,treeType:c,limit:50}).then(e=>{r(e.payload||[]),l({workspaceName:n,path:i,treeName:o,treeType:c})}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))},[e,t]),d=(0,Q.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,Q.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,Q.useEffect)(()=>{u()},[u]),(0,Q.useEffect)(()=>{let e=()=>d();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[d]),{docs:n,setDocs:r,loading:i,error:o,scope:c,reload:d,removeDoc:(0,Q.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await jo(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}function Uf({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let s=Fc(e,t||``,!!t),{title:c,content:l,setTitle:u,setContent:d}=s,f=()=>{s.save().catch(()=>{})};return(0,$.jsxs)(`div`,{ref:t=>n(e.id,t),className:q(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[Vf(e.createdAt),` · #`,e.id]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[(0,$.jsx)(Hc,{...s,onRetry:s.save}),(0,$.jsx)(Rf,{onLinkTo:a,onDelete:o})]})]}),(0,$.jsx)(`input`,{value:c,onChange:e=>u(e.target.value),onBlur:f,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(Lf,{value:l,onChange:d,onBlur:f,innerRef:t=>r(e.id,t)})]})}function Wf({target:e,onCreated:t,onCancel:n}){let r=Pf(e,void 0,`applet`),{title:i,content:a,setTitle:o,setContent:s,saving:c}=r,[l,u]=(0,Q.useState)(null),d=async()=>{try{await r.save(e),r.finish(),t()}catch(e){u(e instanceof Error?e.message:`Failed to save note`)}};return(0,$.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Close note`,children:(0,$.jsx)(ur,{className:`h-3 w-3`})})]}),(0,$.jsx)(`input`,{value:i,onChange:e=>o(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(Lf,{value:a,onChange:s,placeholder:`Write your note…`}),(0,$.jsx)(Hc,{...r,onRetry:r.retry}),l&&(0,$.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,$.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,$.jsx)(`button`,{type:`button`,onClick:d,disabled:!a.trim()||c,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:c?`Saving…`:`Done`})})]})}function Gf({autoAdd:e=!1}){let t=If(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=Hf(t,hs),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(0),[f,p]=(0,Q.useState)(`desc`),[m,h]=(0,Q.useState)(e),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(new Map),y=(0,Q.useRef)(new Map),b=(0,Q.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,Q.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,Q.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await s(e.id)}catch{}},[s]),C=(0,Q.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return f===`asc`?n:-n}),e},[n,f]),w=(0,Q.useMemo)(()=>{let e=c.trim().toLowerCase();if(!e)return[];let t=[];for(let n of C){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[c,C]),T=w.length?w[Math.min(u,w.length-1)]:null;(0,Q.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,Q.useCallback)(e=>{if(!w.length)return;let t=e?(u+1)%w.length:u;e&&d(t);let n=w[t],r=y.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+c.trim().length)),v.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[w,u,c]);return t?(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(Oa,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),d(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),E(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),c.trim()&&(0,$.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:w.length?`${Math.min(u+1,w.length)}/${w.length}`:`0/0`})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:f===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:f===`desc`?(0,$.jsx)(Ci,{className:`h-3.5 w-3.5`}):(0,$.jsx)($i,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>h(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,$.jsx)(Bi,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,$.jsx)(Wf,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)},JSON.stringify(t)),r&&!n.length&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Sa,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,$.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,$.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),C.map(e=>(0,$.jsx)(Uf,{doc:e,updateWorkspace:a?.workspaceName??null,registerEl:b,registerBody:x,highlighted:T?.docId===e.id,onLinkTo:()=>_(e.id),onDelete:()=>S(e)},e.id))]}),g!==null&&(0,$.jsx)(zf,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:bl(t)})}var Kf=`2.1`,qf=new Set([`completed`,`cancelled`]);function Jf({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,Q.useState)(String(e.data?.title??``)),[u,d]=(0,Q.useState)(String(e.data?.description??``)),[f,p]=(0,Q.useState)(e.data?.status||`pending`),[m,h]=(0,Q.useState)(Ge(e.data?.dueDate)),[g,_]=(0,Q.useState)(`idle`),{replicating:v,label:y}=es(e),b=(0,Q.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),x=(0,Q.useRef)(null),S=(0,Q.useRef)(0),w=(0,Q.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++S.current;_(`saving`);try{let i=Se(n.due),a={...e.data||{},title:n.title.trim(),...n.description.trim()?{description:n.description.trim()}:{description:void 0},status:n.status,completed:n.status===`completed`};return i?a.dueDate=i:delete a.dueDate,await Tc(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:a,metadata:e.metadata}),r!==S.current||(b.current={title:n.title,description:n.description},_(`saved`),setTimeout(()=>_(e=>e===`saved`?`idle`:e),1500),!0)}catch{return r===S.current&&_(`error`),!1}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),T=(0,Q.useCallback)((e,t)=>{(e!==b.current.title||t!==b.current.description)&&(_(`dirty`),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>w({title:e,description:t,status:f,due:m}),Bf))},[w,f,m]),E=(0,Q.useCallback)(()=>{x.current&&=(clearTimeout(x.current),null),w({title:c,description:u,status:f,due:m})},[w,c,u,f,m]);(0,Q.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]);let D=(0,Q.useCallback)(async()=>{let t=f,n=f===`completed`?`pending`:`completed`;p(n),await w({title:c,description:u,status:n,due:m})?s(e.id,n):p(t)},[f,w,c,u,m,e.id,s]),O=(0,Q.useCallback)(e=>{h(e),x.current&&=(clearTimeout(x.current),null),w({title:c,description:u,status:f,due:e})},[w,c,u,f]),k=qf.has(f);return(0,$.jsxs)(`div`,{ref:t=>n(e.id,t),className:q(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,$.jsxs)(`span`,{className:`shrink-0`,children:[Vf(e.createdAt),` · #`,e.id,f!==`pending`&&(0,$.jsxs)(`span`,{children:[` · `,He[f]??f]})]}),(0,$.jsx)(C,{value:m,onChange:O,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,$.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,$.jsx)(Sa,{className:`inline h-3 w-3 animate-spin`}),v&&(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,$.jsx)($n,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,$.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,$.jsx)(Rf,{onLinkTo:a,onDelete:o})]})]}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:D,className:`mt-0.5 shrink-0 text-muted-foreground transition-colors hover:text-foreground`,"aria-label":k?`Mark as pending`:`Mark as completed`,title:k?`Mark as pending`:`Mark as completed`,children:k?(0,$.jsx)(gr,{className:`h-4 w-4 text-success`}):(0,$.jsx)(Hi,{className:`h-4 w-4`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),T(e.target.value,u)},onBlur:E,placeholder:`Untitled`,spellCheck:!1,className:q(`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold outline-none placeholder:text-muted-foreground/50`,k?`text-muted-foreground line-through`:`text-foreground`)}),(0,$.jsx)(Lf,{value:u,onChange:e=>{d(e),T(c,e)},onBlur:E,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function Yf({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(_()),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null);return(0,$.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,$.jsx)(ur,{className:`h-3 w-3`})})]}),(0,$.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`What needs doing?`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(Lf,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,$.jsx)(`div`,{className:`mt-2`,children:(0,$.jsx)(C,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,$.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,$.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await gl(e,[{schema:Lo,schemaVersion:Kf,data:ze({title:r,description:a,status:`pending`,priority:``,due:s}),metadata:{features:[]}}]),t()}catch(e){f(e instanceof Error?e.message:`Failed to create todo`),u(!1)}}},disabled:!r.trim()||l,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:l?`Saving…`:`Save todo`})})]})}function Xf({autoAdd:e=!1}){let t=If(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=Hf(t,Lo),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(0),[p,m]=(0,Q.useState)(`desc`),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(e),[y,b]=(0,Q.useState)(null),x=(0,Q.useRef)(new Map),S=(0,Q.useRef)(new Map),C=(0,Q.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,Q.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,Q.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete todo ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await c(e.id)}catch{}},[c]),E=(0,Q.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,Q.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!qf.has(String(e.data?.status??`pending`)));return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return p===`asc`?n:-n}),e},[n,p,h]),O=(0,Q.useMemo)(()=>n.filter(e=>qf.has(String(e.data?.status??`pending`))).length,[n]),k=(0,Q.useMemo)(()=>{let e=l.trim().toLowerCase();if(!e)return[];let t=[];for(let n of D){let r=String(n.data?.description??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[l,D]),A=k.length?k[Math.min(d,k.length-1)]:null;(0,Q.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,Q.useCallback)(e=>{if(!k.length)return;let t=e?(d+1)%k.length:d;e&&f(t);let n=k[t],r=S.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+l.trim().length)),x.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[k,d,l]);return t?(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(Oa,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:l,onChange:e=>{u(e.target.value),f(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),j(!0))},placeholder:`Search todos…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),l.trim()&&(0,$.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:k.length?`${Math.min(d+1,k.length)}/${k.length}`:`0/0`})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:q(`rounded-md border p-1.5 transition-colors`,h?`border-foreground text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:h?`Hide done items`:`Show done items${O?` (${O})`:``}`,"aria-label":h?`Hide done items`:`Show done items`,children:h?(0,$.jsx)(Ca,{className:`h-3.5 w-3.5`}):(0,$.jsx)(gi,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:p===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:p===`desc`?(0,$.jsx)(Ci,{className:`h-3.5 w-3.5`}):(0,$.jsx)($i,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a todo`,children:[(0,$.jsx)(Bi,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,$.jsx)(Yf,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Sa,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,$.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,$.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:O?`Nothing pending - ${O} done item${O>1?`s`:``} hidden.`:`No todos here yet - add the first one.`}),D.map(e=>(0,$.jsx)(Jf,{doc:e,updateWorkspace:o?.workspaceName??null,registerEl:C,registerBody:w,highlighted:A?.docId===e.id,onLinkTo:()=>b(e.id),onDelete:()=>T(e),onStatusSaved:E},e.id))]}),y!==null&&(0,$.jsx)(zf,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:bl(t)})}var Zf=(0,Q.createContext)(null);function Qf(){let e=(0,Q.useContext)(Zf);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function $f(e=!0){let{registerViewer:t}=Qf();(0,Q.useEffect)(()=>{if(e)return t()},[e,t])}var ep=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],tp=`canvas.lens.camera`,np={min:1,max:4,step:.1,hardware:!1};function rp(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(tp)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:ep.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function ip(e,t){let n=ep.find(t=>t.id===e.resolution)??ep[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function ap(e={}){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(e.onEnded);(0,Q.useEffect)(()=>{n.current=e.onEnded});let r=(0,Q.useRef)(null),i=(0,Q.useRef)(null),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(rp),p=(0,Q.useRef)(d),[m,h]=(0,Q.useState)([]),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(1),w=(0,Q.useRef)(1),[T,E]=(0,Q.useState)(!1),D=(0,Q.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,Q.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,Q.useCallback)(async()=>{try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`&&e.deviceId);h(e.map((e,t)=>({deviceId:e.deviceId,label:e.label||`Camera ${t+1}`})))}catch{}},[]),j=(0,Q.useCallback)(()=>{D.current&&window.clearTimeout(D.current),r.current?.getTracks().forEach(e=>e.stop()),r.current=null,t.current&&(t.current.srcObject=null),c(null),o(!1),_(!1),y(null),x(null),C(1),w.current=1,E(!1)},[]),M=(0,Q.useCallback)(async(e,i)=>{r.current=e,e.getVideoTracks().forEach(e=>{e.onended=()=>{j(),n.current?.()}}),t.current&&(t.current.srcObject=e,await t.current.play().catch(()=>{}));let a=e.getVideoTracks()[0],s=a?.getSettings();if(x(s?.width&&s?.height?{width:s.width,height:s.height}:null),_(i),E(!1),i&&a){let e=a.getCapabilities?.()??{};y(e),e.focusMode?.includes(`continuous`)&&await k({focusMode:`continuous`});let t=a.getSettings().zoom;C(e.zoom?t??e.zoom.min:1),w.current=1,A()}c(e),o(!0)},[j,k,A]),N=(0,Q.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:ip(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:ip(e,!1),audio:!1});throw t}},[]),P=(0,Q.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Camera needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getUserMedia)return u(`Camera API not available in this browser.`),!1;try{let e=await N(p.current);return await M(e,!0),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Camera permission denied.`:t===`NotFoundError`?`No camera found.`:`Camera failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M,N]),ee=(0,Q.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Screen capture needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getDisplayMedia)return u(`Screen capture API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1280},height:{ideal:720}},audio:!1});return await M(e,!1),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Screen capture cancelled.`:`Screen capture failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M]),F=(0,Q.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(tp,JSON.stringify(t))}catch{}!r.current||!g||(r.current.getTracks().forEach(e=>{e.onended=null,e.stop()}),r.current=null,P().then(e=>{e||(j(),n.current?.())}))},[g,P,j]),I=(0,Q.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),te=(0,Q.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),L=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),ne=(0,Q.useCallback)(e=>{let t=v?.focusMode??[];if(!t.length)return;D.current&&window.clearTimeout(D.current);let n=navigator.mediaDevices.getSupportedConstraints(),r=e&&n.pointsOfInterest?{pointsOfInterest:[e]}:{};t.includes(`single-shot`)?(k({...r,focusMode:`single-shot`}),t.includes(`continuous`)&&(D.current=window.setTimeout(()=>void k({...r,focusMode:`continuous`}),1500))):k({...r,focusMode:`continuous`})},[v,k]),R=(0,Q.useCallback)((e=640,n=.72)=>{let r=t.current;if(!r||r.readyState<2||!r.videoWidth)return null;let a=Math.max(1,w.current),o=r.videoWidth/a,s=r.videoHeight/a,c=(r.videoWidth-o)/2,l=(r.videoHeight-s)/2,u=Math.min(1,e/Math.max(o,s)),d=Math.round(o*u),f=Math.round(s*u);i.current||=document.createElement(`canvas`);let p=i.current;p.width=d,p.height=f;let m=p.getContext(`2d`);return m?(m.drawImage(r,c,l,o,s,0,0,d,f),p.toDataURL(`image/jpeg`,n)):null},[]);return(0,Q.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:P,startScreen:ee,stop:j,captureFrame:R,camera:(0,Q.useMemo)(()=>g?{devices:m,prefs:d,setPrefs:F,size:b,zoomRange:v?.zoom?{min:v.zoom.min,max:v.zoom.max,step:v.zoom.step||.1,hardware:!0}:np,zoom:S,setZoom:I,torchSupported:!!v?.torch,torch:T,setTorch:te,focusSupported:L,focusAt:ne}:null,[g,m,d,F,b,v,S,I,T,te,L,ne])}}async function op(e,t,n={}){let r={limit:n.limit??12,scope:n.contextPath?`path`:`workspace`};t&&(r.image=t),n.similarTo&&(r.similarTo=n.similarTo);let i=n.q?.trim();i&&(r.q=i),n.maxDistance!=null&&Number.isFinite(n.maxDistance)&&(r.maxDistance=n.maxDistance),n.minDistance!=null&&Number.isFinite(n.minDistance)&&(r.minDistance=n.minDistance),n.debug&&(r.debug=!0),n.idsOnly&&(r.idsOnly=!0),n.contextPath&&(r.context=n.contextPath),n.treeId&&(r.treeNameOrTreeId=n.treeId),n.features&&Object.assign(r,n.features),n.filters&&(r.filters=n.filters),n.applyCanvasQuerySpec!==void 0&&(r.applyCanvasQuerySpec=n.applyCanvasQuerySpec);let a=await Y.postEnvelope(`${qa.workspaces}/${encodeURIComponent(e)}/documents/search/image`,r,n.signal?{signal:n.signal}:void 0),o=a.payload??[],s=n.idsOnly===!0;return{documents:s?[]:o,ids:s?o:o.map(e=>e.id),count:a.count??o.length,totalCount:a.totalCount??o.length,distances:a.debug?.distances??a.debug?.imageDistances??null}}var sp=[{label:`0.5 fps`,ms:2e3},{label:`1 fps`,ms:1e3},{label:`2 fps`,ms:500},{label:`5 fps`,ms:200},{label:`10 fps`,ms:100},{label:`15 fps`,ms:67},{label:`30 fps`,ms:33}],cp=1e3,lp=32,up=12,dp=`canvas.lens.fit`;function fp({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=Qf(),a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,Q.useEffect)(()=>{if(!o)return;let e=window.setTimeout(()=>s(null),900);return()=>window.clearTimeout(e)},[o]);let c=r&&!r.zoomRange.hardware?r.zoom:1;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`video`,{ref:a,muted:!0,playsInline:!0,onClick:t?e=>{let t=a.current;if(!t||!r?.focusSupported||!t.videoWidth)return;let n=t.getBoundingClientRect(),o=(e.clientX-n.left)/n.width,l=(e.clientY-n.top)/n.height,u=.5+(o-.5)/c,d=.5+(l-.5)/c,f=i===`contain`?Math.min(n.width/t.videoWidth,n.height/t.videoHeight):Math.max(n.width/t.videoWidth,n.height/t.videoHeight),p=t.videoWidth*f/n.width,m=t.videoHeight*f/n.height,h=.5+(u-.5)/p,g=.5+(d-.5)/m;h<0||h>1||g<0||g>1||(r.focusAt({x:h,y:g}),s({x:o,y:l,key:Date.now()}))}:void 0,style:c===1?void 0:{transform:`scale(${c})`},className:q(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,$.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute h-10 w-10 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white/90 animate-fade-in`,style:{left:`${o.x*100}%`,top:`${o.y*100}%`}},o.key)]})}function pp({children:e}){let t=nl(),n=(0,Q.useRef)(t);(0,Q.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,Q.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=ap({onEnded:()=>a.current()}),[m,h]=(0,Q.useState)(null),g=(0,Q.useRef)(m);(0,Q.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(cp),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(null),[N,P]=(0,Q.useState)([]),[ee,F]=(0,Q.useState)(null),[I,te]=(0,Q.useState)(null),L=I&&I.frame===ee?I:null,ne=(0,Q.useRef)(null),[R,re]=(0,Q.useState)(0),[z,ie]=(0,Q.useState)(``),[ae,B]=(0,Q.useState)(()=>{try{return localStorage.getItem(dp)===`cover`?`cover`:`contain`}catch{return`contain`}}),oe=(0,Q.useCallback)(e=>{B(e);try{localStorage.setItem(dp,e)}catch{}},[]),se=(0,Q.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:cp,snapshot:!1}),V=(0,Q.useRef)([]),H=(0,Q.useRef)(new Map),ce=(0,Q.useRef)(null),le=(0,Q.useRef)(null),ue=(0,Q.useRef)(null),de=(0,Q.useRef)(0),fe=(0,Q.useRef)(``),pe=(0,Q.useRef)(!1),me=(0,Q.useRef)(async()=>{}),he=(0,Q.useRef)(()=>{});(0,Q.useEffect)(()=>{se.current.text=T,se.current.maxDistance=C===``?NaN:Number(C),se.current.rateMs=x,se.current.paused=y},[T,C,x,y]);let ge=(0,Q.useCallback)(()=>(re(e=>e+1),()=>re(e=>Math.max(0,e-1))),[]),_e=(0,Q.useCallback)(e=>{V.current=[...V.current.slice(-2),e];let t=V.current,r=[...new Set(t.flat())],i=t.length<2?e:r.filter(e=>t.filter(t=>t.includes(e)).length>=2);M(i.length);let a=ce.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(ce.current=i,n.current?.setLensIds(i))},[]),ve=(0,Q.useCallback)((e,t)=>{for(let n of e)H.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);V.current=[...V.current.slice(-2),n];let r=V.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...H.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>H.current.get(e)).filter(e=>!!e);M(s.length),P(s)},[]),ye=(0,Q.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;ue.current?.abort();let a=new AbortController;ue.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await op(t.workspaceRef,e,{q:i&&t.text||void 0,maxDistance:Number.isFinite(t.maxDistance)?t.maxDistance:void 0,contextPath:s?o.activeContextPath:i?t.contextPath:null,treeId:s?o.activeTreeName:null,features:s?o.filters.features:void 0,filters:s?[...tt(o.filters.timeline),..._n(o.filters.geo),...Ee(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?up:lp,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||se.current!==t||!t.running?!1:(de.current=0,A(Math.round(performance.now()-r)),O(null),i?ve(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):_e(c.ids),!0)}catch(e){return a.signal.aborted||se.current!==t||!t.running?!1:(de.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[ve,_e]),be=(0,Q.useCallback)(async()=>{let e=se.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await ye(t,e)}if(se.current.running){let e=Math.max(de.current?Math.min(3e4,1e3*2**Math.min(de.current-1,5)):0,se.current.rateMs-(performance.now()-t));le.current=window.setTimeout(()=>void me.current(),e)}},[p,ye]);(0,Q.useEffect)(()=>{me.current=be},[be]);let xe=(0,Q.useCallback)(()=>{let e=se.current.consumer===`filter`;se.current.running=!1,de.current=0,se.current.consumer=null,le.current&&window.clearTimeout(le.current),ue.current?.abort(),f(),V.current=[],H.current.clear(),ce.current=null,h(null),v(null),b(!1),ie(``),P([]),F(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,Q.useEffect)(()=>{a.current=xe},[xe]);let U=(0,Q.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||pe.current||(se.current.running&&xe(),e===`photo`&&!r.image))return!1;pe.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return pe.current=!1,i?(V.current=[],H.current.clear(),ce.current=null,P([]),M(null),O(null),ie(r.workspaceRef),se.current={...se.current,running:!0,paused:!1,consumer:t,workspaceRef:r.workspaceRef,contextPath:r.contextPath??null,snapshot:e===`photo`},F(e===`photo`?r.image:null),h(e),v(t),b(!1),t===`filter`&&n.current?.setLensIds([]),e===`photo`?he.current(r.image):be(),!0):!1},[u,d,xe,be]),Se=JSON.stringify(t?{contextId:t.state.activeContextId,path:t.state.activeContextPath,tree:t.state.activeTreeName,features:t.state.filters.features,timeline:t.state.filters.timeline,geo:t.state.filters.geo,gps:t.state.filters.lens.gps}:null);(0,Q.useEffect)(()=>{fe.current!==Se&&(fe.current=Se,se.current.consumer===`filter`&&(ue.current?.abort(),V.current=[],ce.current=null,n.current?.setLensIds([])))},[Se]);let W=(0,Q.useCallback)(e=>{se.current.contextPath=e},[]),G=(0,Q.useCallback)(e=>{se.current.paused=e,b(e)},[]),Ce=JSON.stringify([T,C,Se]),we=(0,Q.useRef)(Ce);(0,Q.useEffect)(()=>{we.current=Ce});let Te=(0,Q.useCallback)(e=>{let t=se.current;!t.running||!t.workspaceRef||(ne.current={frame:e,key:we.current},V.current=[],H.current.clear(),ce.current=null,M(null),ye(e,t))},[ye]);(0,Q.useEffect)(()=>{he.current=Te},[Te]);let De=(0,Q.useCallback)(()=>{let e=se.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,F(t),Te(t))},[p,Te]),Oe=(0,Q.useCallback)(()=>{if(se.current.running&&g.current===`photo`){xe();return}se.current.snapshot=!1,ue.current?.abort(),V.current=[],H.current.clear(),F(null)},[xe]),ke=(0,Q.useCallback)(async(e,t,n)=>{let r=se.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,F(e),Te(e),!0):U(`photo`,t,{...n,image:e})},[U,Te]);(0,Q.useEffect)(()=>{if(!ee)return;let e=!0,t=new Image;return t.onload=()=>{e&&te({frame:ee,width:t.naturalWidth,height:t.naturalHeight})},t.src=ee,()=>{e=!1}},[ee]),(0,Q.useEffect)(()=>{if(!ee)return;let e=ne.current;if(e&&e.frame===ee&&e.key===Ce)return;let t=window.setTimeout(()=>Te(ee),350);return()=>window.clearTimeout(t)},[ee,Ce,Te]),(0,Q.useEffect)(()=>{!i||!se.current.running||r&&r===se.current.workspaceRef||xe()},[i,r,xe]);let Ae=(0,Q.useCallback)(()=>{let e=n.current;if(e){if(se.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,Q.useEffect)(()=>xe,[xe]);let je=(0,Q.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:ae,setFit:oe,workspaceRef:z,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:U,setContextPath:W,stop:xe,setPaused:G,snapshot:ee,takeSnapshot:De,clearSnapshot:Oe,snapshotSize:L,searchPhoto:ke,reopen:Ae,hasViewer:R>0,registerViewer:ge}),[m,y,_,s,c,ae,oe,z,x,C,T,l,D,k,j,N,U,W,xe,G,ee,De,Oe,L,ke,Ae,R,ge]);return(0,$.jsxs)(Zf.Provider,{value:je,children:[e,(0,$.jsx)(`video`,{ref:o,muted:!0,playsInline:!0,"aria-hidden":!0,className:`pointer-events-none fixed bottom-0 left-0 h-px w-px opacity-0`})]})}var mp=`h-7 min-w-0 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,hp=`flex h-7 items-center gap-1 rounded-md border border-border px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,gp=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function _p({className:e}){let{camera:t,fit:n,setFit:r}=Qf();if(!t)return null;let{devices:i,prefs:a,setPrefs:o,size:s,zoomRange:c,zoom:l,setZoom:u}=t,d=c.max>c.min;return(0,$.jsxs)(`div`,{className:q(`flex flex-col gap-2`,e),children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,$.jsxs)(`select`,{className:q(mp,`max-w-[12rem] flex-1`),value:a.deviceId??``,onChange:e=>o({deviceId:e.target.value||null}),title:`Camera / lens. On phones with several rear cameras, pick the main or wide one if the picture is too zoomed in.`,"aria-label":`Camera`,children:[(0,$.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,$.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,$.jsx)(`select`,{className:mp,value:a.resolution,onChange:e=>o({resolution:e.target.value}),title:s?`Requested resolution — camera is delivering ${s.width}×${s.height}`:`Requested resolution`,"aria-label":`Resolution`,children:ep.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:hp,title:n===`contain`?`Showing the whole frame — switch to fill the preview`:`Filling the preview (edges cropped) — switch to the whole frame`,"aria-label":n===`contain`?`Fill preview`:`Fit whole frame`,children:n===`contain`?(0,$.jsx)(aa,{className:`h-3.5 w-3.5`}):(0,$.jsx)(mi,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,$.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:hp,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,$.jsx)(La,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:q(hp,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,$.jsx)(Er,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Dn,{className:`h-3.5 w-3.5`})}),s&&(0,$.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,title:c.hardware?`Optical/sensor zoom`:`Digital zoom — crops the searched frame too`,children:[(0,$.jsx)(Gn,{className:`h-3.5 w-3.5 shrink-0`}),(0,$.jsx)(`input`,{type:`range`,min:c.min,max:c.max,step:c.step,value:l,onChange:e=>u(Number(e.target.value)),onDoubleClick:()=>u(c.min),className:`h-1 min-w-0 flex-1 accent-foreground`,"aria-label":`Zoom`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:gp(l)})]})]})}function vp(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=Qf();return e?n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:q(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,$.jsx)(`span`,{className:`pointer-events-none absolute left-2 top-2 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-white`,children:t===`photo`?`Photo`:`Snapshot`}),(0,$.jsx)(`button`,{type:`button`,onClick:i,className:`absolute bottom-2 left-1/2 flex h-9 -translate-x-1/2 items-center gap-1.5 rounded-full bg-black/60 px-3 text-xs font-medium text-white backdrop-blur transition-colors hover:bg-black/75`,title:t===`photo`?`Close the photo and clear its matches`:`Discard the snapshot and go back to the live feed`,children:t===`photo`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ur,{className:`h-3.5 w-3.5`}),` Close`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ja,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Take a snapshot and search it`,title:`Snapshot: freeze this frame and search for similar items`,className:`absolute bottom-2 left-1/2 flex h-12 w-12 -translate-x-1/2 items-center justify-center rounded-full border-4 border-white/90 bg-white/25 text-white shadow-lg backdrop-blur transition-transform hover:bg-white/40 active:scale-90`,children:(0,$.jsx)(Ni,{className:`h-5 w-5`})}):null}async function yp(e,t=1280,n=.85){let r,i=null;try{r=await createImageBitmap(e,{imageOrientation:`from-image`})}catch{i=URL.createObjectURL(e);let t=new Image;t.src=i,await t.decode(),r=t}try{let e=r.width,i=r.height,a=Math.min(1,t/Math.max(e,i)),o=document.createElement(`canvas`);o.width=Math.round(e*a),o.height=Math.round(i*a);let s=o.getContext(`2d`);if(!s)throw Error(`canvas unavailable`);return s.drawImage(r,0,0,o.width,o.height),o.toDataURL(`image/jpeg`,n)}finally{`close`in r&&r.close(),i&&URL.revokeObjectURL(i)}}function bp({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=Qf(),o=(0,Q.useRef)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await yp(r);await a(i,e,{workspaceRef:t,contextPath:n})}catch{u(`Could not read that image.`)}finally{c(!1),o.current&&(o.current.value=``)}}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o.current?.click(),disabled:r||s||!t,className:i,title:l??`Search with a photo from the camera app or gallery`,children:[(0,$.jsx)(An,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,$.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,$.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var xp=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,Sp=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Cp({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=qo(t),{blobUrl:a}=Tt(e,t.id,256,{enabled:i}),o=ns(t);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-(--card-radius) border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,$.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,$.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,$.jsx)(F,{document:t,size:10})}),(0,$.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,$.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function wp(){let e=If(),t=re(),n=Qf(),{rateMs:r,setRateMs:i,text:a,setText:o,maxDistance:s,setMaxDistance:c,latencyMs:l,error:u}=n,d=e?.mode===`workspace`?e.workspaceName:``,f=e?.mode===`workspace`&&e.path!==`/`?e.path:null,p=n.running&&n.consumer===`applet`,m=n.running&&n.consumer!==`applet`,h=p?n.hits:[];$f(p);let g=p?n.snapshotSize??n.camera?.size:null,_=!!g&&g.height>g.width,v=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:y}=n;return(0,Q.useEffect)(()=>{p&&y(f)},[p,f,y]),e?.mode===`workspace`?(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,$.jsx)(`select`,{className:xp,value:r,onChange:e=>i(Number(e.target.value)),title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:sp.map(e=>(0,$.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,$.jsx)(`input`,{className:q(Sp,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,$.jsx)(`input`,{className:q(Sp,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:s,onChange:e=>c(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),p?(0,$.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,$.jsx)(zi,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(`camera`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Rr,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(`screen`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(la,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,$.jsx)(bp,{consumer:`applet`,workspaceRef:d,contextPath:f,disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`})]}),(0,$.jsxs)(`div`,{className:q(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,_?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[p&&(0,$.jsx)(fp,{className:`h-full w-full`,interactive:!0}),p&&(0,$.jsx)(vp,{}),!p&&(0,$.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,$.jsx)(ei,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),p&&(0,$.jsx)(_p,{className:`shrink-0`}),(0,$.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,$.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,$.jsxs)($.Fragment,{children:[n.snapshot?`snapshot`:`live`,` · `,l==null?`searching…`:`${l} ms/frame`,` · `,h.length,` match`,h.length===1?``:`es`,f?` · scoped to ${f}`:``]}):m?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),h.length===0?(0,$.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:p?n.snapshot?`Nothing similar in the snapshot`:`Nothing matching in view`:`Matches appear here`}):(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,$.jsx)(Cp,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}var Tp=`data/schema/`,Ep={"data/schema/file":{label:`Files`,icon:Li},"data/schema/note":{label:`Notes`,icon:ya},"data/schema/task":{label:`Todos`,icon:wi},"data/schema/tab":{label:`Tabs`,icon:Vr},"data/schema/message/email":{label:`Emails`,icon:oi},"data/schema/link":{label:`Links`,icon:Ji},"data/schema/identity":{label:`Identities`,icon:Lr},"data/schema/drawing":{label:`Sketches`,icon:ir}};function Dp(e){return Ep[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:Tr}}function Op(e){return Ep[e]?.icon??Tr}function kp(e){return{...e,lens:Je.lens}}function Ap(e,t,n=!1){let r=n?e=>e:kp;return JSON.stringify(r(e))!==JSON.stringify(r(t??Je))}var jp={savedGeoSelection:null,liveEnabled:!1,liveError:null,t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,addModal:!1,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null,activeContextPath:null,activeContextType:null,activeWorkspaceName:null,activeTreeName:null,activeCanvasId:null,activeContextId:null,activeAccentColor:null,filters:Je,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function Mp(e,t){switch(t.type){case`SET_VIEW`:return{...e,t1Open:t.view!==null,t1View:t.view};case`TOGGLE_VIEW`:return e.t1View===t.view?{...e,t1Open:!1,t1View:null}:{...e,t1Open:!0,t1View:t.view};case`CLOSE_T1`:return{...e,t1Open:!1,t1View:null,t2Open:!1,t2AgentId:null};case`OPEN_T2_AGENT`:return{...e,t2Open:!0,t2AgentId:t.agentId};case`CLOSE_T2`:return{...e,t2Open:!1,t2AgentId:null};case`OPEN_ADD`:return{...e,addOpen:!0,addModal:t.modal??(e.addOpen&&e.addModal),addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addModal:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,addModal:!1,addKind:null,addRelateTo:null,editDocument:t.document,editWorkspaceId:t.workspaceId};case`SET_TOOLS_TAB`:return{...e,toolsTab:t.tab};case`SET_APPS_APPLET`:return{...e,appsAppletId:t.appletId};case`SET_ACCENT_COLOR`:return e.activeAccentColor===t.color?e:{...e,activeAccentColor:t.color};case`SET_GEO_SELECTION`:return{...e,geoSelection:t.selection,isDirty:e.activeContextType===`context`?Ap(e.filters,e.savedFilters,!0)||JSON.stringify(t.selection)!==JSON.stringify(e.savedGeoSelection):e.isDirty};case`SET_SAVED_GEO_SELECTION`:return{...e,savedGeoSelection:t.selection,isDirty:e.activeContextType===`context`?Ap(e.filters,e.savedFilters,!0)||JSON.stringify(e.geoSelection)!==JSON.stringify(t.selection):e.isDirty};case`SET_MAP_DOCUMENTS`:return e.mapDocuments===t.documents&&e.mapWorkspaceId===t.workspaceId?e:{...e,mapDocuments:t.documents,mapWorkspaceId:t.workspaceId};case`SET_NAVIGATION`:{let n=e.activeContextType===t.contextType&&e.activeContextId===t.contextId&&e.activeCanvasId===t.canvasId;return{...e,activeWorkspaceName:t.workspaceName,activeTreeName:t.treeName,activeCanvasId:t.canvasId,activeContextId:t.contextId,activeContextType:t.contextType,activeContextPath:t.contextPath,geoSelection:null,...n?{}:{filters:Je,savedFilters:null,savedSearchQuery:null,isDirty:!1,savedGeoSelection:null,liveEnabled:!1,liveError:null}}}case`SET_CONTEXT_SCOPE`:return e.activeContextType!==`context`||e.activeWorkspaceName===t.workspaceName&&e.activeContextPath===t.contextPath&&e.activeTreeName===t.treeId?e:{...e,activeWorkspaceName:t.workspaceName,activeContextPath:t.contextPath,activeTreeName:t.treeId};case`SET_LIVE`:return{...e,liveEnabled:t.enabled,liveError:null};case`SET_LIVE_ERROR`:return{...e,liveError:t.error};case`SET_FILTERS`:return{...e,filters:t.filters,isDirty:e.activeContextType===null?!1:Ap(t.filters,e.savedFilters,e.activeContextType===`context`)||e.activeContextType===`context`&&JSON.stringify(e.geoSelection)!==JSON.stringify(e.savedGeoSelection)};case`SET_SAVED_FILTERS`:{let n=t.hydrating===!0&&e.isDirty,r=n?e.filters:t.savedFilters??Je;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?Ap(r,t.savedFilters,e.activeContextType===`context`):!1}}case`SET_SAVING`:return{...e,isSaving:t.isSaving};case`SET_BITMAPS`:return{...e,availableBitmaps:t.keys,bitmapsLoading:!1};case`SET_BITMAPS_LOADING`:return{...e,bitmapsLoading:t.loading};case`SET_TIMELINES`:return{...e,availableTimelines:t.names,timelineScales:t.scales??e.timelineScales,timelinesLoading:!1};case`SET_TIMELINES_LOADING`:return{...e,timelinesLoading:t.loading};default:return e}}var Np=`toolbox:session:filters`;function Pp(){try{let e=localStorage.getItem(Np);if(!e)return null;let t=JSON.parse(e);return{...Je,...t,features:{...Je.features,...t.features??{}},timeline:{...Je.timeline,...t.timeline??{}},geo:{...Je.geo,...t.geo??{}},lens:Je.lens,sort:mn(t.sort)}}catch{return null}}function Fp(e){try{localStorage.setItem(Np,JSON.stringify(kp(e)))}catch{}}function Ip(e,t=!1){if(!e?.toolbox)return null;try{let n=e.toolbox;return{features:{allOf:n.features?.allOf??[],anyOf:n.features?.anyOf??[],noneOf:n.features?.noneOf??[]},timeline:{quickFilter:n.timeline?.quickFilter??null,customRanges:n.timeline?.customRanges??(n.timeline?.customRange?[n.timeline.customRange]:[]),indexCreated:n.timeline?.indexCreated??!0,indexUpdated:n.timeline?.indexUpdated??!0,indexDeleted:n.timeline?.indexDeleted??!1,contentEvents:n.timeline?.contentEvents??!1,selectedTimelines:n.timeline?.selectedTimelines??[]},geo:{bbox:n.geo?.bbox??null,includeUnlocated:n.geo?.includeUnlocated??!1},lens:t?{...Je.lens,...n.lens??{}}:Je.lens,sort:mn(n.sort)}}catch{return null}}function Lp(e,t){let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)break;return n}function Rp({children:e,target:t}){let[n,r]=(0,Q.useReducer)(Mp,jp),i=Bt(),a=Qt(),o=new URLSearchParams(i.search).get(`ownerId`)||void 0,s=(0,Q.useRef)(null),c=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{c.current=n}),(0,Q.useEffect)(()=>{let e=!1,n=i.pathname.split(`/`).filter(Boolean),a=t===void 0?n[0]===`workspaces`&&decodeURIComponent(n[1]||``)||null:t?.mode===`workspace`?t.workspaceName:null,o=t===void 0?n[0]===`contexts`&&decodeURIComponent(n[1]||``)||null:t?.mode===`context`?t.contextId:null,{path:s,treeName:l}=t?.mode===`workspace`?t:a?Jd(i.pathname):{path:`/`,treeName:``},u=t=>{if(e)return;let n=t?`canvas`:o?`context`:null,i=c.current;i.activeContextType!==null&&n===null&&Fp(i.filters),r({type:`SET_NAVIGATION`,workspaceName:a,treeName:a?l:null,canvasId:t,contextId:o,contextType:n,contextPath:a?s:null})};return a&&s!==`/`?(Wo(a,l).then(t=>{if(e)return;let n=Lp(t,s);u(n?.type===`canvas`?n.id:null)}).catch(()=>u(null)),()=>{e=!0}):(u(null),()=>{e=!0})},[i.pathname,t]),(0,Q.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_BITMAPS_LOADING`,loading:!0}),Do(e).then(e=>{r({type:`SET_BITMAPS`,keys:e})}))},[n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),Xo(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let{activeContextType:e,activeCanvasId:t,activeWorkspaceName:i,activeTreeName:a,activeContextPath:o}=n;if(e!==`context`){if(e===`canvas`&&t&&i&&o)Wo(i,a||`context`).then(e=>{let t=Lp(e,o),n=Ip(t?.metadata);r({type:`SET_SAVED_FILTERS`,savedFilters:n,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{r({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=Pp();r({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[n.activeCanvasId,n.activeContextPath,n.activeContextType,n.activeTreeName,n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let{activeContextType:e,activeContextId:t}=n;if(e!==`context`||!t)return;let l=!1;s.current=null;let u=0,d=e=>{let t=new URLSearchParams(window.location.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let n=t.toString();a(`${i.pathname}${n?`?${n}`:``}${window.location.hash}`,{replace:!0})},f=(e,t,n,i=null,a=n?[n]:[])=>{let o=e?.filters??t??Je,c=e?.geoSelection??i;s.current=JSON.stringify({filters:o,geoSelection:c,queries:e?.queries??a}),r({type:`SET_SAVED_FILTERS`,savedFilters:t,savedSearchQuery:n}),r({type:`SET_FILTERS`,filters:o}),r({type:`SET_GEO_SELECTION`,selection:c}),r({type:`SET_SAVED_GEO_SELECTION`,selection:i}),r({type:`SET_LIVE`,enabled:e!==null}),d(e?.queries??a)},p=e=>{let n=++u;return _l(t,o).then(t=>{if(l||n!==u)return;let i=t.metadata,a=Ip(i,!0),o=typeof i?.toolboxSearchQuery==`string`?i.toolboxSearchQuery:null;if(r({type:`SET_CONTEXT_SCOPE`,workspaceName:t.workspaceName||t.workspaceId||null,contextPath:t.path||`/`,treeId:t.treeId||null}),t.liveQuery)f(t.liveQuery,a,o,i?.toolboxGeoSelection??null,t.queryOptions?.queries);else if(e){r({type:`SET_LIVE`,enabled:!1});let e=c.current.isDirty?c.current.filters:a??Je,n=i?.toolboxGeoSelection??null;s.current=JSON.stringify({filters:e,geoSelection:n,queries:[]}),r({type:`SET_SAVED_FILTERS`,savedFilters:a,savedSearchQuery:o,hydrating:!0}),r({type:`SET_GEO_SELECTION`,selection:n}),r({type:`SET_SAVED_GEO_SELECTION`,selection:n});let l=new URLSearchParams(window.location.search),u=t.queryOptions?.queries?.length?t.queryOptions.queries:o?[o]:[];!l.has(`q`)&&!l.has(`search`)&&u.length&&d(u)}}).catch(e=>{l||n!==u||r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not load context`})})};p(!0);let m=()=>{p(!1)},h=w.on(`context.url.set`,e=>{e?.id===t&&m()}),g=w.on(`context.updated`,e=>{let n=e;if((n.contextId||n.id)!==t)return;if(!n.metadata){p(!0);return}++u;let r=Ip(n.metadata,!0);f(n.liveQuery??null,r,typeof n.metadata.toolboxSearchQuery==`string`?n.metadata.toolboxSearchQuery:null,n.metadata.toolboxGeoSelection??null,n.queryOptions?.queries)}),_=w.on(`connect`,()=>{p(!0)}),v=w.on(`disconnect`,()=>{c.current.liveEnabled&&r({type:`SET_LIVE_ERROR`,error:`Disconnected — Live updates will resume when connected.`})});return window.addEventListener(`contexts:refresh`,m),()=>{l=!0,s.current=null,h(),g(),_(),v(),window.removeEventListener(`contexts:refresh`,m)}},[n.activeContextId,n.activeContextType,o]);let l=(0,Q.useMemo)(()=>{let e=new URLSearchParams(i.search),t=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),n=(e.get(`search`)||``).trim();return t.length?t:n?[n]:[]},[i.search]),u=(0,Q.useRef)(l);(0,Q.useEffect)(()=>{u.current=l},[l]);let d=(0,Q.useRef)(!1),f=(0,Q.useRef)(null),[p,m]=(0,Q.useState)(0);(0,Q.useEffect)(()=>()=>{f.current!==null&&window.clearTimeout(f.current),f.current=null},[n.activeContextType,n.activeContextId,n.liveEnabled,o]),(0,Q.useEffect)(()=>{n.activeContextType!==`context`||!n.activeContextId||o||!n.liveEnabled||s.current===null||d.current||f.current!==null||!w.isConnected()||JSON.stringify({filters:n.filters,geoSelection:n.geoSelection,queries:l})!==s.current&&(f.current=window.setTimeout(()=>{f.current=null;let e=c.current;if(e.activeContextId!==n.activeContextId||!e.liveEnabled)return;let t=u.current,i=JSON.stringify({filters:e.filters,geoSelection:e.geoSelection,queries:t});if(i===s.current)return;let a=s.current;d.current=!0;let o={filters:e.filters,geoSelection:e.geoSelection,queries:t,binding:bn(e.filters,e.geoSelection,t)};w.request(`context.filters.set`,{contextId:e.activeContextId,liveQuery:o}).then(()=>{c.current.activeContextId===e.activeContextId&&s.current===a&&(s.current=i,r({type:`SET_LIVE_ERROR`,error:null}))}).catch(t=>{c.current.activeContextId===e.activeContextId&&r({type:`SET_LIVE_ERROR`,error:t instanceof Error?t.message:`Live update failed`})}).finally(()=>{d.current=!1,m(e=>e+1)})},n.liveError?1500:100))},[n.activeContextType,n.activeContextId,n.liveEnabled,n.filters,n.geoSelection,l,o,p,n.liveError]);let h=(0,Q.useCallback)(async e=>{let t=c.current;if(t.activeContextType!==`context`||!t.activeContextId||o)return;let n=l,i=e?{filters:t.filters,geoSelection:t.geoSelection,queries:n,binding:bn(t.filters,t.geoSelection,n)}:null;try{await w.request(`context.filters.set`,{contextId:t.activeContextId,liveQuery:i}),s.current=JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:n}),r({type:`SET_LIVE`,enabled:e})}catch(e){r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not change Live mode`})}},[o,l]);(0,Q.useEffect)(()=>{n.activeContextType===null&&Fp(n.filters)},[n.filters,n.activeContextType]);let g=(0,Q.useCallback)(e=>r({type:`SET_VIEW`,view:e}),[]),_=(0,Q.useCallback)(e=>r({type:`TOGGLE_VIEW`,view:e}),[]),v=(0,Q.useCallback)(()=>r({type:`CLOSE_T1`}),[]),y=(0,Q.useCallback)(e=>r({type:`OPEN_T2_AGENT`,agentId:e}),[]),b=(0,Q.useCallback)(()=>r({type:`CLOSE_T2`}),[]),x=(0,Q.useCallback)(e=>r({type:`OPEN_ADD`,kind:e}),[]),S=(0,Q.useCallback)(e=>r({type:`OPEN_ADD`,kind:null,modal:e?.modal,relateTo:e?.fresh?null:void 0}),[]),C=(0,Q.useCallback)((e,t=!1)=>r({type:`OPEN_ADD`,kind:null,relateTo:e,modal:t}),[]),T=(0,Q.useCallback)(()=>r({type:`CLOSE_ADD`}),[]),E=(0,Q.useCallback)((e,t)=>r({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),D=(0,Q.useCallback)(e=>r({type:`SET_TOOLS_TAB`,tab:e}),[]),O=(0,Q.useCallback)(e=>r({type:`SET_APPS_APPLET`,appletId:e}),[]),k=(0,Q.useCallback)(e=>r({type:`SET_ACCENT_COLOR`,color:e}),[]),A=(0,Q.useCallback)(e=>{r({type:`SET_FILTERS`,filters:e})},[]),j=(0,Q.useCallback)((e,t)=>{let{filters:n}=c.current,i=e.startsWith(Tp),a=i?n.features.allOf.filter(t=>t!==e):t?[...new Set([...n.features.allOf,e])]:n.features.allOf.filter(t=>t!==e),o=i&&t?[...new Set([...n.features.anyOf,e])]:n.features.anyOf.filter(t=>t!==e),s=n.features.noneOf.filter(t=>t!==e);r({type:`SET_FILTERS`,filters:{...n,features:{allOf:a,anyOf:o,noneOf:s}}})},[]),M=(0,Q.useCallback)((e,t)=>{let{filters:n}=c.current,i=n.features.allOf.filter(t=>t!==e),a=n.features.anyOf.filter(t=>t!==e),o=n.features.noneOf.filter(t=>t!==e);t===`allOf`?i.push(e):t===`anyOf`?a.push(e):t===`noneOf`&&o.push(e),r({type:`SET_FILTERS`,filters:{...n,features:{allOf:i,anyOf:a,noneOf:o}}})},[]),N=(0,Q.useCallback)(()=>{let{filters:e}=c.current;r({type:`SET_GEO_SELECTION`,selection:null}),r({type:`SET_FILTERS`,filters:{...Je,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}});let t=new URLSearchParams(i.search);t.delete(`q`),t.delete(`search`),t.set(`q`,``),a({pathname:i.pathname,search:t.toString(),hash:i.hash},{replace:!0})},[i.pathname,i.search,i.hash,a]),P=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),ee=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),F=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),I=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),te=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),L=(0,Q.useCallback)(e=>{r({type:`SET_GEO_SELECTION`,selection:e})},[]),ne=(0,Q.useCallback)((e,t=null)=>{r({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),R=(0,Q.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:n,activeTreeName:a,activeContextPath:s,filters:u,geoSelection:d,isSaving:f}=c.current;if(!f){r({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&n&&s){let e=a||`context`,t=Lp(await Wo(n,e),s),r=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await Mo(n,s,{metadata:{...t?.metadata||{},toolbox:kp(u)},querySpec:{features:u.features,filters:[...tt(u.timeline),..._n(u.geo)],query:r.trim()||void 0,sort:u.sort?.sortBy?u.sort:null}},e),Vs(n,e)}else if(e===`context`&&t){let e=(await _l(t,o)).metadata||{},n=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await rl(t,{metadata:{...e,toolbox:u,toolboxGeoSelection:d,toolboxSearchQuery:n.trim()||void 0},...bn(u,d,l)},o)}let c=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;r({type:`SET_SAVED_FILTERS`,savedFilters:u,savedSearchQuery:c.trim()||null,hydrating:!0}),e===`context`&&r({type:`SET_SAVED_GEO_SELECTION`,selection:d})}finally{r({type:`SET_SAVING`,isSaving:!1})}}},[i.search,o,l]),re=(0,Q.useCallback)(e=>{let t=c.current.availableBitmaps.filter(t=>t!==e);r({type:`SET_BITMAPS`,keys:t});let n=c.current.filters,i={...n,features:{allOf:n.features.allOf.filter(t=>t!==e),anyOf:n.features.anyOf.filter(t=>t!==e),noneOf:n.features.noneOf.filter(t=>t!==e)}};JSON.stringify(i.features)!==JSON.stringify(n.features)&&r({type:`SET_FILTERS`,filters:i})},[]),z=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await wc(t,e),re(e)},[re]),ie=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await fs(t,e);return re(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[re]),ae=(0,Q.useCallback)(()=>{let e=c.current.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),Xo(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[]),B=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await ls(t,e),ae()},[ae]),oe=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await $o(t,e);let n=c.current.availableTimelines.filter(t=>t!==e);r({type:`SET_TIMELINES`,names:n});let i=c.current.filters,a=i.timeline.selectedTimelines.filter(t=>t!==e);a.length!==i.timeline.selectedTimelines.length&&r({type:`SET_FILTERS`,filters:{...i,timeline:{...i.timeline,selectedTimelines:a}}})},[]),{features:se,timeline:V,geo:H,lens:ce}=n.filters,le=se.allOf.length>0||se.anyOf.length>0||se.noneOf.length>0||V.quickFilter!==null||(V.customRanges?.length??0)>0||(V.selectedTimelines?.length??0)>0||H.bbox!==null||ce.gps!==null||ce.ids!==null||n.geoSelection!==null;return(0,$.jsx)(Zc.Provider,{value:{state:n,setView:g,toggleView:_,closeT1:v,openAgentT2:y,closeT2:b,openAdd:x,openAddPicker:S,openAddRelated:C,closeAdd:T,openEdit:E,setToolsTab:D,openApplet:O,setAccentColor:k,setFilters:A,setFeatureToggle:j,setFeatureMode:M,clearFilters:N,hasActiveFilters:le,setTimelineFilter:ee,setGeoBBox:F,setLensGps:I,setLensIds:te,setGeoSelection:L,setMapDocuments:ne,setSort:P,setLiveEnabled:h,saveFilters:R,deleteBitmap:z,deleteDataset:ie,createTimeline:B,deleteTimeline:oe,refreshTimelines:ae},children:e})}function zp(e){let t=new URLSearchParams(e),n=t.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(t.get(`search`)||``).trim();return t.has(`q`)?n:r?[r]:[]}function Bp(){let{state:e,setFilters:t}=Qc();return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:e.filters.geo.includeUnlocated??!1,onChange:n=>t({...e.filters,geo:{...e.filters.geo,includeUnlocated:n.target.checked}})}),`Include documents without a location`]})}var Vp=p(),Hp=n(Kc(),1);qc();var Up=`#8b5cf6`,Wp=`#94a3b8`,Gp={color:Up,weight:2,fillColor:Up,fillOpacity:.12},Kp={color:Up,weight:2,dashArray:`5,5`,fillColor:Up,fillOpacity:.06},qp=e=>Math.round(e*1e6)/1e6;function Jp(e){let t=e<10?32:e<100?38:44,n=`<div style="display:flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:9999px;background:${Up};color:#fff;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4);font:600 12px system-ui,sans-serif;cursor:pointer">${e}</div>`;return Hp.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var Yp=e=>e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e]),Xp=new Map;function Zp(e){let t=Xp.get(e);return t??(t=(0,Vp.renderToStaticMarkup)((0,Q.createElement)(Op(e),{width:13,height:13,strokeWidth:2.5})),Xp.set(e,t)),t}var Qp=new Map;function $p(e,t){let n=`${e}|${+!!t}`,r=Qp.get(n);if(!r){let i=`<div style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:9999px;background:${t?Up:Wp};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${Zp(e)}</div>`;r=Hp.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),Qp.set(n,r)}return r}function em(){let{state:e,setGeoSelection:t,setGeoBBox:n}=Qc(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=re(),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(null),p=(0,Q.useRef)([]),m=(0,Q.useRef)(!1),[h,g]=(0,Q.useState)(`idle`),[_,v]=(0,Q.useState)(0),y=(0,Q.useRef)(h),x=(0,Q.useMemo)(()=>r.reduce((e,t)=>e+ +!!b(t),0),[r]),S=(0,Q.useMemo)(()=>i?r.reduce((e,t)=>{let n=b(t);return e+(n&&kt(n.lat,n.lon,i)?1:0)},0):0,[r,i]),C=(0,Q.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&Hp.default.polyline(t,Kp).addTo(e),t.forEach(t=>Hp.default.circleMarker(t,{radius:4,color:Up,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),w=(0,Q.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),T=(0,Q.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:qp(e.lat),lon:qp(e.lng)}))}),w(),g(`idle`)},[t,w]),E=(0,Q.useCallback)(()=>{w(),g(`idle`),t(null),n(null)},[w,t,n]);(0,Q.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=Hp.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});Hp.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=Hp.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>Jp(e.getChildCount())}).addTo(t),f.current=Hp.default.layerGroup().addTo(t),l.current=t;let r=t.getContainer(),i=null,a=null,o=()=>{a&&=(a.remove(),null)},s=e=>{if(y.current===`rect`){e.preventDefault(),i=t.mouseEventToLatLng(e),o();try{r.setPointerCapture(e.pointerId)}catch{}}},m=e=>{if(y.current!==`rect`||!i)return;e.preventDefault();let n=Hp.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=Hp.default.rectangle(n,Kp).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=Hp.default.latLngBounds(i,t.mouseEventToLatLng(e));i=null,o();try{r.releasePointerCapture(e.pointerId)}catch{}let s=a.getSouthWest(),c=a.getNorthEast();s.lat!==c.lat&&s.lng!==c.lng&&n({minLat:qp(s.lat),minLon:qp(s.lng),maxLat:qp(c.lat),maxLon:qp(c.lng)}),g(`idle`)};r.addEventListener(`pointerdown`,s),r.addEventListener(`pointermove`,m),r.addEventListener(`pointerup`,h),r.addEventListener(`pointercancel`,h);let _=e=>{y.current===`polygon`&&(p.current=[...p.current,e.latlng],v(p.current.length),C())};t.on(`click`,_);let b=new ResizeObserver(()=>t.invalidateSize());b.observe(e);let x=window.setTimeout(()=>t.invalidateSize(),120);return()=>{r.removeEventListener(`pointerdown`,s),r.removeEventListener(`pointermove`,m),r.removeEventListener(`pointerup`,h),r.removeEventListener(`pointercancel`,h),t.off(`click`,_),b.disconnect(),window.clearTimeout(x),t.remove(),l.current=null,u.current=null,f.current=null,d.current=null}},[t,n,C]),(0,Q.useEffect)(()=>{y.current=h;let e=l.current;if(!e)return;let t=e.getContainer();h!==`polygon`&&p.current.length&&w(),h===`rect`?(e.dragging.disable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=`none`):h===`polygon`?(e.dragging.enable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=``):(e.dragging.enable(),e.doubleClickZoom.enable(),t.style.cursor=``,t.style.touchAction=``)},[h,w]),(0,Q.useEffect)(()=>{let e=l.current,t=c.current;if(!e||!t)return;let n=new ResizeObserver(()=>e.invalidateSize());return n.observe(t),()=>n.disconnect()},[]),(0,Q.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=b(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||kt(t.lat,t.lon,i),c=Hp.default.marker([t.lat,t.lon],{icon:$p(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(Yp(ns(e).title),{direction:`top`,offset:[0,-14]}),c.on(`click`,()=>{y.current===`idle`&&s(e,a??``)}),o.push(c)}t.addLayers(o),!m.current&&n.length&&!i&&(m.current=!0,e.fitBounds(Hp.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,Q.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=Hp.default.layerGroup();o&&Hp.default.rectangle(Hp.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),Gp).addTo(t),i?.kind===`polygon`&&Hp.default.polygon(i.points.map(e=>[e.lat,e.lon]),Gp).addTo(t),t.addTo(e),d.current=t},[o,i]);let D=h===`rect`?`Drag a box on the map…`:h===`polygon`?`Tap to add points${_?` · ${_}`:``}`:o||i?`Area selected`:`Pan & pick an area`,O=`flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors`;return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:q(O,h===`rect`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Drag a rectangle to select an area`,children:[(0,$.jsx)(pa,{className:`h-3.5 w-3.5`}),`Box`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:q(O,h===`polygon`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Tap points to enclose an area`,children:[(0,$.jsx)(Sr,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:T,disabled:_<3,className:q(O,`border-primary bg-primary text-primary-foreground hover:bg-primary disabled:opacity-40 disabled:hover:bg-primary`),title:`Close the polygon and filter`,children:[(0,$.jsx)($n,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,$.jsx)(`button`,{type:`button`,onClick:w,className:q(O,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:E,disabled:!o&&!i&&h===`idle`,className:q(O,`border-border text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent`),title:`Clear the area selection`,children:[(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,$.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:D})]}),(0,$.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,$.jsx)(`div`,{ref:c,className:`absolute inset-0`}),x===0&&(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,$.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border px-3 py-2 shrink-0 text-[11px] text-muted-foreground`,children:[(0,$.jsx)(Ii,{className:`h-3 w-3`}),x,` of `,r.length,` located`,i&&(0,$.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,S,` in area`]})]})]})}var tm=[{label:`25 m`,m:25},{label:`100 m`,m:100},{label:`500 m`,m:500},{label:`2 km`,m:2e3},{label:`10 km`,m:1e4}],nm=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,rm=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,im=e=>Math.round(e*1e4)/1e4;function am(){let{state:e,setLensGps:t,setLensIds:n}=Qc(),r=e.filters.lens,i=e.activeWorkspaceName,a=r.gps?.radiusM??100,[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(r.gps?.radiusM??100),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(0),[m,h]=(0,Q.useState)(`prompt`),g=(0,Q.useRef)(null),_=(0,Q.useRef)(c);(0,Q.useEffect)(()=>{_.current=c},[c]);let v=`geolocation`in navigator&&window.isSecureContext;(0,Q.useEffect)(()=>{if(!navigator.permissions?.query)return;let e=null;return navigator.permissions.query({name:`geolocation`}).then(t=>{e=t,h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`),t.onchange=()=>h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`)}).catch(()=>{}),()=>{e&&(e.onchange=null)}},[]),(0,Q.useEffect)(()=>{if(!o||!v)return;let e=navigator.geolocation.watchPosition(e=>{let n=im(e.coords.latitude),r=im(e.coords.longitude);t({lat:n,lon:r,radiusM:_.current})},e=>d(e.code===e.PERMISSION_DENIED?`Location permission denied.`:e.message),{enableHighAccuracy:!0,maximumAge:15e3,timeout:2e4});return g.current=e,()=>{navigator.geolocation.clearWatch(e),g.current=null}},[o,v,f,t]);let y=e=>{s(e),d(null),e||t(null)},b=()=>{d(null),s(!0),p(e=>e+1)},x=e=>{l(e),r.gps&&t({...r.gps,radiusM:e})},S=Qf(),{rateMs:C,setRateMs:w,maxDistance:T,setMaxDistance:E,error:D}=S,O=S.running&&S.consumer===`filter`,k=S.running&&S.consumer!==`filter`;$f(O);let A=t=>{i&&S.start(t,`filter`,{workspaceRef:i,contextPath:e.activeContextPath})},j=O,M=S.snapshotSize??S.camera?.size,N=!!M&&M.height>M.width;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[e.activeContextType===`context`&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Point the camera at an object to find visually related content in this context. `,e.liveEnabled?`Bound devices follow your matches as you move.`:`Enable Live to show the matches on your other devices.`]}),(0,$.jsx)(Bp,{}),(0,$.jsxs)(`section`,{className:`space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,disabled:!v,onChange:e=>y(e.target.checked)}),(0,$.jsx)(Wi,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`span`,{children:`Track this device’s GPS`})]}),(0,$.jsx)(`select`,{className:nm,value:c,onChange:e=>x(Number(e.target.value)),disabled:!o,children:tm.map(e=>(0,$.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?m===`denied`?(0,$.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):u?(0,$.jsxs)(`span`,{className:`text-destructive`,children:[u,` `,(0,$.jsx)(`button`,{type:`button`,onClick:b,className:`underline hover:text-foreground`,children:`Request again`})]}):r.gps?`Showing documents within ${a>=1e3?`${a/1e3} km`:`${a} m`} of ${r.gps.lat}, ${r.gps.lon}.`:o?`Waiting for a position fix…`:`Resurface documents geotagged near your current position.`:`Needs a secure context (https or localhost) with location access.`})]}),(0,$.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,$.jsxs)(`button`,{type:`button`,onClick:S.stop,className:`flex h-7 items-center gap-1 rounded-md bg-destructive px-2.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,children:[(0,$.jsx)(zi,{className:`h-3.5 w-3.5`}),` `,S.source===`photo`?`Close photo`:`Stop ${S.source===`camera`?`camera`:`recording`}`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>A(`camera`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Rr,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>A(`screen`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(la,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,$.jsx)(bp,{consumer:`filter`,workspaceRef:i??``,contextPath:e.activeContextPath,disabled:k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`}),(0,$.jsx)(`select`,{className:nm,value:C,onChange:e=>w(Number(e.target.value)),disabled:!i,title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:sp.map(e=>(0,$.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,$.jsx)(`input`,{className:q(rm,`w-24`),placeholder:`max dist`,inputMode:`decimal`,value:T,onChange:e=>E(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K (loose but tunable).`})]}),(0,$.jsxs)(`div`,{className:q(`relative overflow-hidden rounded-lg border border-border bg-black/80`,j?N?`aspect-[3/4] max-h-[60vh]`:`aspect-video`:`hidden`),children:[(0,$.jsx)(fp,{className:`h-full w-full`,interactive:!0}),(0,$.jsx)(vp,{})]}),j&&(0,$.jsx)(_p,{}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?(0,$.jsx)(`span`,{className:`text-destructive`,children:D}):j?S.snapshot?`Snapshot: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. The photo is not stored. Tap Live to resume the feed.`:`Live: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. Tap the shutter to search one still frame. Frames are ephemeral, never stored. Closing the toolbox keeps it running.`:k?`The Lens applet is using the camera. Stop it there first.`:r.ids===null?i?`Point a camera (or share a screen). The view narrows to what the feed matches.`:`Open a workspace to refine with a live feed.`:`The current view holds ${r.ids.length} camera match${r.ids.length===1?``:`es`}. Save to keep this view, or clear matches to remove the camera filter.`}),!j&&r.ids!==null&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(null),className:`min-h-10 rounded-md border border-border px-3 text-xs hover:bg-muted`,children:`Clear matches`})]})]})}var om={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function sm(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t%360+360)%360}function cm(e){return om[e]??`oklch(var(--data-l) var(--data-c) ${sm(e)})`}var lm=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],um=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],dm=[`Yesterday`,`Today`,`Tomorrow`],fm=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],pm=10,mm=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function hm(e,t){let n=new Date;switch(e){case`millennium`:{let e=Math.floor(n.getFullYear()/1e3)*1e3;return new Date(e-t*1e3,0,1)}case`century`:{let e=Math.floor(n.getFullYear()/100)*100;return new Date(e-t*100,0,1)}case`decade`:{let e=Math.floor(n.getFullYear()/10)*10;return new Date(e-t*10,0,1)}case`year`:return new Date(n.getFullYear()-t,0,1);case`month`:return new Date(n.getFullYear(),n.getMonth()-t,1);case`week`:{let e=(n.getDay()+6)%7,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()-e);return r.setDate(r.getDate()-t*7),r}}}function gm(e,t){let n=new Date(t);switch(e){case`millennium`:n.setFullYear(n.getFullYear()+1e3);break;case`century`:n.setFullYear(n.getFullYear()+100);break;case`decade`:n.setFullYear(n.getFullYear()+10);break;case`year`:n.setFullYear(n.getFullYear()+1);break;case`month`:n.setMonth(n.getMonth()+1);break;case`week`:n.setDate(n.getDate()+7)}return n}function _m(e,t,n){if(n===0)return`Now`;switch(e){case`millennium`:case`century`:case`decade`:{let e=t.getFullYear();return e<=0?`${1-e} BCE`:`${e}`}case`year`:return`${t.getFullYear()}`;case`month`:return`${mm[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${mm[t.getMonth()]} – ${e.getDate()} ${mm[e.getMonth()]}`}}}function vm(e,t){return Array.from({length:t},(t,n)=>{let r=hm(e,n),i=gm(e,r);return{offset:n,label:_m(e,r,n),start:r,end:i,isNow:n===0}})}var ym={yesterday:5,today:5,tomorrow:5,lastWeek:5,thisWeek:5,nextWeek:5,lastMonth:4,thisMonth:4,nextMonth:4,lastYear:3,thisYear:3,nextYear:3,lastDecade:2,thisDecade:2,nextDecade:2,lastCentury:1,thisCentury:1,nextCentury:1,lastMillennium:0,thisMillennium:0,nextMillennium:0};function bm(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function xm(e,t){let n=Em(e);return n?(n.setDate(n.getDate()+t),bm(n)):e}function Sm(e){let t=[...e].sort((e,t)=>e.start.localeCompare(t.start)),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=xm(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function Cm(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return Sm([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=xm(t,-1)&&r.push({start:n.start,end:xm(t,-1)}),xm(t,1)<=n.end&&r.push({start:xm(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function wm(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:bm(t.start),end:bm(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function Tm({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=Qc(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,Q.useState)(3),[d,f]=(0,Q.useState)(pm),[p,m]=(0,Q.useState)(new Set),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)(e);e!==_&&(v(e),e&&ym[e]!==void 0&&u(ym[e]),m(new Set));let[y,b]=(0,Q.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=fm[l],S=vm(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,Q.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{_s(a,{names:r,buckets:vm(x.unit,d).map(e=>wm(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:_n(c.geo),applyCanvasSpec:!1}).then(t=>{e||g(t)}).catch(()=>{e||g([])})},250);return()=>{e=!0,clearTimeout(t)}},[a,o,s,x.unit,d,w,C]);let T=a&&r.length>0?h:[],E=Math.max(1,...T.map(e=>e.total)),D=e=>{u(t=>Math.max(0,Math.min(5,t+e))),f(pm),m(new Set)},O=(0,Q.useCallback)((e,t)=>{m(r=>{let i;if(t&&r.size>0){let t=Math.min(e,...r),n=Math.max(e,...r);i=new Set(r);for(let e=t;e<=n;e++)i.add(e)}else i=new Set(r),i.has(e)?i.delete(e):i.add(e);let a=[...i].sort((e,t)=>e-t),o=[];for(let e of a){let t=o[o.length-1];t&&e===t[1]+1?t[1]=e:o.push([e,e])}return n(o.map(([e,t])=>{let n=S.find(e=>e.offset===t).start,r=new Date(S.find(t=>t.offset===e).end);return r.setDate(r.getDate()-1),{start:bm(n),end:bm(r)}})),i})},[S,n]);return(0,$.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,$.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom in (finer periods)`,children:(0,$.jsx)(Gn,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom out (coarser periods)`,children:(0,$.jsx)(xr,{className:`w-3.5 h-3.5`})})]})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-1.5 space-y-1 touch-target`,children:[S.map(e=>{let t=p.has(e.offset),n=T[e.offset],r=n?.total??0,i=r>0?Math.log1p(r)/Math.log1p(E):0,a=n&&r>0?`: ${r} doc${r===1?``:`s`} (${Object.entries(n.counts).map(([e,t])=>`${e}: ${t}`).join(`, `)})`:``;return(0,$.jsxs)(`button`,{type:`button`,onClick:t=>O(e.offset,t.shiftKey),title:`${e.isNow?`Now`:e.label}${a}. Click to tag, shift-click to fill range`,className:q(`w-full flex items-center gap-2 rounded-2xl px-3 py-1.5 text-xs font-medium transition-colors select-none text-left`,t?`bg-primary text-primary-foreground`:e.isNow?`bg-primary/10 text-primary hover:bg-primary/20`:`bg-card text-foreground hover:bg-muted shadow-elevation-1`),children:[e.isNow&&(0,$.jsx)(Hn,{className:`w-3 h-3 shrink-0`}),(0,$.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,$.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,$.jsx)(`span`,{className:q(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,$.jsx)(`span`,{className:`mt-1 flex h-[3px] overflow-hidden rounded-full`,style:{width:`${Math.max(8,i*100)}%`},children:Object.entries(n.counts).map(([e,t])=>(0,$.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:cm(e)}},e))})]})]},e.offset)}),d<200&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+pm),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function Em(e){let t=/^(-?\d{1,6})-(\d{2})-(\d{2})$/.exec(e);return t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):null}function Dm({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,Q.useState)(()=>{let t=e[0]?.start&&Em(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=e=>a(t=>{let n=new Date(t.y,t.m+e,1);return{y:n.getFullYear(),m:n.getMonth()}}),d=(e,r)=>{if(r){n(e),s(null),l(null);return}if(!o){s(e);return}let[i,a]=o<=e?[o,e]:[e,o];t(i,a),s(null),l(null)},f=new Date(i.y,i.m,1),p=new Date(f);p.setDate(p.getDate()-(f.getDay()+6)%7);let m=Array.from({length:42},(e,t)=>{let n=new Date(p);return n.setDate(n.getDate()+t),n}),[h,g]=o?c&&c!==o?o<=c?[o,c]:[c,o]:[o,o]:[null,null],_=t=>e.some(e=>t>=e.start&&t<=e.end),v=t=>e.some(e=>t===e.start||t===e.end),y=bm(r);return(0,$.jsxs)(`div`,{className:`select-none`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(-12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous year`,children:(0,$.jsx)(jr,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous month`,children:(0,$.jsx)(Fn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>a({y:r.getFullYear(),m:r.getMonth()}),className:`text-xs font-semibold text-foreground hover:text-primary transition-colors`,title:`Jump to current month`,children:[mm[i.m],` `,i.y]}),(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next month`,children:(0,$.jsx)(Va,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next year`,children:(0,$.jsx)(dr,{className:`w-3.5 h-3.5`})})]})]}),(0,$.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,$.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,$.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=bm(e),n=e.getMonth()===i.m,r=h!==null&&g!==null&&t>=h&&t<=g,a=t===h||t===g,s=!o&&_(t),c=a||s&&v(t);return(0,$.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:q(`h-6 text-[11px] tabular-nums transition-colors`,c?`bg-primary text-primary-foreground rounded-md`:r||s?`bg-primary/15 text-foreground`:n?`text-foreground hover:bg-muted rounded-md`:`text-muted-foreground/40 hover:bg-muted rounded-md`,t===y&&!c&&`font-bold text-primary`),children:e.getDate()},t)})}),(0,$.jsx)(`p`,{className:`mt-1.5 text-[10px] text-muted-foreground/70`,children:o?`From ${o}: pick the end date`:`Click start + end. Ctrl+click adds/removes single days.`})]})}function Om({label:e,checked:t,onChange:n,color:r}){return(0,$.jsxs)(`div`,{role:`switch`,"aria-checked":t,tabIndex:0,onClick:()=>n(!t),onKeyDown:e=>(e.key===` `||e.key===`Enter`)&&n(!t),className:`flex items-center justify-between gap-3 cursor-pointer select-none outline-none focus-visible:ring-2 focus-visible:ring-ring rounded`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,$.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,$.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,$.jsx)(`div`,{className:q(`relative w-10 h-5 rounded-full transition-colors shrink-0`,!t&&`bg-accent dark:bg-muted-foreground`),style:t?{backgroundColor:r}:void 0,children:(0,$.jsx)(`div`,{className:q(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function km(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=Qc(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(`quick`),[_,v]=(0,Q.useState)(!1),{showToast:y}=Z(),b=new Set(a.selectedTimelines??[]),x=(0,Q.useMemo)(()=>{let e=[];return a.indexCreated&&e.push(`crud:created`),a.indexUpdated&&e.push(`crud:updated`),a.indexDeleted&&e.push(`crud:deleted`),a.contentEvents&&e.push(`content`),e.push(...a.selectedTimelines??[]),e.length>0?e:[`crud:created`]},[a.indexCreated,a.indexUpdated,a.indexDeleted,a.contentEvents,a.selectedTimelines]),S=e=>{let n=new Set(b);n.has(e)?n.delete(e):n.add(e),t({selectedTimelines:[...n]})},C=async()=>{let e=l.trim();if(e){f(!0);try{await n(e),u(``),y({title:`Timeline created`,description:e})}catch(e){y({title:`Failed to create timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{f(!1)}}},w=async e=>{if(window.confirm(`Delete timeline "${e}"?\n\nThis removes all interval data for this timeline.`)){m(e);try{await r(e),y({title:`Timeline deleted`,description:e})}catch(e){y({title:`Failed to delete timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{m(null)}}},E=o.filter(e=>!e.startsWith(`crud:`)&&e!==`content`),D=T(a),O=D.length>0,k=(0,Q.useCallback)(e=>{t({customRanges:e,customRange:null,...e.length>0?{quickFilter:null}:{}})},[t]),A=e=>{t({quickFilter:a.quickFilter===e?null:e,customRanges:[],customRange:null})},j=e=>{t({customRanges:D.filter((t,n)=>n!==e),customRange:null})},M=(e,t)=>(0,$.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,$.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!O;return(0,$.jsx)(`button`,{type:`button`,onClick:()=>A(e),className:q(`text-xs px-1.5 py-1 rounded-md transition-colors truncate`,r?`bg-primary text-primary-foreground font-medium`:`bg-muted/50 text-foreground hover:bg-muted`),title:e,children:t?dm[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,$.jsx)(Tm,{quickFilterKey:a.quickFilter,activeRangeCount:D.length,onSelectRanges:k,histogramNames:x}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,$.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:q(`px-2 py-0.5 transition-colors`,h===`quick`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Quick filters`,children:(0,$.jsx)(tr,{className:`w-3 h-3`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:q(`px-2 py-0.5 transition-colors`,h===`calendar`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Calendar range picker`,children:(0,$.jsx)(Xn,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,$.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,$.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),lm.map((e,t)=>M(e,t===0)),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),className:`flex items-center gap-1 text-[11px] text-muted-foreground/70 hover:text-muted-foreground pt-1 transition-colors`,children:[(0,$.jsx)(Hr,{className:q(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&um.map(e=>M(e,!1))]}):(0,$.jsx)(Dm,{ranges:D,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:Cm(D,e),customRange:null,quickFilter:null})}),O&&(0,$.jsx)(`div`,{className:`mt-2 space-y-1`,children:D.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-md bg-primary/10 border border-primary/30 px-2.5 py-1.5`,children:[(0,$.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>j(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,$.jsx)(ur,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Om,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:cm(`crud:created`)}),(0,$.jsx)(Om,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:cm(`crud:updated`)}),(0,$.jsx)(Om,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:cm(`crud:deleted`)}),(0,$.jsx)(Om,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:cm(`content`)})]}),(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,$.jsx)(Un,{className:`w-3 h-3`})})]}),c?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Sa,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):E.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,$.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:E.map(e=>{let t=b.has(e),n=cm(e);return(0,$.jsxs)(`div`,{className:q(`flex items-center gap-2.5 group rounded-md px-2 py-1.5 cursor-pointer transition-colors`,t?`bg-muted/60`:`hover:bg-muted/30`),onClick:()=>S(e),children:[(0,$.jsx)(`div`,{className:q(`shrink-0 w-4 h-4 rounded border-2 flex items-center justify-center transition-colors`,!t&&`border-muted-foreground/40 bg-transparent group-hover:border-muted-foreground/70`),style:t?{backgroundColor:n,borderColor:n}:void 0,children:t&&(0,$.jsx)(`svg`,{className:q(`w-2.5 h-2.5`,Te(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,$.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,$.jsx)(`span`,{className:`shrink-0 text-[10px] px-1 py-0.5 rounded bg-muted text-muted-foreground select-none`,title:`Observed granularity for "${e}" — each entry is indexed at its own precision (a bare year at year cells, a full date at day cells)`,children:(s[e]??[]).join(`·`)}),(0,$.jsx)(`button`,{type:`button`,disabled:p===e,onClick:t=>{t.stopPropagation(),w(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:`Delete timeline "${e}"`,children:p===e?(0,$.jsx)(Sa,{className:`w-3 h-3 animate-spin`}):(0,$.jsx)(Kr,{className:`w-3 h-3`})})]},e)})}),(0,$.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,$.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&C(),placeholder:`New timeline (e.g. wikipedia, trips)…`,title:`A timeline is a named time axis. Entries index at their own precision — a bare year at year granularity, a full date at day granularity — nothing to configure.`,className:`flex-1 px-2 py-1 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`}),(0,$.jsx)(`button`,{type:`button`,onClick:C,disabled:d||!l.trim(),className:`shrink-0 p-1.5 rounded-md bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 touch-target`,title:`Create timeline`,children:d?(0,$.jsx)(Sa,{className:`w-3.5 h-3.5 animate-spin`}):(0,$.jsx)(Bi,{className:`w-3.5 h-3.5`})})]})]})]})]})}var Am={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},jm=`data/dataset/default`;function Mm(e){let t=new Map;for(let n of e){let e=n.startsWith(`data/backend/`)?`data/backend`:n.startsWith(`data/mime/`)?`data/mime`:n.startsWith(`data/dataset/`)?`data/dataset`:n.split(`/`)[0];t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}var Nm=[`off`,`anyOf`,`allOf`,`noneOf`];function Pm(e){return Nm[(Nm.indexOf(e)+1)%Nm.length]}var Fm=[{m:`anyOf`,label:`any`,on:`bg-info text-info-foreground`},{m:`allOf`,label:`all`,on:`bg-success text-success-foreground`},{m:`noneOf`,label:`not`,on:`bg-destructive text-destructive-foreground`}];function Im({mode:e,onSet:t}){return(0,$.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:Fm.map(n=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:q(`px-2 py-0.5 text-[11px] font-medium transition-colors`,e===n.m?n.on:`bg-transparent text-muted-foreground hover:bg-muted hover:text-foreground`),title:`${n.label}: ${n.m}`,children:n.label},n.m))})}function Lm({keys:e,modeOf:t,onCycle:n}){return e.length?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=Dp(e),a=t(e),o=Fm.find(e=>e.m===a);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:q(`relative flex flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border p-3 min-h-[4.5rem] transition-colors select-none`,a===`off`?`border-border bg-muted/40 text-foreground hover:bg-muted`:a===`anyOf`?`border-info bg-info/10 text-foreground`:a===`allOf`?`border-success bg-success/10 text-foreground`:`border-destructive bg-destructive/10 text-foreground`),children:[o&&(0,$.jsx)(`span`,{className:q(`absolute right-1.5 top-1.5 rounded px-1 py-0.5 text-[9px] font-semibold leading-none`,o.on),children:o.label}),(0,$.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function Rm(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=Qc(),{availableBitmaps:o,bitmapsLoading:s,filters:c}=e,l=new Set(c.features.allOf),u=new Set(c.features.anyOf),d=new Set(c.features.noneOf),f=e=>l.has(e)?`allOf`:u.has(e)?`anyOf`:d.has(e)?`noneOf`:`off`,[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(null),{showToast:_}=Z(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==jm){let t=e.slice(13);if(!window.confirm(`Drop dataset "${t}"?\n\nALL documents stamped with this dataset will be PERMANENTLY DELETED. Documents in other datasets (or the default dataset) are unaffected. Re-ingesting recreates the dataset from scratch.`))return;g(e);try{let n=await a(e);_({title:`Dataset dropped`,description:`"${t}": ${n} document(s) deleted`})}catch(e){_({title:`Dataset drop failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}return}if(!e.startsWith(`data/`)&&window.confirm(`Delete bitmap "${e}"?\n\nThis removes the bitmap from the database. Documents are unaffected, but any features/filters relying on this bitmap will lose their grouping.`)){g(e);try{await i(e),_({title:`Bitmap deleted`,description:e})}catch(e){_({title:`Delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}}};if(s)return(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Sa,{className:`w-4 h-4 animate-spin text-muted-foreground`})});let y=[...c.features.allOf,...c.features.anyOf,...c.features.noneOf],b=[...new Set([...o,...y])];if(!b.length)return(0,$.jsx)(`div`,{className:`p-4 text-xs text-muted-foreground text-center py-10`,children:`No feature bitmaps found`});let x=p.trim().toLowerCase(),S=x?b.filter(e=>e.toLowerCase().includes(x)):b,C=S.filter(e=>e.startsWith(Tp)).sort((e,t)=>{let n=Object.keys(Ep),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=Mm(S.filter(e=>!e.startsWith(Tp))),T=w.get(`data/dataset`);return T&&!T.includes(jm)&&(!x||jm.includes(x))&&T.unshift(jm),(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(Oa,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,$.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:`Search features…`,className:`w-full pl-7 pr-3 py-1.5 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:n,disabled:!r,className:`flex items-center gap-1.5 w-full justify-center px-2.5 py-1.5 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,$.jsx)(ur,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,$.jsx)(Lm,{keys:C,modeOf:f,onCycle:e=>t(e,Pm(f(e)))}),w.size===0&&C.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:Am[e]??e}),(0,$.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===jm,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,$.jsxs)(`div`,{onClick:()=>t(e,Pm(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,Pm(o)))},className:q(`flex items-center gap-2 group rounded-md pl-2 pr-1.5 py-1 border-l-2 transition-colors cursor-pointer select-none`,n%2==0?`bg-muted/50`:`bg-transparent`,`hover:bg-muted`,o===`off`?`border-l-transparent`:o===`anyOf`?`border-l-blue-500 !bg-info/10`:o===`allOf`?`border-l-emerald-500 !bg-success/10`:`border-l-rose-500 !bg-destructive/10`),children:[(0,$.jsxs)(`span`,{className:`flex-1 min-w-0 text-xs font-mono text-foreground truncate`,title:i?`Virtual dataset: documents not stamped with any dataset. Included by default; "not" hides them, "all" shows only them.`:e,children:[e,i&&(0,$.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,$.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,$.jsx)(Im,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,$.jsx)(`button`,{type:`button`,disabled:h===e,onClick:t=>{t.stopPropagation(),v(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:a?`Drop dataset "${e.slice(13)}" (DELETES its documents)`:`Delete bitmap "${e}" from database`,"aria-label":a?`Drop dataset ${e}`:`Delete bitmap ${e}`,children:h===e?(0,$.jsx)(Sa,{className:`w-3.5 h-3.5 animate-spin`}):(0,$.jsx)(Kr,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function zm(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i,setLiveEnabled:a}=Qc(),{toolsTab:o,isDirty:s,isSaving:c,activeContextType:l,savedSearchQuery:u}=e,d=Bt(),f=(new URLSearchParams(d.search).has(`q`)||new URLSearchParams(d.search).has(`search`)?zp(d.search):u?[u]:[])[0]||``,p=l!==null&&f.trim()!==(u||``),m=e.filters.sort??Je.sort,h=m.sortBy!==Je.sort.sortBy||m.order!==Je.sort.order,g=i||!!f.trim()||h,_=(0,$.jsxs)($.Fragment,{children:[g&&(0,$.jsxs)(`button`,{type:`button`,onClick:r,title:`Clear all active filters`,className:`flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(ur,{className:`h-3 w-3`}),`Clear`]}),l!==null&&g&&(s||p)&&(0,$.jsxs)(`button`,{type:`button`,onClick:n,disabled:c,className:`flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary disabled:opacity-60`,children:[c?(0,$.jsx)(Sa,{className:`h-3 w-3 animate-spin`}):(0,$.jsx)(Fr,{className:`h-3 w-3`}),`Save filters`]})]});return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex border-b border-border shrink-0`,children:[{id:`features`,label:`Features`},{id:`timeline`,label:`Timeline`},{id:`map`,label:`Map`},{id:`lens`,label:`Lens`}].map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:q(`flex-1 py-2.5 text-xs transition-colors`,o===e.id?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),l===`context`&&(0,$.jsxs)(`div`,{className:`shrink-0 space-y-1 border-b border-border px-3 py-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex min-h-8 flex-wrap items-center justify-between gap-x-3 gap-y-1`,children:[(0,$.jsxs)(`label`,{className:`flex min-h-8 cursor-pointer items-center gap-2 text-sm font-medium`,title:`Live view updates every device bound to this context. Save filters to keep the current view.`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 accent-current`,checked:e.liveEnabled,disabled:new URLSearchParams(d.search).has(`ownerId`),onChange:e=>{a(e.target.checked)}}),`Live view`]}),(0,$.jsx)(`div`,{className:`ml-auto flex items-center gap-2`,children:_})]}),e.liveError&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-destructive`,children:e.liveError})]}),l!==`context`&&g&&(0,$.jsx)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:_}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[o===`features`&&(0,$.jsx)(Rm,{}),o===`timeline`&&(0,$.jsx)(km,{}),o===`map`&&(0,$.jsx)(em,{}),o===`lens`&&(0,$.jsx)(am,{})]})]})}function Bm(){let e=If(),t=nl()?.state,n=!!t&&(e?.mode===`context`?t.activeContextType===`context`&&t.activeContextId===e.contextId:e?.mode===`workspace`?t.activeContextType!==`context`&&t.activeWorkspaceName===e.workspaceName&&t.activeTreeName===e.treeName&&t.activeContextPath===e.path:!t.activeWorkspaceName&&!t.activeContextId),r=!n&&e?.mode===`context`?e.contextId:null;return(0,Q.useEffect)(()=>{if(!r)return;let e=`context:${r}`,t=()=>w.emit(`subscribe`,{channel:e}),n=w.on(`connect`,t);return t(),()=>{n(),w.emit(`unsubscribe`,{channel:e})}},[r]),n?(0,$.jsx)(zm,{}):(0,$.jsx)(Rp,{target:e,children:(0,$.jsx)(pp,{children:(0,$.jsx)(zm,{})})})}function Vm({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=Tt(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,$.jsxs)(`div`,{className:`group relative overflow-hidden rounded-(--card-radius) border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,$.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,$.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,$.jsx)(ir,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,$.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:Vf(e.updatedAt||e.createdAt)})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Delete ${o}`,className:`absolute right-1.5 top-1.5 rounded-md bg-background/80 p-1 opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100`,children:(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`})})]})}function Hm({autoAdd:e}){let t=If(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=Hf(t,ss),[c,l]=(0,Q.useState)(e?`new`:null),{showErrorToast:u}=vo();return t?(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,$.jsxs)(X,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,$.jsx)(Bi,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,$.jsx)(Vm,{doc:e,scope:a,onOpen:()=>l(e),onRemove:()=>{confirm(`Delete "${String(e.data?.title??`Sketch`)}"?`)&&s(e.id).catch(e=>u(e instanceof Error?e.message:`Failed to delete sketch`))}},`${e.id}:${e.checksumArray?.[0]??``}`))}),c&&a&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,$.jsx)(Et,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var Um=[{id:`filters`,label:`Filters`,icon:_a,modes:[`context`,`global`],description:`Search and filter a workspace or a live context`,Component:Bm},{id:`notes`,label:`Notes`,icon:ya,modes:[`context`],description:`All notes in the current context, editable in place`,Component:Gf},{id:`todo`,label:`Todos`,icon:wi,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:Xf},{id:`sketch`,label:`Sketch`,icon:ir,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:Hm},{id:`lens`,label:`Lens`,icon:Pa,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:wp}];function Wm(e){return Um.filter(t=>t.modes.includes(e))}function Gm({target:e,children:t}){return(0,$.jsx)(Ff.Provider,{value:e,children:t})}function Km({children:e}){let[t,n]=(0,Q.useState)(null),r=(0,Q.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,Q.useCallback)(()=>n(null),[]),a=(0,Q.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,$.jsxs)(P.Provider,{value:a,children:[e,(0,$.jsx)(ke,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var qm=`universe`;function Jm(){let{appletId:e}=wt(),[t,n]=$e(),r=Um.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||qm,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,Q.useMemo)(()=>i?{mode:`context`,contextId:i}:{mode:`workspace`,workspaceName:a,path:o,treeName:s,treeType:s===`directory`?`directory`:`context`},[i,a,o,s]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{rs().then(d).catch(()=>d([])),ol().then(p).catch(()=>p([]))},[]);let[m,h]=(0,Q.useState)(o),[g,_]=(0,Q.useState)(o);g!==o&&(_(o),h(o));let v=e=>{let r=new URLSearchParams(t);r.delete(`add`);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r,{replace:!0})};if(!r)return(0,$.jsxs)(`div`,{className:`flex h-viewport flex-col items-center justify-center gap-3 surface-desk`,children:[(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,$.jsx)(`div`,{className:`flex gap-2`,children:Um.map(e=>(0,$.jsx)(Le,{to:`/apps/${e.id}`,className:`rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted`,children:e.label},e.id))})]});let y=i?`context`:`path`;return(0,$.jsx)(Km,{children:(0,$.jsx)(pp,{children:(0,$.jsxs)(`div`,{className:`flex h-viewport flex-col surface-desk p-shell gap-shell`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 rounded-xl border bg-card px-3 py-2 shadow-elevation-2`,children:[(0,$.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,$.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:q(`px-2.5 py-1 text-xs capitalize transition-colors`,y===e?`bg-foreground text-background`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:e},e))}),y===`path`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`select`,{value:a,onChange:e=>v({workspace:e.target.value,path:`/`}),className:`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Workspace`,children:[!u.some(e=>e.name===a)&&(0,$.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,$.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,$.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),onBlur:()=>{let e=m.trim()||`/`;e!==o&&v({path:e})},onKeyDown:e=>{e.key===`Enter`&&e.target.blur()},spellCheck:!1,placeholder:`/`,className:`h-7 w-40 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,"aria-label":`Path`})]}):(0,$.jsxs)(`select`,{value:i??``,onChange:e=>v({context:e.target.value}),className:`h-7 max-w-56 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Context`,children:[!i&&(0,$.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,$.jsx)(`div`,{className:`grow`}),(0,$.jsx)(Le,{to:`/home`,className:`flex items-center gap-1 rounded-md p-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Open the full Canvas app`,children:(0,$.jsx)(pr,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-elevation-2`,children:y===`context`&&!i?(0,$.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:[`Pick a context above to bind `,r.label,` to it.`]}):(0,$.jsx)(Gm,{target:l,children:(0,$.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})})})}var Ym=`false`,Xm=`false`,Zm=Ym===`true`,Qm=Xm===`true`;function $m(e={}){let{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:a,onRegisteredSW:o,onRegisterError:s}=e,c,l,u,d=async(e=!0)=>{await l,Zm||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await g(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!Qm){if(Zm)c.addEventListener(`activated`,e=>{(e.isUpdate||e.isExternal)&&(n?n():window.location.reload())}),c.addEventListener(`installed`,e=>{e.isUpdate||i?.()});else{let e=!1,t=()=>{e=!0,c?.addEventListener(`controlling`,e=>{e.isUpdate&&(n?n():window.location.reload())}),r?.()};c.addEventListener(`installed`,n=>{n.isUpdate===void 0?n.isExternal===void 0?!e&&i?.():n.isExternal?t():!e&&i?.():n.isUpdate||i?.()}),c.addEventListener(`waiting`,t)}}c.register({immediate:t}).then(e=>{o?o(`/sw.js`,e):a?.(e)}).catch(e=>{s?.(e)})}}return l=f(),d}var eh=new Set,th=!1,nh=$m({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){th=!0,eh.forEach(e=>e())}});function rh(e){return eh.add(e),th&&e(),()=>{eh.delete(e)}}function ih(){nh(!0)}function ah(){let[e,t]=(0,Q.useState)(!1),[n,r]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>rh(()=>t(!0)),[]),!e||n?null:(0,$.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,$.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>ih(),className:`flex items-center gap-1 rounded-full bg-foreground px-3 py-1 text-xs font-medium text-background hover:bg-foreground/90`,children:[(0,$.jsx)(Un,{className:`h-3 w-3`}),` Reload`]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(!0),"aria-label":`Not now`,className:`rounded-full p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]})})}var oh;function sh(){let[e,t]=(0,Q.useState)({local:!1});return(0,Q.useEffect)(()=>{oh??=fetch(`${lo}/runtime/capabilities`).then(async e=>e.ok?(await e.json()).payload:{local:!1}).catch(()=>({local:!1}));let e=!0;return oh.then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function ch(e){return e.isShared||e.type===`shared`?e.id:e.name}function lh({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=Qt();return(0,$.jsxs)(`div`,{className:q(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,$.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>i?i():s(r),"aria-label":`Back`,title:`Back`,className:`mt-1 shrink-0 text-muted-foreground transition-colors hover:text-foreground touch-target`,children:(0,$.jsx)(xa,{className:`h-5 w-5`})}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h1`,{className:q(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,$.jsx)(`p`,{className:q(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(`/`),"aria-label":`Close`,title:`Close`,className:`order-2 flex h-9 w-9 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,$.jsx)(ur,{className:`h-4 w-4`})}),n&&(0,$.jsx)(`div`,{className:`order-3 flex w-full items-center gap-2 max-sm:flex-wrap sm:order-1 sm:w-auto`,children:n})]})}function uh({className:e}){let t=Qt();return(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:q(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,e),children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})}function dh({onBack:e,title:t=`Back`,className:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:q(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,n),children:(0,$.jsx)(xa,{className:`h-4 w-4`})})}var fh=180;function ph({x:e,y:t,current:n,onChange:r,onClose:i}){ln(i);let[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)({q:``,list:[]}),[d,p]=(0,Q.useState)(!0),m=(0,Q.useRef)(null),h=(0,Q.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&i(),h.current={name:e,t}};(0,Q.useEffect)(()=>{m.current?.focus()},[]),(0,Q.useEffect)(()=>{let e=!0;return Yt().then(t=>{e&&(c(t),p(!1))}),()=>{e=!1}},[]),(0,Q.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{Ve(e).then(t=>{u({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=l.q===_,y=_!==``&&!v,b=(0,Q.useMemo)(()=>(_?v?l.list:[]:s).slice(0,fh),[_,v,l.list,s]),x=(0,Q.useRef)(null),[S,C]=(0,Q.useState)({x:e,y:t});return(0,Q.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,Md.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,$.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,$.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,$.jsx)(ur,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[Re.map(e=>(0,$.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:q(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,$.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:q(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,$.jsx)(ur,{className:`w-3 h-3`})}),(0,$.jsx)(`label`,{title:`Custom color`,className:q(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!Re.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!Re.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,$.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,$.jsx)(`input`,{ref:m,value:a,onChange:e=>o(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),d||y?(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,$.jsx)(Sa,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,$.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,$.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:q(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,$.jsx)(ur,{className:`w-4 h-4`})}),b.map(e=>(0,$.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:q(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,$.jsx)(f,{icon:e,width:18,height:18,color:n.color})},e))]}),!d&&!y&&b.length===0&&(0,$.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function mh(e,t,n){let r=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{r.current=n}),(0,Q.useEffect)(()=>{if(!e)return;e.emit(`subscribe`,{channel:t});let n=Object.keys(r.current).map(t=>{let n=(...e)=>{r.current[t]?.(...e)};return e.on(t,n),[t,n]});return()=>{e.emit(`unsubscribe`,{channel:t});for(let[t,r]of n)e.off(t,r)}},[e,t])}function hh({title:e,onClose:t,children:n}){return(0,$.jsxs)(`div`,{className:`space-y-4 rounded-(--card-radius) border bg-card p-4 shadow-elevation-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,$.jsx)(ur,{className:`h-4 w-4`})})]}),n]})}function gh({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,Q.useState)(!1),l=e.status===`active`,u=e.type===`universe`||e.name===`universe`,d=e.status===`error`,f=e.status===`not_found`,p=e.isShared===!0||e.type===`shared`,m=e.ownerEmail||e.owner,h=typeof e.sharedVia==`object`&&e.sharedVia?e.sharedVia:null,g=h?.permissions||[],_=g.includes(`admin`)?`admin`:g.includes(`write`)?`read/write`:`read-only`,v=h?.type===`group`?`via group ${h.principal}`:h?.type===`user`?`shared with you`:``,y=e.origin===`remote`,b=e.status===`offline`,x=Tn(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(kl,{className:`relative ${S}`,style:C,children:[(0,$.jsx)(Al,{children:(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,$.jsx)(jl,{className:`truncate`,children:e.label||e.name}),(0,$.jsx)(Ml,{children:p?`Shared from ${m}`:e.description||``})]}),(0,$.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,$.jsx)(X,{variant:`outline`,size:`icon`,onClick:()=>n(ch(e)),title:`Stop Workspace`,disabled:d||f,children:(0,$.jsx)(pa,{className:`h-4 w-4`})}):(0,$.jsx)(X,{variant:`outline`,size:`icon`,onClick:()=>t(ch(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,$.jsx)(_r,{className:`h-4 w-4`})}),l&&(0,$.jsx)(X,{variant:`outline`,size:`icon`,onClick:()=>r(ch(e)),title:`Enter Workspace`,disabled:d||f,children:(0,$.jsx)(ii,{className:`h-4 w-4`})}),a&&(0,$.jsx)(X,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:ct(e)?`Workspace settings`:`Workspace settings require admin access`,"aria-label":`Workspace settings`,disabled:f||!ct(e),children:(0,$.jsx)(Xi,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,$.jsx)(X,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,$.jsx)(Ri,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,$.jsxs)(co,{open:s,onOpenChange:c,children:[(0,$.jsx)(to,{asChild:!0,children:(0,$.jsx)(X,{variant:`outline`,size:`icon`,title:y?`Remove remote workspace reference`:`Delete Workspace`,disabled:l&&!y,className:`text-destructive hover:text-destructive hover:bg-destructive/10`,children:(0,$.jsx)(Kr,{className:`h-4 w-4`})})}),(0,$.jsxs)(eo,{children:[(0,$.jsxs)(so,{children:[(0,$.jsx)(Ya,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,$.jsx)(Ja,{children:y?(0,$.jsxs)($.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,$.jsx)(`br`,{}),(0,$.jsx)(`br`,{}),`The workspace itself stays untouched on `,e.remote?.url||e.host,`; only the stored share token and the local cache entry are dropped.`]}):(0,$.jsxs)($.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,$.jsx)(`br`,{}),(0,$.jsx)(`br`,{}),(0,$.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,$.jsxs)(io,{children:[(0,$.jsx)(oo,{children:`Cancel`}),(0,$.jsx)(ro,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,$.jsx)(Nl,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`div`,{className:`h-3 w-3 rounded-full ${(()=>{switch(e.status){case`active`:return`bg-success`;case`inactive`:case`available`:return`bg-muted-foreground`;case`error`:case`offline`:return`bg-destructive`;case`not_found`:return`bg-muted-foreground`;default:return`bg-accent`}})()}`}),(0,$.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:(()=>{switch(e.status){case`active`:return`Active`;case`inactive`:return`Inactive`;case`error`:return`Error`;case`not_found`:return`Not Found`;case`available`:return`Available`;case`removed`:return`Removed`;case`destroyed`:return`Destroyed`;case`offline`:return`Offline`;default:return e.status}})()}),u&&(0,$.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,$.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:e.remote?.url?`${e.remote.url} (${(e.remote.permissions||[]).join(`, `)||`no permissions`})`:void 0,children:[`Remote · `,e.host]}),p&&(0,$.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:[v,`${_} access`].filter(Boolean).join(` · `),children:[`Shared · `,_]})]})})]})})}function _h(){let[e,t]=$e(),n=e.get(`create`)===`1`,[r,i]=(0,Q.useState)(n),[a,o]=(0,Q.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,Q.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var vh=`canvas:lastPath`,yh=200;function bh(){try{let e=localStorage.getItem(vh);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function xh(e){try{localStorage.setItem(vh,JSON.stringify(e))}catch{}}function Sh(e,t,n){if(!e)return;let r=bh(),i=r[e];if(i&&i.tree===t&&i.path===n)return;delete r[e],r[e]={tree:t,path:n};let a=Object.keys(r);if(a.length>yh)for(let e of a.slice(0,a.length-yh))delete r[e];xh(r)}function Ch(e){let t=bh()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function wh(e){let t=Ch(e);return t?Yd(e,t.path,t.tree):`/workspaces/${e}`}var Th=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:er,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:Na,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:Ba,label:`Offline & cache`,description:`Manage cached content and storage on this device.`}]},{id:`account`,label:`Your account`,description:`Manage your access and the defaults your workspaces inherit.`,items:[{path:`/api-tokens`,icon:Pr,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:la,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:na,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:oa,label:`Shared with you`,description:`Find content other people have shared with your account.`}]},{id:`server`,label:`Server administration`,description:`Administrator controls for everyone using this Canvas server.`,items:[{path:`/admin/users`,icon:Zn,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:Gi,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/auth`,icon:Rn,label:`Authentication`,description:`Configure sign-in backends: local passwords, LDAP and IMAP.`},{path:`/admin/embedding`,icon:na,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:Ra,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:Ia,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:qr,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:Zr,label:`All agents`,description:`Inspect and manage agents across the server.`}]},{id:`information`,label:`Information`,description:`Information about your Canvas installation.`,items:[{path:`/about`,icon:Wn,label:`About Canvas`,description:`View versions and information about this installation.`}]}],Eh=[`/settings`,...Th.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function Dh(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var Oh=[{id:`classic`,name:`Classic`,description:`Menu panel on the left, one content sheet.`},{id:`strip`,name:`Canvas strip (beta)`,description:`Experimental. Menus and canvases side by side in a strip you walk with the arrow keys or a swipe. Shift+click opens a second canvas to the right; pins open their own row.`}],kh=`canvas:layout`;function Ah(){try{return localStorage.getItem(kh)===`strip`?`strip`:`classic`}catch{return`classic`}}var jh=Ah(),Mh=new Set;function Nh(){for(let e of Mh)e()}function Ph(){return jh}function Fh(e){try{e===`strip`?localStorage.setItem(kh,e):localStorage.removeItem(kh)}catch{}jh=e,Nh()}function Ih(e){Mh.add(e);let t=t=>{(t.key===kh||t.key===null)&&(jh=Ah(),e())};return window.addEventListener(`storage`,t),()=>{Mh.delete(e),window.removeEventListener(`storage`,t)}}function Lh(){return(0,Q.useSyncExternalStore)(Ih,Ph,()=>`classic`)}var Rh=[{id:`shift`,name:`Shift + arrows`,description:`Shift with an arrow key moves between columns and rows.`},{id:`alt`,name:`Alt + arrows`,description:`Alt with an arrow key. Some browsers use Alt+Left/Right for history.`},{id:`ctrl`,name:`Ctrl + arrows`,description:`Ctrl (Cmd on macOS) with an arrow key.`},{id:`none`,name:`Bare arrows`,description:`Plain arrow keys, except while typing in a field.`}],zh=`canvas:layout-nav`;function Bh(){try{let e=localStorage.getItem(zh);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var Vh=Bh(),Hh=new Set;function Uh(){return Vh}function Wh(e){try{e===`shift`?localStorage.removeItem(zh):localStorage.setItem(zh,e)}catch{}Vh=e;for(let e of Hh)e()}function Gh(e){Hh.add(e);let t=t=>{(t.key===zh||t.key===null)&&(Vh=Bh(),e())};return window.addEventListener(`storage`,t),()=>{Hh.delete(e),window.removeEventListener(`storage`,t)}}function Kh(){return(0,Q.useSyncExternalStore)(Gh,Uh,()=>`shift`)}function qh(e,t){let n=e.ctrlKey||e.metaKey;switch(t){case`shift`:return e.shiftKey&&!e.altKey&&!n;case`alt`:return e.altKey&&!e.shiftKey&&!n;case`ctrl`:return n&&!e.shiftKey&&!e.altKey;case`none`:return!e.shiftKey&&!e.altKey&&!n}}function Jh(){return window.matchMedia(`(max-width: 767px)`).matches&&Ph()!==`strip`}var Yh=(0,Q.createContext)(null);function Xh(){let e=(0,Q.useContext)(Yh);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function Zh(e){let t=e.split(`/`).filter(Boolean),n=t[0]||``,r=t[1]||null,i=t[2]||null;return n===`contexts`?{section:`contexts`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`workspaces`?{section:`workspaces`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`agents`?{section:`agents`,entityId:r,m2View:i===`settings`?`settings`:r?`detail`:null}:n===`admin`||Eh.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function Qh(e,t){let n=Bt(),r=Qt(),i=(0,Q.useRef)(!1),a=(0,Q.useRef)(e);return(0,Q.useEffect)(()=>{a.current=e},[e]),(0,Q.useLayoutEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=Zh(n.pathname);if(e===null&&n.pathname!==`/`&&Ph()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=Jh(),c=s?n.state?.canvasMenu:void 0;t(c?{type:`RESTORE_MENU`,menu:c}:{type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,n.state,t]),{navigateToEntity:(0,Q.useCallback)(e=>{i.current=!0,r(e)},[r])}}function $h(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=fo(qa.ws,{auth:{token:e},transports:[`websocket`],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3});return n.on(`connect`,()=>{console.log(`WebSocket connected`)}),n.on(`connect_error`,e=>{console.error(`WebSocket connection error:`,e)}),n.on(`error`,e=>{console.error(`WebSocket error:`,e)}),t(n),()=>{n.close()}},[]),e}var eg=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function tg(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await Us(e,`/${n}`,!0,a);let t=We(`/${n}`);t&&await Mo(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return Vs(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function ng(){let[e,t]=(0,Q.useState)(new Set),[n,r]=(0,Q.useState)(`context`);return{selected:e,setSelected:t,tree:n,setTree:r,toggle:e=>{t(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}}}function rg({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,$.jsx)(`div`,{className:`mt-3 grid gap-1.5 ${o?`grid-cols-1`:`grid-cols-2 sm:grid-cols-3 md:grid-cols-4`}`,children:eg.map(n=>{let r=Pe[n.toLowerCase()];return(0,$.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded border px-2 py-1.5 text-sm hover:bg-accent/50`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,$.jsx)(f,{icon:r.icon,width:16,height:16,color:r.color}),(0,$.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var ig=[{value:`full`,icon:Yn,title:`Standard`,blurb:`Everything in one folder: your files in home/, alongside db/, data/, git/.`,tree:[`workspace.json`,`home/ ← your files`,`db/ data/ cache/ Git/`]},{value:`home`,icon:Ar,title:`Roaming home`,blurb:`The workspace folder IS your drive. Mount it over WebDAV and it looks like a plain home directory. Canvas keeps its files in a hidden .workspace/.`,tree:[`your files, at the top level`,`.workspace/ ← hidden, ignored`]}];function ag({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,$.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:ig.map(i=>{let a=e===i.value,o=i.icon;return(0,$.jsxs)(`button`,{id:`${r}-${i.value}`,type:`button`,role:`radio`,"aria-checked":a,disabled:n,onClick:()=>t(i.value),className:`flex w-full gap-2 rounded-md border p-2.5 text-left transition-colors disabled:opacity-50 ${a?`border-primary bg-accent/40`:`hover:bg-accent/20`}`,children:[(0,$.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,$.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,$.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,$.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function og(){let[e,t]=(0,Q.useState)(`full`),[n,r]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let e=!0;return Y.get(`/ping`,{skipAuth:!0}).then(r=>{let i=r?.defaults?.workspaceLayout;e&&!n&&(i===`home`||i===`full`)&&t(i)}).catch(()=>{}),()=>{e=!1}},[]),[e,e=>{r(!0),t(e)}]}function sg({disabled:e}){let[t,n]=(0,Q.useState)(0),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),d=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=!0;return d.current?.id!==t&&(d.current={id:t,promise:Ms()}),d.current.promise.then(t=>{if(!e)return;let n=[...t.discovered,...t.adopted];o(e=>[...new Map([...e,...n].map(e=>[e.id,e])).values()]),c(t)}).catch(t=>{e&&u(t instanceof Error?t.message:`Workspace scan failed`)}).finally(()=>{e&&i(!1)}),()=>{e=!1}},[t]),(0,$.jsxs)(`section`,{className:`space-y-2 rounded-md border p-3`,"aria-label":`Find workspace folders`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`text-sm font-medium`,children:`Workspaces folder`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copied a workspace folder here? Scan to add it to your workspaces.`})]}),(0,$.jsxs)(X,{type:`button`,variant:`outline`,size:`sm`,disabled:e||r,onClick:()=>{i(!0),u(``),n(e=>e+1)},children:[(0,$.jsx)(Un,{className:`mr-2 h-3.5 w-3.5 ${r?`animate-spin`:``}`}),r?`Scanning…`:`Rescan`]})]}),r&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Looking for workspace folders…`}),!r&&!l&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:a.length?`Found ${a.length} ${a.length===1?`workspace`:`workspaces`}. Added to your workspace list.`:`No new workspace folders found.`}),a.length>0&&(0,$.jsx)(`ul`,{className:`space-y-2`,children:a.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(Le,{className:`text-sm font-medium underline underline-offset-2`,to:`/workspaces/${encodeURIComponent(e.name)}`,children:e.label||e.name}),(0,$.jsx)(`p`,{className:`break-all text-xs text-muted-foreground`,children:e.dir})]},e.id))}),l&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:l}),!!s?.skipped.length&&(0,$.jsxs)(`details`,{className:`text-sm text-muted-foreground`,children:[(0,$.jsxs)(`summary`,{children:[s.skipped.length,` `,s.skipped.length===1?`folder could`:`folders could`,` not be added`]}),(0,$.jsx)(`ul`,{className:`mt-1 space-y-1`,children:s.skipped.map(e=>(0,$.jsxs)(`li`,{className:`break-all`,children:[e.dir,`: `,e.reason]},e.dir))})]})]})}function cg({name:e,label:t,setName:n,setLabel:r,disabled:i=!1}){return(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace name`,(0,$.jsx)(J,{required:!0,pattern:`[a-zA-Z0-9]([a-zA-Z0-9_]|-)*`,placeholder:`my-workspace`,value:e,onChange:e=>n(e.target.value),disabled:i}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Used in addresses. Archive imports also use it as the folder name.`})]}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Display label`,(0,$.jsx)(J,{required:!0,placeholder:`My Workspace`,value:t,onChange:e=>r(e.target.value),disabled:i})]})]})}function lg({onImported:e,disabled:t=!1}){let[n,r]=(0,Q.useState)(`upload`),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(null),b=t||f,x=async t=>{t.preventDefault(),p(!0),_(``),y(null),h(`Starting…`);let r={name:c.trim(),label:u.trim()},a=e=>h(tc[e.phase]||e.phase);try{let t=n===`upload`?await zs(i,e=>h(e<1?`Uploading… ${Math.round(e*100)}%`:`Extracting…`),a,r):await cc(o.trim(),r,a);y(t),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e?.(t)}catch(e){_(e instanceof Error?e.message:`Workspace import failed`)}finally{p(!1)}};return(0,$.jsxs)(`form`,{className:`space-y-3`,onSubmit:e=>void x(e),children:[(0,$.jsx)(sg,{disabled:b}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Import from`,(0,$.jsxs)(`select`,{value:n,disabled:b,onChange:e=>r(e.target.value),className:`rounded-md border bg-background p-2`,children:[(0,$.jsx)(`option`,{value:`upload`,children:`Upload an archive`}),(0,$.jsx)(`option`,{value:`path`,children:`Path on this server`})]})]}),n===`upload`?(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace archive`,(0,$.jsx)(J,{required:!0,type:`file`,accept:`.tar.gz,.tgz,.tar.bz2,.tbz2,.tbz`,disabled:b,onChange:e=>a(e.target.files?.[0]||null)})]}):(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Server path`,(0,$.jsx)(J,{required:!0,placeholder:`/tmp/workspace.tar.gz`,value:o,disabled:b,onChange:e=>s(e.target.value)}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`An archive or workspace folder on the server. Archives are extracted into your Workspaces directory.`})]}),(0,$.jsx)(cg,{name:c,label:u,setName:l,setLabel:d,disabled:b}),(0,$.jsxs)(X,{type:`submit`,disabled:b||!c.trim()||!u.trim()||(n===`upload`?!i:!o.trim()),children:[f?(0,$.jsx)(Un,{className:`mr-2 h-4 w-4 animate-spin`}):(0,$.jsx)(Wr,{className:`mr-2 h-4 w-4`}),f?`Importing…`:`Import workspace`]}),f&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:m}),g&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),v&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Imported `,v.label||v.name,`.`]})]})}function ug(e){return[...e].sort((e,t)=>{let n=typeof e.order==`number`&&Number.isFinite(e.order)?e.order:2**53-1,r=typeof t.order==`number`&&Number.isFinite(t.order)?t.order:2**53-1;if(n!==r)return n-r;let i=e.createdAt??``,a=t.createdAt??``;return i===a?(e.name??``).localeCompare(t.name??``):i<a?-1:1})}function dg(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function fg(e,t){return{failed:(await Promise.allSettled(e.map((e,n)=>e.order===n?Promise.resolve():t(e,n)))).filter(e=>e.status===`rejected`).length}}function pg(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function mg(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(ie()),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(``),[_,v]=og(),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),T=sh(),[E,D]=_h(),O=ng(),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(!1),[ee,F]=(0,Q.useState)(!1),[I,te]=(0,Q.useState)(null),{showToast:L}=Z(),ne=Qt(),R=et(),{openM2Drawer:re}=Xh(),z=$h();mh(z,`workspace`,{"workspace:status:changed":e=>t(t=>t.map(t=>t.id===e.workspaceId?{...t,status:e.status}:t)),"workspace:created":e=>t(t=>[...t,e.workspace]),"workspace:deleted":e=>t(t=>t.filter(t=>t.id!==e.workspaceId)),"workspaces.scanned":({report:e})=>{!e.discovered.length&&!e.adopted.length&&!e.updated.length&&!e.missing.length||rs().then(e=>t(ug(e))).catch(()=>{})}}),(0,Q.useEffect)(()=>{let e=async()=>{try{r(!0);let e=await rs();t(ug(e)),a(null)}catch(e){console.error(`Workspace fetch error:`,e);let t=`Failed to fetch workspaces`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to fetch workspaces`}a(t),L({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}};e();let n=()=>{e()};return window.addEventListener(`workspaces:refresh`,n),()=>{window.removeEventListener(`workspaces:refresh`,n)}},[z,L]);let ae=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await ks({name:o,description:c||void 0,color:u,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),O.selected.size>0){try{await Ps(e.name);let{ok:t,failed:n}=await tg(e.name,Array.from(O.selected),O.tree);n&&L({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),L({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}O.setSelected(new Set)}s(``),l(``),d(ie()),m(null),g(``),L({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),D(!1)}catch(e){console.error(`Workspace creation error:`,e);let t=`Failed to create workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create workspace`}L({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},B=async e=>{if(e.preventDefault(),I)try{let e={label:I.label,description:I.description,color:I.color,icon:I.icon??null};await Eo(I.name,e),t(t=>t.map(t=>t.id===I.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),L({title:`Success`,description:`Workspace '${I.label}' details updated.`}),te(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;L({title:`Error`,description:t,variant:`destructive`})}},oe=e=>{te(e)},se=async e=>{try{await Ss(e.name),t(t=>t.filter(t=>t.id!==e.id)),L({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;L({title:`Error`,description:t,variant:`destructive`})}},V=async e=>{try{let n=await Ps(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),L({title:`Success`,description:`Workspace '${n.label||n.name}' started.`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){console.error(`Workspace start error:`,e);let t=`Failed to start workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to start workspace`}L({title:`Error`,description:t,variant:`destructive`})}},H=async e=>{try{let n=await Rs(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),L({title:`Success`,description:`Workspace '${n.label||n.name}' stopped.`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){console.error(`Workspace stop error:`,e);let t=`Failed to stop workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to stop workspace`}L({title:`Error`,description:t,variant:`destructive`})}},ce=e=>{ne(wh(e))},{rowProps:le,handleProps:ue,draggingIndex:de,insertLineClass:fe}=pg((n,r)=>{let i=dg(e,n,r);t(i),fg(i,(e,t)=>Eo(ch(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&L({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(lh,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{variant:`outline`,onClick:()=>A(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,$.jsx)(X,{variant:`outline`,onClick:()=>P(e=>!e),children:`Import workspace`}),(0,$.jsx)(X,{variant:`outline`,onClick:()=>M(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,$.jsx)(X,{variant:`outline`,onClick:()=>F(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!T.local&&!E&&(0,$.jsxs)(X,{onClick:()=>D(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,$.jsx)(Bi,{className:`h-4 w-4 sm:mr-2`}),(0,$.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),!T.local&&E&&(0,$.jsx)(hh,{title:`Create New Workspace`,onClose:()=>D(!1),children:(0,$.jsxs)(`form`,{onSubmit:ae,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsx)(J,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,$.jsx)(J,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,$.jsx)(J,{value:c,onChange:e=>l(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,disabled:C,onClick:e=>b({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:p||`ph:stack-fill`,width:22,height:22,color:Tn(u)})}),(0,$.jsx)(J,{id:`workspace-color`,type:`color`,value:u,onChange:e=>d(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,$.jsx)(X,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>d(ie()),disabled:C,children:`Randomize`})]}),y&&(0,$.jsx)(ph,{x:y.x,y:y.y,current:{icon:p??void 0,color:u},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&d(e.color)},onClose:()=>b(null)}),(0,$.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,$.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`How the workspace directory is laid out on disk. Fixed once created.`}),(0,$.jsx)(ag,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,$.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,$.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,$.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`Ticked folders are created right after the workspace, with matching icons and colors.`}),(0,$.jsx)(rg,{selected:O.selected,onToggle:O.toggle,tree:O.tree,onTreeChange:O.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,$.jsxs)(X,{type:`submit`,disabled:C||!o.trim(),children:[(0,$.jsx)(Bi,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),k&&(0,$.jsx)(gg,{}),ee&&(0,$.jsx)(_g,{onClose:()=>F(!1),onChanged:async()=>{try{t(ug(await rs()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),N&&(0,$.jsx)(hh,{title:`Import workspace`,onClose:()=>P(!1),children:(0,$.jsx)(lg,{onImported:()=>P(!1)})}),j&&(0,$.jsx)(hg,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),M(!1)},onClose:()=>M(!1)}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,$.jsx)(`div`,{className:`text-center text-destructive`,children:(0,$.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,$.jsx)(`div`,{className:`grid gap-4`,children:e.map((t,n)=>{let r={...t,createdAt:t.createdAt,updatedAt:t.updatedAt,color:t.color===null?void 0:t.color},i=Tn(t.color);return(0,$.jsxs)(`div`,{...le(n),className:`flex items-stretch rounded-lg ${fe(n,e.length)||``} ${de===n?`opacity-60`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,...ue(n),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:`hidden w-5 shrink-0 cursor-grab items-center justify-center rounded-l-lg active:cursor-grabbing md:flex ${i?``:`bg-muted`}`,style:i?{backgroundColor:i}:void 0,children:(0,$.jsx)(Pn,{className:`h-4 w-4 ${Te(i)}`})}),(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,$.jsx)(gh,{workspace:r,onStart:V,onStop:H,onEnter:ce,onEdit:oe,onSettings:e=>{R?re(`workspaces`,`settings`,ch(e)):ne(`/workspaces/${ch(e)}/settings/general`)},onDestroy:se})})]},t.id)})})]}),I&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,I.label]}),(0,$.jsxs)(`form`,{onSubmit:B,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,$.jsx)(J,{id:`edit-label`,value:I.label,onChange:e=>te(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(J,{id:`edit-description`,value:I.description||``,onChange:e=>te(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>S({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:I.icon||`ph:stack-fill`,width:22,height:22,color:Tn(I.color)})}),(0,$.jsx)(J,{id:`edit-workspace-color`,type:`color`,value:I.color||`#FFFFFF`,onChange:e=>te(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,$.jsx)(X,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>te(e=>e?{...e,color:ie()}:null),children:`Randomize Color`})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(X,{type:`submit`,disabled:!I.label?.trim(),children:`Save Changes`}),(0,$.jsx)(X,{type:`button`,variant:`outline`,onClick:()=>te(null),children:`Cancel`})]})]}),x&&(0,$.jsx)(ph,{x:x.x,y:x.y,current:{icon:I.icon??void 0,color:I.color??void 0},onChange:e=>{te(t=>{if(!t)return null;let n={...t};return`icon`in e&&(n.icon=e.icon??null),`color`in e&&e.color&&(n.color=e.color),n})},onClose:()=>S(null)})]})]})}function hg({onImported:e,onClose:t}){let{showToast:n}=Z(),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(``);return(0,$.jsx)(hh,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,$.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault();let i;try{i=new URL(r.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}if(!a.trim().startsWith(`canvas-`)){n({title:`Error`,description:`Invalid access token (expected canvas-...)`,variant:`destructive`});return}f(!0),m(`Starting…`);try{let t=await ec(i,a.trim(),e=>{m(tc[e.phase]||e.phase)},{name:s.trim(),label:l.trim()});n({title:`Success`,description:`Workspace '${t.label||t.name}' imported from ${i}.`}),e(t)}catch(e){let t=e,r=t?.message||t?.payload?.message||`Failed to import remote workspace`;n({title:`Error`,description:r,variant:`destructive`})}finally{f(!1),m(``)}},className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(J,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:d}),(0,$.jsx)(J,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:d}),(0,$.jsx)(X,{type:`submit`,disabled:d||!r.trim()||!a.trim()||!s.trim()||!l.trim(),children:d?`Importing…`:`Import Workspace`})]}),(0,$.jsx)(cg,{name:s,label:l,setName:c,setLabel:u,disabled:d}),d&&p&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,$.jsx)(`strong`,{children:`copy`}),` of the workspace from the remote canvas-server into this one, where it then lives independently. The remote workspace is stopped while it is packed, and large workspaces can take several minutes — progress is shown above.`]})]})})}function gg(){let{showToast:e}=Z(),[t,n]=(0,Q.useState)(``),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(J,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,$.jsx)(J,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,$.jsx)(X,{onClick:async()=>{if(!s(t.trim())){e({title:`Error`,description:`Invalid URL`,variant:`destructive`});return}if(!r.trim().startsWith(`canvas-`)){e({title:`Error`,description:`Invalid access token`,variant:`destructive`});return}o(!0);try{sessionStorage.setItem(`sharedToken:last`,r.trim());let e=new URLSearchParams({url:t.trim()}).toString();window.location.href=`/shared?${e}`}catch(t){e({title:`Error`,description:t instanceof Error?t.message:`Failed to open shared resource`,variant:`destructive`})}finally{o(!1)}},disabled:a||!t.trim()||!r.trim(),children:`Open`})]}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`We use your provided URL and token to fetch via the remote's public API.`})]})}function _g({onClose:e,onChanged:t}){let{showToast:n}=Z(),r=Qt(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)([]),f=(0,Q.useCallback)(async()=>{try{d(await kc())}catch{d([])}},[]);(0,Q.useEffect)(()=>{f()},[f]);let p=async e=>{e.preventDefault();let r;try{r=new URL(i.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}l(!0);try{let e=await ic(r,o.trim());n({title:`Remote workspace added`,description:`'${e.label}' is available as ${e.address}.`}),a(``),s(``),await f(),t?.()}catch(e){let t=e;n({title:`Error`,description:t?.message||t?.payload?.message||`Failed to add remote workspace`,variant:`destructive`})}finally{l(!1)}},m=async e=>{try{await bs(e.id),await f(),t?.()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to remove remote workspace`,variant:`destructive`})}};return(0,$.jsxs)(hh,{title:`Open a remote Workspace`,onClose:e,children:[(0,$.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(J,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,$.jsx)(J,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,$.jsx)(X,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,$.jsx)(`code`,{className:`font-mono text-xs`,children:`name@host`}),` — nothing is copied. Every call you make to it is forwarded to the remote with the share token (its permissions apply); document content and thumbnails are cached locally so they stay readable when the remote is offline. Use “Import remote…” if you want an independent local copy instead.`]})]}),u.length>0&&(0,$.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,$.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,$.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`remote`})]}),(0,$.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,$.jsx)(X,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,$.jsx)(X,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}function vg({workspaceId:e,treeName:t=`context`,path:n=`/`,children:r,className:i,headerOnly:a=!1,readOnly:o=!1}){let[s,c]=(0,Q.useState)(null),l=Rt({workspaceId:e,treeName:t}),u=[...!o&&l.onImportDocuments?[{label:`Import documents…`,run:()=>l.onImportDocuments(n)}]:[],{label:`Export documents…`,run:()=>l.onExportDocuments(n)}];return(0,$.jsxs)(`div`,{className:i,onContextMenu:e=>{e.defaultPrevented||a&&!e.target.closest(`.canvas-navigation`)||(e.preventDefault(),c({x:e.clientX,y:e.clientY}))},children:[r,s&&(0,$.jsx)(ut,{...s,onClose:()=>c(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:u.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`block w-full rounded-sm px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{c(null),e.run().catch(e=>alert(e instanceof Error?e.message:String(e)))},children:e.label},e.label))})]})}var yg={membership:`keep`,propagation:`never`,targets:[],acceptPropagatedDeletions:!1},bg=e=>`/workspaces/${encodeURIComponent(e)}/trash/operations`,xg=(e,t)=>Y.get(`${bg(e)}?${new URLSearchParams(Object.entries(t).map(([e,t])=>[e,String(t)]))}`),Sg=(e,t,n,r={})=>Y.post(`${bg(e)}/${n}`,{ids:t,...r}),Cg=(e,t,n,r)=>Y.patch(`/workspaces/${encodeURIComponent(e)}/backends/imap/${encodeURIComponent(t)}/containers/${encodeURIComponent(n)}`,{removalPolicy:r});function wg(e){let t=pt(`backends`,e.path)?.backend;return(0,$.jsx)(Tg,{...e},JSON.stringify([e.workspace,t]))}function Tg({workspace:e,path:t,onNavigate:n}){let r=pt(`backends`,t),i=r.backend,a=r.prefix,[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)(null),x=(0,Q.useCallback)(()=>g(e=>e+1),[]),[S,C]=(0,Q.useState)(t);S!==t&&(C(t),v(new Set),b(null),m(null),f(null));let w=o?.revision!==h,T=w?[]:o.items,E=w?[]:o.backends,D=o?.days;(0,Q.useEffect)(()=>{let t=!1;return(i?Mt(e,i).then(e=>({...e,backends:[]})):js(e).then(e=>({items:[],days:null,backends:e.filter(e=>e.driver===`file`&&e.enabled!==!1)}))).then(e=>{t||s({...e,revision:h,error:null})}).catch(e=>{t||s({revision:h,items:[],backends:[],days:null,error:e instanceof Error?e.message:String(e)})}),()=>{t=!0}},[e,i,h]),(0,Q.useEffect)(()=>{let t=null,n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==`backends`||(t||=setTimeout(()=>{t=null,x()},500))};return window.addEventListener(`workspace:trash:refresh`,n),window.addEventListener(`workspace:tree:refresh`,n),()=>{window.removeEventListener(`workspace:trash:refresh`,n),window.removeEventListener(`workspace:tree:refresh`,n),t&&clearTimeout(t)}},[e,x]);let O=Ft(T,a),k=async(t,n)=>{if(!(!i||u.current||w||!n.length)&&!(t===`discard`&&!Ht(i,n))){u.current=!0,l(t),f(null),m(null),b(null);try{let r=await(t===`restore`?cn:en)(e,i,[...n].sort((e,t)=>t.deletedAt-e.deletedAt).map(e=>e.id)),a=r.filter(e=>!e.ok);m(`${r.length-a.length} item(s) ${t===`restore`?`restored to their original paths`:`permanently deleted`}.`),a.length&&f(`${a.length} item(s) remain in Trash. ${a.slice(0,3).map(e=>`${e.key||`Item`}: ${e.reason===`precondition-failed`||e.reason===`target-exists`?`original path is occupied`:e.message||e.reason}`).join(`; `)}`),v(new Set)}catch(e){f(e instanceof Error?e.message:String(e))}finally{u.current=!1,l(null),x()}}},A=(e,t,n)=>b({x:e,y:t,row:n});return(0,$.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col bg-background`,"aria-label":`Backend Trash`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 border-b px-4 py-3`,children:[(0,$.jsx)(Kr,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(U,{items:ge(t,e).map((e,t)=>t===2&&i?{...e,label:i}:e),onNavigate:n,className:`basis-48`}),(0,$.jsxs)(`div`,{className:`ml-auto flex max-w-full flex-wrap items-center gap-2`,children:[_.size>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`restore`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,$.jsx)(ja,{className:`h-3.5 w-3.5`}),`Restore selected`]}),(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`}),`Delete selected`]})]}),i&&O.length>0&&(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.flatMap(e=>e.items)),children:[(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`}),a?`Empty this folder`:`Empty Trash`]}),(0,$.jsx)(`button`,{title:`Refresh Trash`,"aria-label":`Refresh Trash`,className:`rounded p-2 hover:bg-accent`,disabled:!!c||w,onClick:x,children:(0,$.jsx)(Un,{className:`h-4 w-4 ${w?`animate-spin`:``}`})})]})]}),(0,$.jsxs)(`div`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`Restore files and folders to their original paths. Existing files are kept.`,D?` Deleted items are kept for ${D} days.`:``]}),p&&(0,$.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:p}),(d||o?.error)&&(0,$.jsx)(`p`,{role:`alert`,className:`px-4 py-2 text-sm text-destructive`,children:d||o?.error}),c&&(0,$.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:c===`restore`?`Restoring…`:`Deleting permanently…`}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:w?(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Loading Trash…`}):i?O.length===0?(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`This Trash folder is empty.`}):(0,$.jsxs)(`table`,{className:`w-full text-left text-sm`,children:[(0,$.jsx)(`thead`,{className:`border-b text-xs text-muted-foreground`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`w-8 p-2`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all visible items`,checked:O.length>0&&O.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(O.map(e=>e.id)):new Set)})}),(0,$.jsx)(`th`,{className:`p-2`,children:`Name`}),(0,$.jsx)(`th`,{className:`p-2 max-sm:hidden`,children:`Original path`}),(0,$.jsx)(`th`,{className:`p-2 max-md:hidden`,children:`Deleted`}),(0,$.jsx)(`th`,{className:`p-2`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsx)(`tbody`,{children:O.map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-border/50 hover:bg-accent/50`,onContextMenu:t=>{t.preventDefault(),A(t.clientX,t.clientY,e)},onDoubleClick:()=>e.navigable&&n(Gt(i,e.key)),children:[(0,$.jsx)(`td`,{className:`p-2`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.name}`,checked:_.has(e.id),disabled:!!c,onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,$.jsx)(`td`,{className:`p-2`,children:(0,$.jsxs)(`button`,{className:`flex items-center gap-2 text-left`,onClick:()=>e.navigable&&n(Gt(i,e.key)),children:[e.directory?(0,$.jsx)(Gr,{className:`h-4 w-4 shrink-0`}):(0,$.jsx)(fa,{className:`h-4 w-4 shrink-0`}),(0,$.jsxs)(`span`,{children:[e.name,e.navigable&&(0,$.jsxs)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.items.length,` items`]})]})]})}),(0,$.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-sm:hidden`,children:e.key}),(0,$.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-md:hidden`,children:new Date(e.items.reduce((e,t)=>Math.max(e,t.deletedAt),0)).toLocaleString()}),(0,$.jsx)(`td`,{className:`p-2 text-right`,children:(0,$.jsx)(`button`,{title:`Actions for ${e.name}`,"aria-label":`Actions for ${e.name}`,disabled:!!c,className:`rounded p-2 hover:bg-accent`,onClick:t=>A(t.clientX,t.clientY,e),children:(0,$.jsx)(Yi,{className:`h-4 w-4`})})})]},e.id))})]}):(0,$.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[E.map(e=>(0,$.jsxs)(`button`,{onClick:()=>n(Gt(e.address)),className:`flex items-center gap-3 rounded-lg border p-4 text-left hover:bg-accent`,children:[(0,$.jsx)(Kr,{className:`h-6 w-6 text-muted-foreground`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:e.label||e.address}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.address})]})]},e.address)),!E.length&&(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`No file backends are available.`})]})}),y&&(0,$.jsxs)(ut,{x:y.x,y:y.y,onClose:()=>b(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[y.row.navigable&&(0,$.jsxs)(`button`,{className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent`,onClick:()=>{n(Gt(i,y.row.key)),b(null)},children:[(0,$.jsx)(Gr,{className:`h-4 w-4`}),`Open folder`]}),(0,$.jsxs)(`button`,{disabled:!!c,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent disabled:opacity-50`,onClick:()=>void k(`restore`,y.row.items),children:[(0,$.jsx)(ja,{className:`h-4 w-4`}),`Restore `,y.row.directory?`folder`:`file`]}),(0,$.jsxs)(`button`,{disabled:!!c||w,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-destructive hover:bg-destructive/10 disabled:opacity-50`,onClick:()=>void k(`discard`,y.row.items),children:[(0,$.jsx)(Kr,{className:`h-4 w-4`}),`Delete permanently`]})]})]})}function Eg({value:e,backends:t,source:n,onSave:r,destination:i=!0}){let[a,o]=(0,Q.useState)({...yg,...e}),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=`rounded border bg-background px-2 py-1.5 text-xs w-full`,f=async()=>{c(!0),u(``);try{await r(a),u(`Removal policy saved.`)}catch(e){u(e instanceof Error?e.message:`Could not save policy`)}finally{c(!1)}};return(0,$.jsxs)(`details`,{className:`border-t pt-3 text-xs`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:`Source removals and Trash`}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`A completed scan removes missing locations from the backend tree. Items with no remaining locations go to Trash until you purge them.`}),(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`space-y-1 block`,children:[`When an item disappears from this source`,(0,$.jsxs)(`select`,{className:d,value:a.membership,disabled:s,onChange:e=>o({...a,membership:e.target.value}),children:[(0,$.jsx)(`option`,{value:`keep`,children:`Keep in managed trees`}),(0,$.jsx)(`option`,{value:`review`,children:`Review removal in Trash`}),(0,$.jsx)(`option`,{value:`trash`,children:`Move to Trash automatically`})]})]}),(0,$.jsxs)(`label`,{className:`space-y-1 block`,children:[`Remove tracked copies from other backends`,(0,$.jsxs)(`select`,{className:d,value:a.propagation,disabled:s,onChange:e=>o({...a,propagation:e.target.value}),children:[(0,$.jsx)(`option`,{value:`never`,children:`Never`}),(0,$.jsx)(`option`,{value:`review`,children:`Review in Trash`}),(0,$.jsx)(`option`,{value:`automatic`,children:`Automatically, retaining recovery copies`})]})]})]}),a.propagation!==`never`&&(0,$.jsxs)(`fieldset`,{className:`space-y-2`,children:[(0,$.jsx)(`legend`,{className:`mb-1 font-medium`,children:`Destinations`}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:a.targets===`all`,disabled:s,onChange:e=>o({...a,targets:e.target.checked?`all`:[]})}),`All eligible backends`]}),a.targets!==`all`&&t.filter(e=>e.address!==n&&e.kind===`storage`).map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:s||e.config?.propagatedRemovalSupported!==!0,checked:a.targets.includes(e.address),onChange:t=>o({...a,targets:t.target.checked?[...a.targets,e.address]:a.targets.filter(t=>t!==e.address)})}),String(e.config?.label||e.address),e.config?.propagatedRemovalSupported===!0?!e.config?.removalPolicy?.acceptPropagatedDeletions&&` · protected`:` · recovery removal unavailable`]},e.address)),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`Only tracked, Canvas-owned copies are eligible. Protected destinations refuse propagated deletion. Recovery removal currently supports filesystem and workspace blob storage; remote destinations remain protected.`})]}),i&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:s,checked:a.acceptPropagatedDeletions,onChange:e=>o({...a,acceptPropagatedDeletions:e.target.checked})}),`Accept propagated deletions on this backend`]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(X,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>void f(),children:s?`Saving…`:`Save removal policy`}),(0,$.jsx)(`span`,{role:`status`,children:l})]})]})]})}function Dg({workspaceName:e,canWrite:t}){let{showToast:n}=Z(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(!1),d=(0,Q.useCallback)(async()=>{o(!0);try{i(await ds(e))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to load the trash`,variant:`destructive`})}finally{o(!1)}},[e]);(0,Q.useEffect)(()=>{d()},[d]);let f=(0,Q.useCallback)(e=>s.includes(e),[s]),p=async(e,t)=>{c(t=>[...t,...e]);try{await t()}finally{c(t=>t.filter(t=>!e.includes(t)))}},m=t=>p([t.id],async()=>{try{let r=await Gs(e,[t.id]);r.failed?.length?n({title:`Not restored`,description:r.failed[0]?.error||`No restore target recorded`,variant:`destructive`}):(n({title:`Restored`,description:`Document put back where it was.`}),i(e=>e.filter(e=>e.id!==t.id)))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to restore`,variant:`destructive`})}}),h=t=>p([t.id],async()=>{try{let r=await Vo(e,[t.id]);if(r.failed?.length)throw Error(`The item could not be purged. Refresh and retry.`);n({title:`Cleared from Trash`,description:r.preserved?.length?`Existing backend copies remain indexed.`:`Document permanently deleted.`}),i(e=>e.filter(e=>e.id!==t.id))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to delete`,variant:`destructive`})}}),g=async()=>{if(!l){u(!0);return}u(!1);try{let t=await Vo(e);n({title:`Trash emptied`,description:`${t.destroyed?.length??0} document(s) purged. ${t.preserved?.length??0} item(s) cleared with backend copies preserved.`}),await d()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to empty the trash`,variant:`destructive`})}},_=(0,Q.useMemo)(()=>r.map(e=>{let t=ns(e),n=(e.trashed?.placements??[]).flatMap(e=>e.paths.map(t=>`${e.tree}:${t}`));return{document:e,title:t.title,origin:n,trashedAt:e.trashed?.trashedAt||null}}),[r]);return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-medium`,children:`Managed-tree items`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 max-w-2xl`,children:`Restore managed-tree placements or permanently purge these items. Pending removals require separate approval. Backend copies are managed below.`})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 max-sm:flex-wrap`,children:[(0,$.jsxs)(X,{variant:`outline`,size:`sm`,onClick:()=>d(),disabled:a,children:[(0,$.jsx)(Un,{className:`mr-2 h-3.5 w-3.5 ${a?`animate-spin`:``}`}),`Refresh`]}),(0,$.jsxs)(X,{variant:l?`destructive`:`outline`,size:`sm`,onClick:g,onBlur:()=>u(!1),disabled:!t||r.length===0,children:[(0,$.jsx)(Kr,{className:`mr-2 h-3.5 w-3.5`}),l?`Click again to delete everything`:`Empty trash`]})]})]}),a&&r.length===0&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading…`}),!a&&r.length===0&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The trash is empty.`}),_.length>0&&(0,$.jsx)(`div`,{className:`border rounded-md divide-y`,children:_.map(({document:e,title:n,origin:r,trashedAt:i})=>(0,$.jsxs)(`div`,{className:`flex items-center gap-3 px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm`,children:n}),(0,$.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[r.length>0?`from ${r.join(`, `)}`:`no recorded origin`,i?` · ${new Date(i).toLocaleString()}`:``]})]}),(0,$.jsxs)(X,{variant:`outline`,size:`sm`,onClick:()=>m(e),disabled:!t||f(e.id)||r.length===0,title:r.length===0?`Nothing recorded to restore to`:`Put it back where it was`,children:[(0,$.jsx)(ja,{className:`mr-2 h-3.5 w-3.5`}),`Restore placements`]}),(0,$.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>h(e),disabled:!t||f(e.id),title:`Delete permanently`,children:(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`})})]},e.id))})]})}function Og({workspaceName:e}){return(0,$.jsx)(kg,{workspaceName:e},e)}function kg({workspaceName:e}){let[t,n]=(0,Q.useState)(`pending`),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(0),[l,u]=(0,Q.useState)(0),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)({}),[x,S]=(0,Q.useState)(`/Trash`),[C,w]=(0,Q.useState)([]),[T,E]=(0,Q.useState)({write:!1,admin:!1});(0,Q.useEffect)(()=>{let t=!0;return yo(e).then(e=>{let n=e.remote?.permissions||e.access?.permissions||(typeof e.sharedVia==`object`?e.sharedVia?.permissions:[])||[],r=ct(e);t&&E({admin:r,write:r||n.includes(`write`)})}).catch(()=>{}),()=>{t=!1}},[e]);let[D,O]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let t=!0;return js(e).then(e=>{t&&w(e)}).catch(()=>{}),()=>{t=!1}},[e]),(0,Q.useEffect)(()=>{let n=!1,i=()=>xg(e,{view:t,search:r,...a?{backend:a}:{},offset:s}).then(e=>{n||(f(e),m(``))}).catch(e=>{n||m(e instanceof Error?e.message:`Could not load Trash`)});i();let o=setInterval(()=>{h||i()},5e3);return()=>{n=!0,clearInterval(o)}},[e,t,r,a,s,l,h]);let k=d?.operations||[],A=()=>{v(new Set),u(e=>e+1)},j=()=>{Vs(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e}}))},M=async(t,n=[..._])=>{if(!(!n.length||h)&&!(t===`purge`&&!window.confirm(`Permanently delete retained recovery copies for ${n.length} operation(s)?`))){g(!0),m(``);try{let r=(t===`approve`?(await Promise.all(n.map(n=>Sg(e,[n],t,y[n])))).flatMap(e=>e.results):(await Sg(e,n,t)).results).filter(e=>!e.ok||e.operation?.state===`failed`);r.length&&m(r.map(e=>e.error||e.operation?.error||`A destination could not be changed. Expand the item for details.`).join(` `)),j(),A()}catch(e){m(e instanceof Error?e.message:`Trash action failed`)}finally{g(!1)}}},N=e=>{n(e),c(0),f(null),v(new Set),b({})};return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:`Workspace Trash`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Review source removals, recover items, and see what automatic policies changed.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,role:`tablist`,"aria-label":`Trash views`,children:[[[`pending`,`Pending removal`],[`trashed`,`In Trash`],[`activity`,`Activity`]].map(([e,n])=>(0,$.jsx)(X,{role:`tab`,"aria-selected":t===e,size:`sm`,variant:t===e?`default`:`outline`,onClick:()=>N(e),children:n},e)),(0,$.jsxs)(X,{size:`sm`,variant:`ghost`,className:`ml-auto`,onClick:A,disabled:h,children:[(0,$.jsx)(Un,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),t===`trashed`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Dg,{workspaceName:e,canWrite:T.write},l),(0,$.jsxs)(`details`,{className:`rounded border p-3`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:`Browse backend recovery copies`}),(0,$.jsx)(`div`,{className:`mt-3 min-h-48`,children:(0,$.jsx)(wg,{workspace:e,path:x,onNavigate:S})})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(J,{"aria-label":`Filter Trash items`,placeholder:`Filter by item or path…`,className:`max-w-xs`,value:r,onChange:e=>{i(e.target.value),f(null),c(0),v(new Set)}}),(0,$.jsx)(J,{"aria-label":`Filter by backend`,placeholder:`Backend name…`,className:`max-w-56`,value:a,onChange:e=>{o(e.target.value),f(null),c(0),v(new Set)}}),_.size>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsxs)(`span`,{children:[_.size,` selected`]}),t===`pending`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{size:`sm`,disabled:h,onClick:()=>void M(`approve`),children:`Approve selected`}),(0,$.jsx)(X,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`keep`),children:`Keep selected`}),(0,$.jsx)(X,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`retry`),children:`Retry`})]}),t===`trashed`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`restore`),children:`Restore copies`}),(0,$.jsx)(X,{size:`sm`,variant:`destructive`,disabled:h,onClick:()=>void M(`purge`),children:`Purge copies`})]})]})]}),D&&(0,$.jsxs)(`div`,{className:`rounded border p-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Removal policy · `,D.source.account||D.source.backend,D.source.folder?` / ${D.source.folder}`:``]}),(0,$.jsx)(X,{size:`sm`,variant:`ghost`,onClick:()=>O(null),children:`Close`})]}),(0,$.jsx)(Eg,{source:D.source.backend,backends:C,destination:!1,value:{...yg,...C.find(e=>e.address===D.source.backend)?.config?.removalPolicy,membership:y[D.id]?.membership??D.membership!==`keep`?`review`:`keep`,propagation:D.targets.length?`review`:`never`,targets:[...new Set(D.targets.filter(e=>!y[D.id]||y[D.id].targets.includes(JSON.stringify([e.backend,e.key]))).map(e=>e.backend))]},onSave:async t=>{D.source.driver===`imap`?await Cg(e,D.source.account,D.source.folder,t):await us(e,D.source.driver,D.source.backend,{removalPolicy:t}),w(await js(e))}},D.id)]}),p&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p}),(0,$.jsxs)(`div`,{className:`overflow-x-auto rounded border`,children:[(0,$.jsxs)(`table`,{className:`w-full text-left text-xs`,children:[(0,$.jsx)(`thead`,{className:`bg-muted`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`p-3 w-8`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select visible operations`,disabled:!T.write||h||!k.length||t===`activity`,checked:k.length>0&&k.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(k.map(e=>e.id)):new Set)})}),(0,$.jsx)(`th`,{className:`p-3`,children:`Item and affected copies`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Source`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Status`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Detected`})]})}),(0,$.jsx)(`tbody`,{children:k.map(e=>{let n=y[e.id]||{targets:e.targets.filter(e=>e.state!==`kept`).map(e=>JSON.stringify([e.backend,e.key])),membership:e.membership!==`keep`};return(0,$.jsxs)(`tr`,{className:`border-t align-top`,children:[(0,$.jsx)(`td`,{className:`p-3`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.title}`,disabled:!T.write||h||t===`activity`,checked:_.has(e.id),onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,$.jsx)(`td`,{className:`p-3 min-w-64`,children:(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:e.title}),(0,$.jsxs)(`div`,{className:`mt-2 space-y-2 text-muted-foreground`,children:[(0,$.jsx)(`p`,{children:e.orphan?`No remaining byte locations. Restore placements only unless recovery bytes are available.`:`${e.remainingLocations.length} remaining location(s) when detected.`}),e.placements.map(e=>(0,$.jsxs)(`p`,{children:[e.tree,`: `,e.paths.join(`, `)]},e.tree)),e.membership!==`keep`&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:n.membership,disabled:h||t!==`pending`||e.membershipApplied,onChange:t=>b({...y,[e.id]:{...n,membership:t.target.checked}})}),e.membershipApplied?`Managed placements moved to Trash`:`Move managed placements to Trash`]}),e.targets.map(r=>{let i=JSON.stringify([r.backend,r.key]);return(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:h||t!==`pending`||!!r.trashId,checked:n.targets.includes(i),onChange:t=>b({...y,[e.id]:{...n,targets:t.target.checked?[...n.targets,i]:n.targets.filter(e=>e!==i)}})}),(0,$.jsxs)(`span`,{className:`break-all`,children:[r.backend,`:`,r.key,` · `,r.state,r.error&&(0,$.jsx)(`span`,{className:`block text-destructive`,children:r.error})]})]},i)}),(0,$.jsx)(X,{size:`sm`,variant:`outline`,disabled:!T.admin,onClick:()=>O(e),children:`Use these choices as a source policy`}),e.remainingLocations.map(e=>(0,$.jsx)(`p`,{className:`break-all`,children:e.url},e.url))]})]})}),(0,$.jsxs)(`td`,{className:`p-3 break-all`,children:[e.source.account||e.source.backend,e.source.folder&&(0,$.jsx)(`span`,{className:`block text-muted-foreground`,children:e.source.folder})]}),(0,$.jsxs)(`td`,{className:`p-3`,children:[e.state,e.error&&(0,$.jsx)(`p`,{className:`mt-1 max-w-xs text-destructive`,children:e.error})]}),(0,$.jsx)(`td`,{className:`p-3 whitespace-nowrap text-muted-foreground`,children:new Date(e.createdAt).toLocaleString()})]},e.id)})})]}),!k.length&&(0,$.jsx)(`p`,{className:`p-5 text-center text-sm text-muted-foreground`,children:d?`No matching operations.`:`Loading…`})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[d?.total??0,` operation(s)`]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(X,{size:`sm`,variant:`outline`,disabled:!s||h,onClick:()=>{c(Math.max(0,s-200)),v(new Set)},children:`Previous`}),(0,$.jsx)(X,{size:`sm`,variant:`outline`,disabled:s+k.length>=(d?.total??0)||h,onClick:()=>{c(s+200),v(new Set)},children:`Next`})]})]})]})}function Ag({workspaceName:e,children:t}){let n=e,[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(0),[d,f]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{let t=!1,r=0,a,s=!1,c=async()=>{if(s||t)return;s=!0;let c=++r;try{let s=a?await hc(e):await yo(e);!t&&c===r&&(`id`in s&&(a=s.id,f({identity:n,allowed:ct(s)})),i({identity:n,state:Za()||s.status===`active`?`active`:s.status===`inactive`?`stopped`:`unavailable`}),o(``))}catch(e){if(!t&&c===r){let t=e instanceof Error?e.message:`Unable to check workspace status`,r=Xa(t);i(e=>r&&e?.identity===n&&e.state===`active`?e:{identity:n,state:r?`offline`:`unavailable`}),o(t)}}finally{s=!1}},l=t=>{let s=t.detail?.refs;!s?.includes(e)&&!(a&&s?.includes(a))||(r++,i({identity:n,state:`stopped`}),o(``))},u=t=>{let s=t.workspaceId||t.id;!s||s!==e&&s!==a||!t.status||(r++,i({identity:n,state:t.status===`active`?`active`:t.status===`inactive`?`stopped`:`unavailable`}),o(``))};c(),window.addEventListener(`workspaces:refresh`,c),window.addEventListener(`workspace:stopped`,l),window.addEventListener(`focus`,c);let d=w.on(`connect`,c);w.on(`workspace:status:changed`,u),w.on(`workspace.status.changed`,u);let p=ao(e=>{e||c()});return()=>{t=!0,d?.(),p(),w.off(`workspace:status:changed`,u),w.off(`workspace.status.changed`,u),window.removeEventListener(`workspaces:refresh`,c),window.removeEventListener(`workspace:stopped`,l),window.removeEventListener(`focus`,c)}},[e,n,l]),r?.identity!==n)return(0,$.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`});if(r.state===`active`)return t;let p=r.state===`stopped`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`font-medium`,children:p?`Workspace stopped`:r.state===`offline`?`Server unreachable`:`Workspace unavailable`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p?`Start this workspace to view its content.`:r.state===`offline`?`Reconnect to load this workspace. Previously loaded content stays available offline.`:`Unable to check this workspace. Try again or check its settings.`}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(X,{disabled:s,onClick:async()=>{c(!0),o(``);try{p&&await Ps(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?p?`Starting…`:`Checking…`:p?`Start workspace`:`Retry`}),d?.identity===n&&d.allowed&&(0,$.jsx)(Le,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]})}function jg({workspaceId:e,workspaceName:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,Q.useEffect)(()=>{let t=!1,n=!1,i=!1,a=0,o=new Map,s=new Map,c=(e,t)=>{let n=e.filter(e=>e.address!==t.backend);if(!t.resyncing)return n;let r=e.find(e=>e.address===t.backend)||s.get(t.backend);return[...n,{address:t.backend,config:r?.config,resyncStartedAt:r?.resyncStartedAt||new Date().toISOString(),progress:t.progress??r?.progress}]},l=async()=>{if(n){i=!0;return}n=!0;let u=a;try{let n=await js(e);if(!t){s=new Map(n.map(e=>[e.address,e]));let e=n.filter(e=>e.resyncing);for(let t of o.values())t.version>u&&(e=c(e,t.event));r(e)}}catch{}finally{n=!1,i&&!t&&(i=!1,l())}},u=t=>{t.workspaceId!==e||!t.backend||typeof t.resyncing!=`boolean`||(o.set(t.backend,{version:++a,event:t}),r(e=>c(e,t)))},d=t=>{t.workspaceId===e&&l()};l();let f=w.on(`connect`,l);return w.on(`backend.resync.changed`,u),w.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),w.off(`backend.resync.changed`,u),w.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,$.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,$.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,$.jsx)(Sa,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,$.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,$.jsx)(ur,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,$.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:i}),(0,$.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,$.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}function Mg({navigationTabs:e,navigationActions:t,onBack:n,accentColor:r,frameContent:i=!0,urlType:a,urlDisplay:o,contextPath:s,treeName:c,workspaceId:l,workspaceLabel:u,workspaceIcon:d,documentSchema:f,documents:p,isLoading:m,totalCount:h,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:M,disablePurgeDocuments:N,canvasInfo:P,isCanvasPinned:ee,onTogglePinCanvas:F,onSaveAsCanvas:I,onShareCanvas:te,onUnshareCanvas:L,onDeleteCanvas:ne,isSharingCanvas:R,isDeletingCanvas:re,isCanvasShared:z,isCanvasLocked:ie,backendSearchQueries:ae,onBackendSearch:B,onRemoveBackendQuery:oe,serverSort:se,onServerSortChange:V,scope:H,onScopeChange:ce,canSaveChanges:le,isSavingChanges:ue,onSaveChanges:de,onBrowseWorkspaces:fe,onBrowseTree:pe,onNavigatePath:me,linkTree:he,children:ge,contentBanner:_e,folders:ve,onOpenFolder:ye}){let be=a===`canvas`,{state:xe,toggleView:U,hasActiveFilters:Se,openAddPicker:W}=Qc(),G=gn(),[Ce,we]=(0,Q.useState)(``),Te=JSON.stringify([l,c,s,f]),[Ee,De]=(0,Q.useState)(Te);Ee!==Te&&(De(Te),we(``));let Oe=(0,$.jsxs)($.Fragment,{children:[t,I&&(0,$.jsx)(`button`,{type:`button`,onClick:I,title:`Save as canvas`,"aria-label":`Save as canvas`,className:`flex h-control-sm w-control-sm shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent touch-target`,children:(0,$.jsx)(vi,{className:`h-4 w-4`})})]});return(0,$.jsxs)(`div`,{className:`flex flex-col h-full min-h-0 bg-background`,children:[e&&(0,$.jsx)(un,{accentColor:r,children:e}),(0,$.jsxs)(`div`,{className:`canvas-surface-body${i?` is-framed`:``}`,children:[(0,$.jsx)(Pt,{workspaceIcon:d,workspace:u||l||o.split(`://`)[0]||`Workspace`,tree:c?`${c}${a.endsWith(`-layer`)?`:layer`:``}`:a.replace(`-layer`,``),path:s,accentColor:r,onBack:G.location?G.location.section===`view`?G.close:()=>G.update?.({section:`view`}):n,section:G.location?`document/${G.location.documentId}/${G.location.section}`:void 0,onSection:G.location?()=>G.update?.({section:`view`}):void 0,onBrowseWorkspaces:fe,onBrowseTree:pe,onNavigatePath:me,onFilter:()=>U(`tools`),filtersActive:Se,filtersOpen:xe.t1Open&&xe.t1View===`tools`,onAdd:e=>W({modal:e.shiftKey,fresh:!0}),search:B||!ge?{queries:ae||[],onSearch:B??we,localOnly:!B,onRemoveQuery:oe,scope:H,onScopeChange:ce}:void 0,onDraftChange:ge?void 0:we}),be&&P?(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[P.color&&(0,$.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:P.color}}),(0,$.jsx)(ri,{className:`w-4 h-4 shrink-0 text-primary`}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:P.label||o.split(`://`)[1]||`Canvas`}),P.description&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:P.description})]}),le&&de&&(0,$.jsxs)(`button`,{type:`button`,onClick:de,disabled:ue,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:`Save filters`,children:[(0,$.jsx)(Fr,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:ue?`Saving...`:`Save filters`})]}),F&&(0,$.jsxs)(`button`,{type:`button`,onClick:F,"aria-pressed":!!ee,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground`,title:ee?`Unpin from home`:`Pin to home`,children:[ee?(0,$.jsx)(qn,{className:`w-3 h-3`}):(0,$.jsx)(wr,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:ee?`Unpin`:`Pin`})]}),te&&(0,$.jsxs)(`button`,{type:`button`,onClick:te,disabled:R||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:z?`Copy public link`:`Share canvas`,children:[(0,$.jsx)(oa,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:R?`Sharing...`:z?`Copy link`:`Share`})]}),z&&L&&(0,$.jsxs)(`button`,{type:`button`,onClick:L,disabled:R||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,$.jsx)(Jn,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),ne&&(0,$.jsxs)(`button`,{type:`button`,onClick:ne,disabled:re||ie&&!z,title:ie&&!z?`Unlock this canvas before deleting it`:`Delete canvas`,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,$.jsx)(Kr,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:re?`Deleting…`:`Delete`})]})]})}):null,ge&&(I||t)&&(0,$.jsx)(`div`,{className:`flex items-center gap-2 border-b px-3 py-1`,children:Oe}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[_e,ge||(0,$.jsx)(rn,{externalSearchQuery:Ce,toolbarActions:Oe,documents:f?p.filter(e=>e.schema===f):p,isLoading:m,folders:f?void 0:ve,onOpenFolder:ye,contextPath:s,treeName:c,workspaceId:l,totalCount:h,viewMode:f?`card`:`table`,allowViewToggle:!0,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:f?void 0:M,disablePurgeDocuments:N,backendSearchQueries:ae,onBackendSearch:B,serverSort:se,onServerSortChange:V,onRemoveBackendQuery:oe,scope:H,onScopeChange:ce,canSaveChanges:!be&&le,isSavingChanges:ue,onSaveChanges:de,linkTree:he},f??`documents`)]})]})]})}var Ng=[{id:`todos`,label:`Todo list`},{id:`todo-app`,label:`Todo App`},{id:`notes`,label:`Notes list`},{id:`notes-app`,label:`Notes App`},{id:`sketch`,label:`Sketch`}];function Pg(e){return e?.kind===`app`&&e.app===`notes`?`data/schema/note`:void 0}var Fg={id:`default`,name:`All`,kind:`documents`};function Ig(){return[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}]}function Lg(e){let t=e?.views;if(!Array.isArray(t))return[Fg];let n=t.filter(e=>{let t=e;return!t||typeof t.id!=`string`||typeof t.name!=`string`?!1:t.kind===`documents`||t.kind===`columns`||t.kind===`app`&&(Ng.some(e=>e.id===t.app)||t.app===`filters`||t.app===`lens`)});return n.length>0?n:[Fg]}var Rg={todos:wi,"todo-app":wi,notes:ya,"notes-app":ya,filters:_a,sketch:ir,lens:Pa};function zg({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=v.current;if(!e)return;let t=t=>{if(t.ctrlKey||e.scrollWidth<=e.clientWidth)return;let n=Math.abs(t.deltaX)>Math.abs(t.deltaY)?t.deltaX:t.deltaY,r=t.deltaMode===1?16:t.deltaMode===2?e.clientWidth:1;t.preventDefault(),e.scrollLeft+=n*r};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[]),(0,Q.useEffect)(()=>{v.current?.querySelector(`[aria-pressed="true"], input`)?.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,c]);let y=()=>{h(null),_(null)},b=()=>{if(m&&g&&m!==g.id){let t=e.find(e=>e.id===m),n=e.filter(e=>e.id!==m),i=n.findIndex(e=>e.id===g.id);t&&i>=0&&(n.splice(g.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!c)return;let t=u.trim();t&&r(e.map(e=>e.id===c?{...e,name:t}:e)),l(null)},S=(t,n)=>{p(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?Ng.find(e=>e.id===n)?.label??`App`:`List`,o=t===`columns`?{id:i,name:a,kind:t,columns:Ig()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),l(i),d(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[Fg],n===t?i[0]?.id??Fg.id:void 0)};return(0,$.jsxs)(`div`,{className:q(`relative flex h-full min-w-0 items-end`,a),children:[(0,$.jsx)(`div`,{ref:v,className:`flex min-w-0 items-end gap-0.5 overflow-x-auto overscroll-x-contain pt-1 [scrollbar-width:none]`,children:e.map(r=>{let a=r.id===t,f=r.kind===`columns`?Aa:r.kind===`app`&&r.app?Rg[r.app]:ki;return c===r.id?(0,$.jsx)(`input`,{autoFocus:!0,"aria-label":`Tab name`,value:u,onChange:e=>d(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&l(null)},className:q(`relative h-[2.3rem] w-28 shrink-0 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs outline-none ring-0`,a?q(`z-[2] bg-background font-medium`,o?ue(o):`text-foreground`):`bg-muted text-muted-foreground`),style:{backgroundColor:a?o:void 0}},r.id):(0,$.jsxs)(`button`,{type:`button`,"aria-pressed":a,onClick:()=>n(r.id),onDoubleClick:()=>{i||(l(r.id),d(r.name))},title:i?r.name:`${r.name}: double-click to rename, drag to reorder`,draggable:!i,onDragStart:e=>{e.dataTransfer.setData(`text/plain`,r.name),e.dataTransfer.effectAllowed=`move`,h(r.id)},onDragOver:e=>{if(!m||m===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;_(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:q(`group relative flex h-[2.3rem] shrink-0 items-center gap-1.5 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs transition-colors`,a?q(`z-[2] bg-background font-medium`,o?ue(o):`text-foreground`):`bg-muted text-muted-foreground hover:bg-accent hover:text-foreground`,m===r.id&&`opacity-50`),style:{backgroundColor:a?o:void 0,boxShadow:g?.id===r.id?`inset ${g.before?`2px`:`-2px`} 0 0 var(--primary)`:void 0},children:[(0,$.jsx)(f,{className:`h-3 w-3 shrink-0`}),(0,$.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,$.jsx)(Ur,{className:`h-3 w-3 shrink-0 opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-60`,"aria-label":`Open to the side`,onClick:e=>{e.stopPropagation(),s(r.id)}}),!i&&e.length>1&&(0,$.jsx)(ur,{className:q(`h-3 w-3 shrink-0 transition-opacity hover:text-destructive`,a?`opacity-60 hover:opacity-100`:`opacity-0 group-hover:opacity-100`),onClick:e=>{e.stopPropagation(),C(r.id)}})]},r.id)})}),!i&&(f?(0,$.jsxs)(`span`,{className:`absolute left-0 top-full z-30 flex w-full min-w-64 flex-wrap items-center gap-2 rounded-b-xl border bg-card p-2 shadow-lg`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(ki,{className:`h-3 w-3`}),` List`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(Aa,{className:`h-3 w-3`}),` Board`]}),Ng.map(e=>{let t=Rg[e.id];return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(t,{className:`h-3 w-3`}),` `,e.label]},e.id)}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,$.jsx)(ur,{className:`h-3 w-3`})})]}):(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(!0),title:`Add view`,"aria-label":`Add view`,className:`relative ml-1 flex h-[2.3rem] w-10 shrink-0 items-center justify-center rounded-md pb-1 text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,$.jsx)(Bi,{className:`h-3.5 w-3.5`})}))]})}function Bg(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let o=!1;return lc(e,n,t,{limit:200,allOf:[r],...i?{sortBy:i,order:`asc`}:{}}).then(e=>{o||l({key:a,docs:e.payload||[]})}).catch(()=>{o||l({key:a,docs:[]})}),()=>{o=!0}},[a,o]);let u=c?.key===a?c.docs:[],d=c?.key!==a;return(0,Q.useEffect)(()=>{let e=()=>s(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]),{docs:u,isLoading:d,refresh:(0,Q.useCallback)(()=>s(e=>e+1),[])}}function Vg({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=Bg(e,t,n,Lo,`tasks`),[o,s]=(0,Q.useState)(!1),c=o?r.filter(e=>e.data?.status!==`completed`):r,l=r.filter(e=>{let t=e.data?.status;return t!==`completed`&&t!==`cancelled`}).length;return(0,$.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,$.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,$.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,$.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,$.jsx)(Wd,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function Hg({app:e,contextId:t,...n}){let r=t&&e!==`lens`?{mode:`context`,contextId:t}:{mode:`workspace`,workspaceName:n.workspaceId,treeName:n.treeName,path:n.path,treeType:n.treeName===`directory`||n.treeName===`backends`?`directory`:`context`},i=e===`todo-app`?`todo`:e===`notes-app`?`notes`:e,a=Um.find(e=>e.id===i);return(0,$.jsx)(Gm,{target:r,children:e===`todos`?(0,$.jsx)(Vg,{...n}):a?(0,$.jsx)(a.Component,{}):null})}var Ug=[{id:`emails`,label:`Emails`,schemas:[`data/schema/message`]},{id:`todos`,label:`Todos`,schemas:[`data/schema/task`]},{id:`notes`,label:`Notes`,schemas:[`data/schema/note`]},{id:`links`,label:`Links`,schemas:[`data/schema/tab`,`data/schema/link`]},{id:`files`,label:`Files`,schemas:[`data/schema/file`]}];function Wg(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function Gg({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)({}),[d,f]=(0,Q.useState)({}),p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1),g=(0,Q.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,Q.useEffect)(()=>{let e=p.current;if(!e)return;let t=new ResizeObserver(()=>g());return t.observe(e),()=>t.disconnect()},[g]);let _=(e,t)=>{e.preventDefault();let i=e.currentTarget.parentElement;if(!i)return;let a=e.clientX,o=i.getBoundingClientRect().width,s=o,c=e=>{s=Math.min(900,Math.max(220,o+e.clientX-a)),f(e=>({...e,[t]:s}))},l=()=>{window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),r(n.map(e=>e.id===t?{...e,width:Math.round(s)}:e))};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l)},v=e=>{f(t=>{let n={...t};return delete n[e],n}),r(n.map(t=>t.id===e?{...t,width:void 0}:t))},y=e=>{let t=l[e];if(t===void 0)return;let i=n.find(t=>t.id===e);i&&(i.filter||``)!==t&&r(n.map(n=>n.id===e?{...n,filter:t||void 0}:n))},b=Ug.filter(e=>!n.some(t=>t.id===e.id));return(0,$.jsxs)(`div`,{className:`relative h-full`,children:[(0,$.jsx)(`div`,{ref:p,onScroll:g,className:`flex h-full snap-x snap-mandatory gap-3 overflow-x-auto overscroll-x-contain p-2`,"data-testid":`schema-columns-board`,children:n.map(t=>{let a=(l[t.id]??t.filter??``).toLowerCase(),s=e.filter(e=>Wg(e,t.schemas)).filter(e=>{if(!a)return!0;let t=ns(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,$.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-(--card-radius) border bg-muted/20 ${c?`sm:basis-[var(--col-w)]`:`sm:basis-[48%] lg:basis-[32%] xl:basis-[24%]`}`,style:c?{"--col-w":`${c}px`}:void 0,children:[!i&&(0,$.jsx)(`div`,{onPointerDown:e=>_(e,t.id),onDoubleClick:()=>v(t.id),title:`Drag to resize; double-click to reset`,className:`absolute right-0 inset-y-0 z-10 w-2 cursor-col-resize touch-none rounded-r-lg transition-colors hover:bg-primary/25 active:bg-primary/40 max-sm:hidden`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,$.jsx)(`span`,{className:`flex-1`}),!i&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(n.filter(e=>e.id!==t.id)),title:`Remove column`,className:`rounded-sm p-0.5 text-muted-foreground hover:text-destructive`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(`div`,{className:`px-3 pb-2`,children:(0,$.jsx)(`input`,{value:l[t.id]??t.filter??``,onChange:e=>u(n=>({...n,[t.id]:e.target.value})),onBlur:()=>y(t.id),onKeyDown:e=>{e.key===`Enter`&&y(t.id)},placeholder:`Filter…`,readOnly:i,className:`h-7 w-full rounded-md border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})}),(0,$.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=ns(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o(e),className:`w-full min-w-0 rounded-md border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(F,{document:e,size:3.5}),(0,$.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,$.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,$.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground/70`,children:new Date(e.updatedAt||e.createdAt).toLocaleDateString()})]},e.id)}),s.length===0&&(0,$.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground/60`,children:`Empty`})]})]},t.id)})}),(!i&&b.length>0||m)&&(0,$.jsxs)(`div`,{className:`pointer-events-none absolute inset-y-0 right-0 z-20 flex w-7 flex-col items-end bg-gradient-to-l from-background via-background/60 to-transparent py-2`,children:[!i&&b.length>0&&(0,$.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(e=>!e),title:`Add column`,"aria-label":`Add column`,className:`flex h-7 w-6 items-center justify-center rounded-l-md border border-r-0 bg-background text-muted-foreground shadow-elevation-1 hover:bg-accent hover:text-foreground`,children:(0,$.jsx)(Bi,{className:`h-3.5 w-3.5`})}),s&&(0,$.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,$.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>{c(!1),r([...n,{...e}])},className:`w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:e.label},e.id)),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`mt-1 w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/60 hover:bg-accent/50`,children:`Cancel`})]})]}),m&&(0,$.jsx)(Va,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,$.jsx)(ke,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var Kg=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function qg(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function Jg(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>Jg(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:qg(e)}];let r=Kg(e);if(!r)return[];let i=r.tree??r.treeId,a=typeof i==`string`?n.get(i)??null:null;return[].concat(r.paths??r.path??`/`).filter(e=>typeof e==`string`).map(e=>({tree:a,kind:t,path:qg(e)}))}function Yg(e){let t=[],n=e=>{let n=Number(e);Number.isSafeInteger(n)&&n>0&&t.push(n)};return Array.isArray(e.ids)&&e.ids.forEach(n),Array.isArray(e.documentIds)&&e.documentIds.forEach(n),e.id!=null&&n(e.id),e.documentId!=null&&n(e.documentId),t}function Xg(e){let t=new Map;for(let n of e)t.set(n.id,n.name),t.set(n.name,n.name);return t}function Zg(e,t,n=new Map){let r=Kg(t);if(!r)return{targets:[],ids:[],unknown:!0};if(e.startsWith(`tree.`)){let e=typeof r.treeName==`string`?r.treeName:null,t=r.treeType===`directory`||r.treeType===`context`?r.treeType:null,n=r.contextSpec??r.path;return typeof n==`string`?{targets:[{tree:e,kind:t,path:qg(n)}],ids:Yg(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...Jg(r.context,`context`,n),...Jg(r.directory,`directory`,n)],a=Kg(r.changed);a&&i.push(...Jg(a.context,`context`,n),...Jg(a.directory,`directory`,n));let o=Yg(r);if(i.length)return{targets:i,ids:o,unknown:!1};let s=r.reason===`content`||r.reason===`relations`;return e.startsWith(`document.updated`)&&s&&o.length?{targets:[],ids:o,unknown:!1}:{targets:[],ids:o,unknown:!0}}function Qg(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function $g(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>qg(e).split(`/`).filter(Boolean).map(e=>e.normalize(`NFKC`).trim().replace(/\s+/g,` `).replace(/[^\p{L}\p{N}\p{M} .+_@-]/gu,`_`).replace(/_+/g,`_`).toLowerCase()||`_`),r=new Set(n(e.path)),i=n(t.path);return r.size===0||i.length===0||i.some(e=>r.has(e))}return Qg(e.path,t.path)}function e_(e){return Zg(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function t_(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>$g(e,t))))return!0;if(e.ids.length&&n){let t=n instanceof Set?n:new Set(n);if(e.ids.some(e=>t.has(e)))return!0}return!1}var n_=(0,Q.createContext)(null);function r_(){let e=(0,Q.useContext)(n_);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function i_(e,t,n={}){return w.request(Rl,{workspace:e,specs:t,opts:n})}function a_(e,t,n){return w.request(zl,{sessionId:e,label:t,spec:n})}function o_(e){return w.request(Bl,{sessionId:e})}function s_(e,t={}){return w.request(Vl,{sessionId:e,...t})}function c_(e){return w.request(Hl,{sessionId:e})}function l_(e){return w.on(Ul,e)}var u_=100;function d_({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),f=(0,Q.useRef)([]),p=(0,Q.useRef)(new Map),m=(0,Q.useRef)(null),h=(0,Q.useRef)(null),g=(0,Q.useRef)(null),_=(0,Q.useRef)({}),v=(0,Q.useRef)(null),y=(0,Q.useMemo)(()=>JSON.stringify(t),[t]),b=(0,Q.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,Q.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,Q.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=u_){let i=e.slice(r,r+u_),a=await Ks(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,Q.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),x(),r.length===0)return;let a=await S(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}x()},[S,x]),T=(0,Q.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await C(a,[],t)},[C]);(0,Q.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await i_(e,JSON.parse(y),JSON.parse(b));if(t){c_(r.sessionId).catch(()=>{});return}n=r.sessionId,m.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await T(r.ids,r.count)}catch(e){if(t)return;d(e instanceof Error?e.message:`Failed to open query session`),l(null),m.current=null}};i();let o=w.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&c_(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,Q.useEffect)(()=>{if(!c)return;let e=l_(e=>{if(e.sessionId===c){if(g.current!==null){v.current?.(g.current,_.current);return}e.ids===void 0?C(e.added??[],e.removed??[],e.count):T(e.ids,e.count)}});return()=>{e?.()}},[c,C,T]);let E=(0,Q.useCallback)(async()=>{let e=m.current;if(e)try{let t=await o_(e);await T(t.ids,t.count)}catch{}},[T]),D=(0,Q.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await a_(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await T(r.ids,r.count)},[T]),O=(0,Q.useCallback)(async(e,t={})=>{let n=m.current;if(!n)throw Error(`No open query session`);if(g.current=e,_.current=t,e===null){await E();return}let r=await s_(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),x()},[x,E]);(0,Q.useEffect)(()=>{v.current=O},[O]);let k=(0,Q.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await s_(r,{match:t,limit:n.limit??100,...n.mode?{mode:n.mode}:{}});for(let e of i.documents)p.current.set(e.id,e);let a=await a_(r,e,{ids:i.ids});return await T(a.ids,a.count),i.ids},[T]);return{documents:i,count:o,ready:c!==null,error:u,setCue:D,resync:E,rank:O,rankAndPin:k}}var f_=`canvas:query-debug`,p_=`canvas:query-debug-changed`;function m_(){try{return localStorage.getItem(f_)===`1`}catch{return!1}}function h_(e){try{e?localStorage.setItem(f_,`1`):localStorage.removeItem(f_)}catch{}window.dispatchEvent(new CustomEvent(p_,{detail:e}))}function g_(){let[e,t]=(0,Q.useState)(m_);return(0,Q.useEffect)(()=>{let e=()=>t(m_());return window.addEventListener(p_,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(p_,e),window.removeEventListener(`storage`,e)}},[]),e}function __({data:e,className:t}){let[n,r]=(0,Q.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,Q.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,$.jsxs)(`div`,{className:q(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let s=a>0?i[a].distance:null;return(0,$.jsxs)(`div`,{className:q(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,$.jsx)(Hr,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Va,{className:`h-3.5 w-3.5`}),`Query debug`,(0,$.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,$.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,s===null?(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,$.jsxs)($.Fragment,{children:[` A jump at `,(0,$.jsx)(`span`,{className:`font-mono`,children:s.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,$.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,$.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,$.jsx)(`tbody`,{children:i.map((e,t)=>(0,$.jsxs)(`tr`,{className:q(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,$.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,$.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,$.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,$.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}function v_(e,t){if(!e)return[];let n=t.split(`/`).filter(Boolean),r=e;for(let e of n)if(r=r?.children?.find(t=>t.name===e)??null,!r)return[];let i=n.length?`/${n.join(`/`)}`:``,a=(r.children??[]).filter(e=>e.type!==`canvas`).map(e=>({name:e.name,path:`${i}/${e.name}`,label:e.label,color:e.color,childCount:e.children?.length??0})).sort((e,t)=>(e.label||e.name).localeCompare(t.label||t.name,void 0,{numeric:!0,sensitivity:`base`}));return n.length>0&&a.unshift({name:`..`,path:n.length>1?`/${n.slice(0,-1).join(`/`)}`:`/`,isParent:!0}),a}var y_=new Map;function b_(e,t,n){return`${e}\0${t}\0${n}`}function x_(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${b_(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function S_(e,t,n){let r=b_(e,t,n);for(let e of y_.keys())e.startsWith(r)&&y_.delete(e)}function C_(e,t){let n=`${e}\0`;for(let[e,r]of y_){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);t_(t,{tree:i,kind:jc(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&y_.delete(e)}}function w_(e,t){C_(t?.workspaceName??e,e_(t))}function T_(){let{workspaceName:e}=wt();return e?(0,$.jsx)(Ag,{workspaceName:e,children:(0,$.jsx)(E_,{})}):null}function E_(){let{workspaceName:e,treeName:t}=wt(),n=Bt(),r=Qt(),{showToast:i,showProgress:a}=Z(),o=new URLSearchParams(n.search),s=(()=>{let e=o.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(o.get(`search`)||``).trim();return t?[t]:[]})(),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(!0),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(0),v=g_(),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(v);x!==v&&(S(v),v||b(null));let[C,T]=(0,Q.useState)(`path`),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(null),[A,j]=(0,Q.useState)(null),[M,N]=(0,Q.useState)(``),[P,ee]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[te,L]=(0,Q.useState)(!1),[ne,R]=(0,Q.useState)(null),[re,z]=(0,Q.useState)(1),[ie,ae]=(0,Q.useState)(50),[B,oe]=(0,Q.useState)(s),[se,V]=(0,Q.useState)(null),{state:H,saveFilters:ce,setSort:le,setAccentColor:ue,setMapDocuments:de}=Qc(),fe=H.filters.features.allOf,pe=H.filters.features.anyOf,me=H.filters.features.noneOf,he=tt(H.filters.timeline),ge=_n(H.filters.geo),ve=Ee(H.filters.lens,H.filters.geo.includeUnlocated),ye=H.filters.lens.ids,be=[...he,...ge,...ve],xe=H.filters.sort??dn,U=JSON.stringify({a:fe,b:pe,c:me,d:be,i:ye,s:xe}),Se=JSON.stringify({a:fe,b:pe,c:me,d:be,s:xe}),W=Jd(n.pathname).path,G=t??`context`,Ce=G===`backends`,[we,Te]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{!Ce||!e||js(e).then(Te).catch(()=>Te([]))},[Ce,e]);let De=Ce?pc(W,we):null,[Oe,ke]=(0,Q.useState)(!1),Ae=`${G}\0${W}`,[je,Me]=(0,Q.useState)(Ae);je!==Ae&&(Me(Ae),ke(!1));let Ne=o.get(`layer`)===`1`,Pe=o.get(`layerId`)||null,[Fe,K]=(0,Q.useState)(null),[Ie,Le]=(0,Q.useState)(null),Re=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{Re.current=Ie},[Ie]);let[ze,Be]=(0,Q.useState)(`left`),[Ve,He]=(0,Q.useState)([]),{openM1Drawer:Ue,openM2Drawer:We,goBack:Ge}=Xh(),[Ke,qe]=(0,Q.useState)([]),Je=(0,Q.useMemo)(()=>{if(!Fe||W===`/`||Ne)return null;let e=W.split(`/`).filter(Boolean),t=Fe;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Fe,W,Ne]),Ye=Je?.type===`canvas`?`canvas`:null,Xe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{!e||!Fe||Ne||Xe.current===`${e}/${G}`&&(W!==`/`&&!Je||Sh(e,G,W))},[e,Fe,Ne,W,Je,G]);let Ze=(0,Q.useMemo)(()=>Ne||C===`workspace`||B.length>0||jc(G)!==`directory`?[]:v_(Fe,W),[Fe,W,G,Ne,C,B]),Qe=Ne?null:W===`/`?Fe:Je,$e=`${G}\0${W}`,[et,nt]=(0,Q.useState)(null),rt=et?.key===$e?et.views:Lg(Qe?.metadata),it=et?.key===$e?et.activeId:rt[0]?.id??Fg.id,at=rt.find(e=>e.id===it)??rt[0]??Fg,ot=Ce?void 0:Pg(at),st=ot?[...fe,ot]:fe,ct=e=>{z(1),He([]),nt({key:$e,views:rt,activeId:e})},lt=(t,n)=>{n&&n!==it&&(z(1),He([])),nt({key:$e,views:t,activeId:n??it}),Mo(e,W,{metadata:{...Qe?.metadata??{},views:t}},G).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},ut=Ye===`canvas`&&typeof Je?.querySpec?.query==`string`?Je.querySpec.query:``,dt=Ye===`canvas`?{label:Je?.label,description:Je?.description,color:Je?.color}:null,{isPinned:ft,pin:mt,unpin:ht,pins:gt}=r_(),_t=c?.name,vt=(0,Q.useMemo)(()=>_t&&Ye===`canvas`&&!Ne?{workspaceName:_t,treeName:G,path:W}:null,[_t,Ye,Ne,G,W]),yt=vt?ft(vt):!1,bt=Je?.id,xt=Je?.label,Ct=(0,Q.useCallback)(async()=>{if(vt)try{let e=gt.find(e=>e.workspaceName===vt.workspaceName&&e.treeName===vt.treeName&&e.path===vt.path);e?await ht(e.id):await mt({...vt,layerId:bt,label:xt})}catch(e){console.error(`Failed to update home pins:`,e)}},[vt,gt,mt,ht,bt,xt]),Tt=e?`${e}://${W===`/`?``:W.replace(/^\//,``)}`:``,Et=Tn(c?.color)||null;(0,Q.useEffect)(()=>(ue(Et),()=>ue(null)),[Et,ue]);let Dt=(0,Q.useCallback)(async t=>{let n=ye;if(t?.anyOf?.length&&pe.length&&(n=((await lc(e,W,G,{limit:0,anyOf:pe,ids:ye,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await lc(e,W,G,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...fe,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:pe,noneOf:me,filters:be,ids:n,queries:[...B,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,W,G,U,B]);(0,Q.useEffect)(()=>{e&&(async()=>{d(!0);try{let t=await Y.get(`${qa.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,l(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;i({title:`Error`,description:n,variant:`destructive`}),l(null)}finally{d(!1)}})()},[e,i]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&l(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let Ot=(ye?.length??0)>0&&!Ne&&!(Oe&&De)&&B.length<=1,{documents:kt,count:At,ready:jt,setCue:Mt,resync:Nt,rank:Ft}=d_({workspaceRef:e,specs:(0,Q.useMemo)(()=>{let e={features:{allOf:st,anyOf:pe,noneOf:me},filters:be};return C!==`workspace`&&(jc(G)===`directory`?e.directory={tree:G,path:W}:e.context=W),[{label:`scope`,spec:e}]},[Se,W,G,C,ot]),opts:(0,Q.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:Ot}),It=Ot&&jt,Lt=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{Lt.current=It},[It]);let Rt=B.length===1?B[0].trim():``;(0,Q.useEffect)(()=>{jt&&Ft(Rt?{text:Rt}:null,{limit:ie,offset:(re-1)*ie}).catch(()=>{})},[jt,Rt,ie,re,Ft]);let zt=(ye??[]).join(`,`);(0,Q.useEffect)(()=>{jt&&Mt(`lens`,{ids:ye??[]}).catch(()=>{})},[jt,zt,Mt,ye]);let Vt=It?kt:f,Ht=It?At:g,Ut=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{Ut.current=new Set(Vt.map(e=>Number(e.id)))},[Vt]);let Wt=H.geoSelection;(0,Q.useEffect)(()=>{de(Vt,c?.name??null)},[Vt,c?.name,de]),(0,Q.useEffect)(()=>()=>de([]),[de]);let Gt=(0,Q.useMemo)(()=>Wt?Vt.filter(e=>_e(e,Wt,H.filters.geo.includeUnlocated)):Vt,[Vt,Wt,H.filters.geo.includeUnlocated]),Kt=Ls(W,st,{treeName:G,treeType:jc(G),scope:C,queries:B,anyOf:pe,noneOf:me,filters:be,ids:ye,layerId:Ne&&Pe?Pe:void 0}),qt=JSON.stringify([e,Kt]),[Jt,Yt]=(0,Q.useState)(``),[Zt,$t]=(0,Q.useState)(!1),en=(0,Q.useRef)(!1),tn=m||Zt||Jt!==qt||It||!!Wt,nn=(0,Q.useRef)(0),rn=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{nn.current++,rn.current=null},[]);let an=(0,Q.useRef)(``),on=(0,Q.useCallback)(async t=>{if(!e)return;if(pt(G,W)){nn.current++,rn.current=null,an.current=``,p([]),_(0),h(!1);return}if(Lt.current)return;let n=`${Oe&&De?`${C}:unfiled`:C}:${ot??``}`,r=(ye?.length??0)>0,a=x_(e,G,W,re,ie,B.join(`␟`),Se,Ne&&Pe?Pe:``,n),o=r&&a===an.current;an.current=a;let s=x_(e,G,W,re,ie,B.join(`␟`),U,Ne&&Pe?Pe:``,n),c=`${s}\0${v}`;if(t?.silent&&rn.current?.key===c){rn.current.refreshPending=!0;return}let l=++nn.current,u=t?.silent||r||v?void 0:y_.get(s);u&&(p(u.documents),_(u.totalCount),Yt(qt),h(!1)),(t?.silent??(o||!!u))||h(!0);let d={key:c,refreshPending:!1};rn.current=d;try{let t;t=Oe&&De?await Cc(e,De.driver,De.address,{linked:!1,limit:ie,offset:(re-1)*ie}):Ne&&Pe&&C!==`workspace`?await Os(e,G,Pe,{limit:ie,page:re,queries:B,allOf:st,anyOf:pe,noneOf:me,filters:be,ids:ye,sortBy:xe.sortBy||void 0,order:xe.order}):await Ks(e,W,st,{limit:ie,page:re,treeName:G,treeType:G===`directory`||G===`backends`?`directory`:`context`,queries:B,anyOf:pe,noneOf:me,filters:be,ids:ye,sortBy:xe.sortBy||void 0,order:xe.order,scope:C,debug:v&&B.length>0,debugLimit:200});let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&y_.set(s,{documents:n,totalCount:i}),l!==nn.current)return;let a=t.debug,c=a?.imageDistances??a?.distances??null;b(c?{query:B[B.length-1]??``,distances:c}:null),p(o?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),_(i),Yt(qt)}catch(e){if(l!==nn.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),p([]),_(0)}finally{rn.current===d&&(rn.current=null),l===nn.current&&h(!1),l===nn.current&&d.refreshPending&&on({silent:!0})}},[e,W,G,Pe,Ne,re,ie,c?.status,B,U,C,Oe,v,ot]);(0,Q.useEffect)(()=>{on()},[on]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Le({treeName:n.treeName||`context`,path:Kd(n.path||`/`)}),Be(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,G,W]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&w_(e,n),t_(e_(n),{tree:G,kind:jc(G),path:W,wholeWorkspace:C===`workspace`}))){if(e&&S_(e,G,W),Lt.current){Nt();return}on({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[on,e,W,G,C,Nt]);let sn=c?.name,cn=c?.id;(0,Q.useEffect)(()=>{if(!e||!sn&&!cn)return;let t=[sn,cn].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>w.emit(`subscribe`,{channel:e}));n();let r=w.on(`connect`,n),i=new Map,a=!1,o=()=>{Qo(e).then(e=>{a||(i=Xg(e))}).catch(()=>{})};o();let s=null,c=0,l=!1,u=null,d=()=>{if(s=null,c=Date.now(),u){let{treeName:t,path:n}=u;u=null,window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}if(l){if(l=!1,Lt.current){Nt();return}on({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=Zg(t,n,i);C_(e,r);let a={tree:G,kind:jc(G),path:W,wholeWorkspace:C===`workspace`},f=Re.current;f&&t_(r,{tree:f.treeName,kind:jc(f.treeName),path:f.path})&&(u=f),t_(r,a,Ut.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.inserted.batch`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>w.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>w.off(e,t))}},[e,cn,sn,G,W,C,on,Nt]);let ln=`${W}\0${G}\0${Pe??``}\0${C}`,[un,fn]=(0,Q.useState)(ln);un!==ln&&(fn(ln),z(1),V(null));let pn=`${W}\0${G}\0${Pe??``}`,[mn,hn]=(0,Q.useState)(pn);mn!==pn&&(hn(pn),T(`path`));let gn=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;N(n),j({parentPath:e,captureView:t})},vn=o.get(`createCanvas`)===`1`,[yn,bn]=(0,Q.useState)(!1);yn!==vn&&(bn(vn),vn&&gn(W,!1)),(0,Q.useEffect)(()=>{if(!vn)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[vn,W]);let xn=(0,Q.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let i=t.toString();r(`${n.pathname}${i?`?${i}`:``}${n.hash}`)},[n.pathname,n.search,n.hash,r]),Sn=JSON.stringify([o.has(`q`),...s]),[Cn,wn]=(0,Q.useState)(Sn);Cn!==Sn&&(wn(Sn),oe(s),z(1));let En=`${Sn}\0${Ye??``}\0${ut}\0${W}\0${se??``}`,[Dn,On]=(0,Q.useState)(En);Dn!==En&&(On(En),o.has(`q`)||s.length>0||Ye!==`canvas`||se===W||(oe(ut?[ut]:[]),z(1)));let kn=(0,Q.useCallback)(e=>{let t=e.trim();t&&(V(null),oe(e=>{if(e.includes(t))return e;let n=[...e,t];return xn(n),z(1),n}))},[xn,V,oe,z]),An=(0,Q.useCallback)(e=>{oe(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&V(W),xn(n),z(1),n})},[xn,W,V,oe,z]),jn=B.join(` `).trim(),Mn=!!H.activeContextType&&(H.isDirty||jn!==(Ye===`canvas`?ut:H.savedSearchQuery||``));!e&&Fe!==null&&K(null),(0,Q.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&Vs(e,G),Wo(e,G).then(i=>{!t&&a===n&&(r=!0,Xe.current=`${e}/${G}`,K(i))}).catch(()=>{!t&&a===n&&!r&&K(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==G||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=St(e,cn);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,G,cn]),!(e&&Ye===`canvas`&&!Ne)&&ne!==null&&R(null),(0,Q.useEffect)(()=>{let t=!1;if(!(!e||Ye!==`canvas`||Ne))return xs(e,W,G).then(e=>{t||R(e)}).catch(()=>{t||R(null)}),()=>{t=!0}},[e,W,G,Ye,Ne]);let Nn=async()=>{if(c){D(!0);try{let t=await Ps(e||c.id);l(t),i({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;i({title:`Error`,description:t,variant:`destructive`})}finally{D(!1)}}},Pn=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`Document from "${W}"`});try{await as(e||c.id,[t],W,[],G,Hn,{trashIfOrphaned:!0}),S_(e||c.id,G,W),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document removed from workspace path.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Fn=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`Document from "${W}"`});try{await jo(e||c.id,[t],W,[],G,Hn),S_(e||c.id,G,W),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},In=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`${t.length} document(s) from "${W}"`});try{await as(e||c.id,t,W,[],G,Hn,{trashIfOrphaned:!0}),S_(e||c.id,G,W),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Ln=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`${t.length} document(s)`});try{await jo(e||c.id,t,W,[],G,Hn),S_(e||c.id,G,W),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Rn=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await Ys(e||c.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},zn=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await Ys(e||c.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);p(e=>e.filter(e=>!i.has(e.id))),_(e=>Math.max(0,e-i.size));let a=[r.successful?.length?`${r.successful.length} destroyed`:null,r.failed?.length?`${r.failed.length} failed`:null].filter(Boolean).join(`, `);r.failed?.length?n.fail({title:`Destroy incomplete`,description:a,variant:`destructive`}):n.done({title:`Destroyed`,description:a||`No documents destroyed`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},Bn=e=>{k({documentIds:e,operation:`copy`,sourcePath:W,sourceTreeName:G}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Vn=e=>{k({documentIds:e,operation:`cut`,sourcePath:W,sourceTreeName:G}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Hn=jc(G),Un=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??G,o=r.targetTreeType??Hn,s=r.move??O?.operation===`cut`,c=a({title:s?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let a=await vs(e,t,n,i,o);if(a){S_(e,i,t);let a=r.sourceTreeName||O?.sourceTreeName,o=r.sourcePath||O?.sourcePath;if((r.move??O?.operation===`cut`)&&o&&a){let t=jc(a);await as(e,n,o,[],a,t),S_(e,a,o),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:o,treeName:a}}))}c.done({title:`Success`,description:`${n.length} document(s) ${s?`moved`:`pasted`} to "${t}"`}),k(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await on(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else c.done();return a}catch(e){return c.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Wn=async(t,n)=>{if(!e)return!1;try{let r=(await Fs(e,n,t,G,Hn)).length>0;return r&&(Xt(e,G,n),i({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},Gn=async()=>{if(!c||Ht===0||tn||en.current||window.prompt(`Type PURGE to permanently delete all ${Ht} matching documents across all pages.`)!==`PURGE`)return;en.current=!0,$t(!0);let t=a({title:`Purging…`,description:`${Ht} matching document(s)`});try{let n=await gs(e||c.id,Kt,Ht);n.deleted===n.requested?t.done({title:`Success`,description:`${n.deleted} document(s) purged.`}):t.fail({title:`Purge incomplete`,description:`${n.deleted} of ${n.requested} document(s) purged. Refresh and review the remaining results before retrying.`})}catch(e){t.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}finally{S_(e||c.id,G,W),await on({silent:!0}),en.current=!1,$t(!1)}},Kn=()=>gn(W,!0),qn=async()=>{if(!(!e||!A||!M.trim())){ee(!0);try{let t=M.trim(),n=A.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`,a={...H.filters,features:{...H.filters.features,allOf:st}};await Dc(e,i,G,A.captureView?{metadata:{toolbox:a},querySpec:{features:a.features,filters:[...tt(H.filters.timeline),..._n(H.filters.geo)],query:jn||void 0,sort:H.filters.sort?.sortBy?H.filters.sort:null}}:{}),j(null),Vs(e,G);try{let t=await Wo(e,G,{force:!0});K(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(Yd(e,i,G))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{ee(!1)}}},Jn=async()=>{if(!(!e||Ye!==`canvas`)){I(!0);try{let t=ne||await Ac(e,W,G);R(t);let n=`${window.location.origin}${t.url}`;await navigator.clipboard?.writeText(n),i({title:`Public canvas link copied`,description:n})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to share canvas`,variant:`destructive`})}finally{I(!1)}}},Yn=async()=>{if(ne){I(!0);try{await To(ne.code),R(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:G}})),i({title:`Canvas unshared`,description:`The public link no longer works.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to unshare canvas`,variant:`destructive`})}finally{I(!1)}}},Xn=async()=>{if(!e||Ye!==`canvas`||W===`/`)return;let t=dt?.label||W.split(`/`).pop()||`canvas`,n=ne?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){L(!0);try{if(ne)await To(ne.code),R(null);else if(Je?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await bo(e,W,!1,G);let n=W.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:G}})),r(Yd(e,a,G)),i({title:`Canvas deleted`,description:`"${t}" was removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete canvas`,variant:`destructive`})}finally{L(!1)}}},Zn=(0,Q.useCallback)(async t=>{if(!e||!Ie)return;let n={treeName:G,path:W},r=ze===`left`?n:Ie,o=ze===`left`?Ie:n,s=ze===`left`?Ve:Ke;if(s.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let c=jc(o.treeName),l=a({title:t?`Moving…`:`Copying…`,description:`${s.length} document(s) → "${o.path}"`});try{if(!await vs(e,o.path,s,o.treeName,c)){l.done();return}if(S_(e,o.treeName,o.path),t){let t=jc(r.treeName);await as(e,s,r.path,[],r.treeName,t),S_(e,r.treeName,r.path)}[r,o].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),l.done({title:t?`Moved`:`Copied`,description:`${s.length} document(s) → "${o.path}"`})}catch(e){l.fail({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,Ie,ze,G,W,Ve,Ke,i,a]);if((0,Q.useEffect)(()=>{if(!Ie)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),Zn(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ie,Zn]),u)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!c)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let Qn=Ye===`canvas`&&!Ne&&!!Je,$n=!Qn&&!Ce&&Qe?(0,$.jsx)(zg,{views:rt,activeId:it,onSelect:ct,onSave:lt,accentColor:Tn(c.color),onOpenToSide:e=>{Le({treeName:G,path:W,viewId:e}),Be(`right`)}}):void 0,er=De||c.status!==`active`?(0,$.jsxs)($.Fragment,{children:[De&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{ke(!Oe),z(1)},"aria-pressed":Oe,className:q(`min-h-10 rounded-md border px-2 text-xs`,Oe&&`bg-warning/15 text-warning`),children:`Unfiled only`}),c.status!==`active`&&(0,$.jsx)(`button`,{type:`button`,onClick:Nn,disabled:E,className:`min-h-10 rounded-md border px-2 text-xs`,children:E?`Starting…`:`Start`})]}):void 0,tr=pt(G,W)?W===`/Trash`?(0,$.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,$.jsx)(Og,{workspaceName:e||c.id})}):(0,$.jsx)(wg,{workspace:e||c.id,path:W,onNavigate:t=>r(Yd(e,t,`backends`))},e):(0,$.jsx)(Mg,{navigationTabs:$n,navigationActions:er,onBack:Ge,accentColor:Tn(c.color),urlType:Ne?jc(G)===`directory`?`${G}-layer`:`context-layer`:Ye===`canvas`?`canvas`:jc(G)===`directory`?G:`context`,urlDisplay:Tt,contextPath:W,treeName:G,workspaceId:e||c.id,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,documentSchema:ot,documents:Gt,isLoading:m,totalCount:Ht,currentPage:re,pageSize:ie,onPageChange:z,onPageSizeChange:e=>{ae(e),z(1)},onRemoveDocument:W===`/`?void 0:Pn,onDeleteDocument:Fn,onDestroyDocument:Rn,onRemoveDocuments:W===`/`?void 0:In,onDeleteDocuments:Ln,onDestroyDocuments:zn,onCopyDocuments:Bn,onCutDocuments:Vn,onPasteDocuments:Ce?void 0:Un,onImportDocuments:Ce?void 0:Wn,onSelectionChange:He,onBrowseTree:()=>We(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>Ue(`workspaces`),onNavigatePath:t=>r(Yd(e,t,G)),folders:Ze,onOpenFolder:t=>r(Yd(e,Kd(t),G)),scope:C,onScopeChange:T,pastedDocumentIds:O?.documentIds,linkTree:Fe,onPurgeDocuments:Ce?void 0:Gn,disablePurgeDocuments:tn,canvasInfo:dt??void 0,isCanvasPinned:yt,onTogglePinCanvas:vt?Ct:void 0,onSaveAsCanvas:Fe&&Ye!==`canvas`&&!Ne&&!Ce?Kn:void 0,onShareCanvas:Ye===`canvas`&&!Ne?Jn:void 0,onUnshareCanvas:ne?Yn:void 0,onDeleteCanvas:Ye===`canvas`&&!Ne?Xn:void 0,isSharingCanvas:F,isDeletingCanvas:te,isCanvasShared:!!ne,isCanvasLocked:!!Je?.locked,backendSearchQueries:B,onBackendSearch:kn,serverSort:H.filters.sort,onServerSortChange:le,onRemoveBackendQuery:An,canSaveChanges:Mn,isSavingChanges:H.isSaving,onSaveChanges:ce,contentBanner:v&&y?(0,$.jsx)(__,{data:y,className:`mb-3`}):null,children:Qn&&Je?(0,$.jsx)(yf,{workspaceId:e||c.id,treeName:G,path:W,layerId:Je.id,querySpec:Je.querySpec,metadata:Je.metadata,isLocked:!!Je.locked,fetchDocuments:H.isDirty?Dt:void 0}):!Ce&&at.kind===`columns`?(0,$.jsx)(Gg,{documents:Gt,workspaceId:e||c.id,columns:at.columns??[],onColumnsChange:e=>lt(rt.map(t=>t.id===at.id?{...t,columns:e}:t))}):!Ce&&at.kind===`app`&&at.app&&at.app!==`notes`?(0,$.jsx)(Hg,{app:at.app,workspaceId:e||c.id,treeName:G,path:W}):null});return(0,$.jsxs)(vg,{workspaceId:e||c.id,treeName:G,path:W,headerOnly:!0,className:`relative flex flex-col h-full min-h-0`,children:[(0,$.jsx)(jg,{workspaceId:c.id,workspaceName:c.label||c.name},c.id),pt(G,W)&&(0,$.jsx)(Pt,{workspace:c.label||c.name,workspaceIcon:c.icon,tree:G,path:W,onBack:Ge,onBrowseTree:()=>We(`workspaces`,`detail`,e||c.id),onBrowseWorkspaces:()=>Ue(`workspaces`),onNavigatePath:t=>r(Yd(e,t,G)),accentColor:Tn(c.color)}),A&&(0,$.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,$.jsx)(hh,{title:`New canvas`,onClose:()=>j(null),children:(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),qn()},className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,$.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:M,onChange:e=>N(e.target.value),onKeyDown:e=>{e.key===`Escape`&&j(null)},autoFocus:!0})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,$.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:A.parentPath===`/`?`/`:A.parentPath})]})]}),(0,$.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:A.captureView,onChange:e=>j({...A,captureView:e.target.checked})}),(0,$.jsxs)(`span`,{children:[`Capture the current view`,(0,$.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(X,{type:`submit`,disabled:!M.trim()||P,children:P?`Creating…`:`Create canvas`}),(0,$.jsx)(X,{type:`button`,variant:`outline`,onClick:()=>j(null),children:`Cancel`})]})]})})}),(0,$.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,$.jsx)(`div`,{"data-canvas-pane":!0,className:q(`flex-1 min-w-0 bg-background overflow-hidden`,Ie&&(ze===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||Be(`left`)},children:tr}),Ie&&e&&(0,$.jsx)(O_,{workspaceName:e,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,pane:Ie,isFocused:ze===`right`,clipboard:O,setClipboard:k,onFocus:()=>Be(`right`),onSelectionChange:qe,onNavigate:e=>Le(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Le(null),Be(`left`),qe([])}})]})]})}function D_(e,t){if(!e||t===`/`)return e;let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)return null;return n}function O_({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:u}){let{openM1Drawer:d,openM2Drawer:f}=Xh(),{showToast:p,showProgress:m}=Z(),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(0),[C,w]=(0,Q.useState)(1),[T,E]=(0,Q.useState)(50),D=jc(r.treeName),O=D_(h,r.path),k=O?.type===`canvas`,A=(0,Q.useMemo)(()=>D===`directory`?v_(h,r.path):[],[h,r.path,D]),j=r.viewId?Lg(O?.metadata).find(e=>e.id===r.viewId)??null:null,M=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,N=Pg(j),P=(0,Q.useCallback)(async()=>{if(pt(r.treeName,r.path)){v([]),S(0),b(!1);return}let t=x_(e,r.treeName,r.path,C,T,``,N??``),n=y_.get(t);if(n){v(n.documents),S(n.totalCount);return}b(!0);try{let n=await Ks(e,r.path,N?[N]:[],{limit:T,page:C,treeName:r.treeName,treeType:D}),i=n.payload||[],a=n.totalCount||n.count||0;v(i),S(a),y_.set(t,{documents:i,totalCount:a})}catch(e){p({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),v([]),S(0)}finally{b(!1)}},[e,r.path,r.treeName,D,T,C,p,N]);(0,Q.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&Vs(e,r.treeName),Wo(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,g(e))}).catch(()=>{!t&&o===n&&!i&&g(null)})};a(!1);let o=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==r.treeName||a(!n?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{t=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,r.treeName]),(0,Q.useEffect)(()=>{P()},[P]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(w_(e,n),t_(e_(n),{tree:r.treeName,kind:jc(r.treeName),path:r.path})&&(S_(e,r.treeName,r.path),P()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[P,e,r.treeName,r.path]);let ee=(0,Q.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??D,l=i.move??a?.operation===`cut`,u=m({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await vs(e,t,n,s,c);if(r){S_(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=jc(c);await as(e,n,r,[],c,t),S_(e,c,r),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:r,treeName:c}}))}u.done({title:`Success`,description:`${n.length} document(s) ${l?`moved`:`pasted`} to "${t}"`}),o(null),await P(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:s}}))}else u.done();return r}catch(e){return u.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,r.treeName,D,P,m,a,o]),F=(0,Q.useCallback)(()=>{S_(e,r.treeName,r.path),P()},[e,r.treeName,r.path,P]),I=(0,Q.useCallback)(async t=>{let n=m({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await as(e,t,r.path,[],r.treeName,D),F(),n.done({title:`Removed`,description:`${t.length} document(s) removed from "${r.path}"`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,F,m]),te=(0,Q.useCallback)(async t=>{let n=m({title:`Deleting…`,description:`${t.length} document(s)`});try{await jo(e,t,r.path,[],r.treeName,D),F(),n.done({title:`Deleted`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,F,m]),L=(0,Q.useCallback)(async t=>{let n=m({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await Ys(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}F();let i=`${r.successful?.length??0} document(s) destroyed${r.failed?.length?` · ${r.failed.length} failed`:``}.`;r.failed?.length?n.fail({title:`Destroy incomplete`,description:i,variant:`destructive`}):n.done({title:`Destroyed`,description:i})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,F,m]);return(0,$.jsxs)(`div`,{className:q(`relative flex-1 min-w-0 rounded-(--sheet-radius) border bg-background overflow-hidden`,i?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||s()},children:[u&&(0,$.jsx)(`button`,{type:`button`,onClick:u,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),pt(r.treeName,r.path)?r.path===`/Trash`?(0,$.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,$.jsx)(Og,{workspaceName:e})}):(0,$.jsx)(wg,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,$.jsx)(Mg,{frameContent:!1,onBrowseWorkspaces:()=>d(`workspaces`),onBrowseTree:()=>f(`workspaces`,`detail`,e),urlType:k?`canvas`:D===`directory`?r.treeName:`context`,urlDisplay:M,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:N,documents:_,isLoading:y,totalCount:x,currentPage:C,pageSize:T,onPageChange:w,onPageSizeChange:e=>{E(e),w(1)},onRemoveDocument:r.path===`/`?void 0:e=>I([e]),onRemoveDocuments:r.path===`/`?void 0:I,onDeleteDocument:e=>te([e]),onDeleteDocuments:te,onDestroyDocument:e=>L([e]),onDestroyDocuments:L,onCopyDocuments:e=>{o({documentIds:e,operation:`copy`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{o({documentIds:e,operation:`cut`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:r.treeName===`backends`?void 0:ee,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:h,folders:A,onOpenFolder:l,onNavigatePath:l,canvasInfo:k?{label:O?.label,description:O?.description,color:O?.color}:void 0,children:j?.kind===`columns`?(0,$.jsx)(Gg,{documents:_,workspaceId:e,columns:j.columns??[],onColumnsChange:()=>{},readOnly:!0}):j?.kind===`app`&&j.app&&j.app!==`notes`?(0,$.jsx)(Hg,{app:j.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}function k_(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(!e)return;let t=!1,r=()=>{yo(e).then(r=>{t||n({ref:e,workspace:r})}).catch(()=>{})};return r(),window.addEventListener(`workspaces:refresh`,r),()=>{t=!0,window.removeEventListener(`workspaces:refresh`,r)}},[e]),t?.ref===e?t?.workspace:void 0}function A_(){let{workspaceName:e}=wt();return e?(0,$.jsx)(Ag,{workspaceName:e,children:(0,$.jsx)(j_,{})}):(0,$.jsx)(`p`,{role:`alert`,className:`p-6`,children:`Workspace not specified.`})}function j_(){let{workspaceName:e=``,documentId:t=``,algo:n=``,checksum:r=``}=wt(),i=Qt(),a=Bt(),{goBack:o,openM1Drawer:s,openM2Drawer:c}=Xh(),l=k_(e),u=!!n&&!!r,d=u?`${n}/${r}`:t,f=JSON.stringify([e,t,n,r]),p=Number(t),m=/^\d+$/.test(t)&&Number.isSafeInteger(p)&&p>0,h=u||m,[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(null),b=v?.identity===f?v:null,x=h&&(!b||b.revision!==g);(0,Q.useEffect)(()=>{let t=!1;if(h)return(u?fc(e,n,r):rc(e,p)).then(e=>{t||y({identity:f,revision:g,document:e||null,missing:!e,error:``})}).catch(e=>{t||y({identity:f,revision:g,document:null,missing:e?.statusCode===404,error:e instanceof Error?e.message:`Unable to retrieve this document.`})}),()=>{t=!0}},[e,p,f,g,h,u,n,r]);let S={workspace:l?.label||e,workspaceIcon:l?.icon,path:`/`,tree:`context`,document:b?.document?ns(b.document).title:`Document ${d}`,onBack:o,onBrowseWorkspaces:()=>s(`workspaces`),onBrowseTree:()=>c(`workspaces`,`detail`,e),onNavigatePath:t=>i(Yd(e,t,`context`))},C=a.hash.slice(1),w=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`].includes(C)?C:`view`;return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[!b?.document&&(0,$.jsx)(Pt,{...S}),b?.document?(0,$.jsx)(O,{document:b.document,workspaceId:e,onChanged:()=>_(e=>e+1),navigation:S,initialTab:w,onTabChange:e=>i(`${a.pathname}${a.search}#${e}`,{replace:!0}),tabActions:(0,$.jsx)(X,{variant:`ghost`,disabled:x,onClick:()=>_(e=>e+1),children:`Refresh`})},f):x?(0,$.jsx)(`p`,{role:`status`,className:`p-6 text-sm text-muted-foreground`,children:`Loading document…`}):(0,$.jsxs)(`div`,{role:`alert`,className:`space-y-2 p-6 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium`,children:b?.missing?`Document ${d} not found`:`Unable to load document`}),h&&(0,$.jsx)(X,{variant:`outline`,onClick:()=>_(e=>e+1),children:`Retry`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:h?b?.missing?`This record is no longer available in this workspace. Subtree exports skip missing records and report their IDs.`:b?.error:`Document ID must be a positive integer.`})]})]})}function M_(e){let t=new URLSearchParams;return e?.mode===`context`&&t.set(`context`,e.contextId),e?.mode===`workspace`&&(t.set(`workspace`,e.workspaceName),t.set(`path`,e.path),t.set(`tree`,e.treeName)),t}var N_={id:`sketch`,label:`Sketch`,icon:ir,schemas:[ss],canCreate:!0,canEdit:e=>e.schema===ss,createUrl(e){let t=M_(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=M_(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},P_=[{kind:`message`,label:`New Message`,icon:kn},{kind:`note`,label:`Note`,icon:ya},{kind:`link`,label:`Link`,icon:Ji},{kind:`todo`,label:`Todo`,icon:wi},{kind:`identity`,label:`Identity`,icon:Lr},{kind:`sketch`,label:`Sketch`,icon:ir},{kind:`plaintext`,label:`Plaintext file`,icon:Li},{kind:`file`,label:`File`,icon:Wr},{kind:`photo`,label:`Photo/Video`,icon:Rr},{kind:`existing`,label:`Existing document`,icon:ta},{kind:`folder`,label:`Folder`,icon:Xr}];function F_(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?P_:P_.filter(e=>e.kind!==`photo`)}function I_({onSelect:e,variant:t=`list`,omit:n}){let r=F_().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,$.jsx)($.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex items-center gap-2 rounded-full bg-card px-3 py-1.5 text-sm font-medium shadow-elevation-3 transition-transform hover:scale-105`,children:[n,(0,$.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,$.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted`,children:[(0,$.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}function L_(e){if(e.manual){let t=`${e.manual.lat.toFixed(5)}, ${e.manual.lon.toFixed(5)}`;return e.manualLabel?`${e.manualLabel} · ${t}`:`Custom pin · ${t}`}if(!e.supported)return`Needs a secure (https) connection, or pick a point on the map`;if(e.permission===`denied`)return`Blocked. Allow location for this site, or pick a point on the map`;if(e.error)return e.error;if(e.busy)return`Getting your location…`;if(e.enabled&&e.fix){let{lat:t,lon:n,accuracy:r}=e.fix;return`${t.toFixed(5)}, ${n.toFixed(5)}${r==null?``:` · ±${r} m`}`}return e.enabled?`Location will be attached when you save`:`Attach where you are, or pick any point on the map`}function R_({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,Q.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{role:`switch`,"aria-checked":e.enabled,"aria-disabled":i,"aria-label":`Geotag this document`,"aria-describedby":`${t}-hint`,tabIndex:i?-1:0,onClick:()=>!i&&e.setEnabled(!e.enabled),onKeyDown:t=>{i||(t.key===` `||t.key===`Enter`)&&(t.preventDefault(),e.setEnabled(!e.enabled))},className:q(`flex flex-1 items-center justify-between gap-3 select-none outline-none rounded focus-visible:ring-2 focus-visible:ring-ring`,i?`cursor-not-allowed opacity-50`:`cursor-pointer`),children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,$.jsx)(Sa,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,$.jsx)(Ii,{className:q(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,$.jsx)(`div`,{className:q(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,$.jsx)(`div`,{className:q(`absolute top-[2px] h-4 w-4 rounded-full bg-background shadow-elevation-1 transition-transform`,e.enabled?`translate-x-[22px]`:`translate-x-[2px]`)})})]}),(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(!0),title:`Pick a point on the map`,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(da,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.setManual(null),"aria-label":`Remove custom pin`,title:`Remove custom pin`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]})]}),(0,$.jsx)(`p`,{id:`${t}-hint`,className:q(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:L_(e)}),n&&(0,$.jsx)(ye,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}function z_(e){let t=`/workspaces/${encodeURIComponent(e.workspaceName)}`,n=e.path.replace(/^\/+/,``).split(`/`).map(encodeURIComponent).join(`/`);return e.treeName===`context`?`${t}/path/${n}`:`${t}/trees/${encodeURIComponent(e.treeName)}/path/${n}`}function B_({title:e,icon:t,onClose:n,onSave:r,navigateAfterSave:i=!1,canSave:a=!1,saving:o=!1,saveProgress:s,successMessage:c=`Saved`,lockedWorkspaceName:l,fillParent:u=!1,fullWidthContent:d=!1,relationSubjectId:f,frame:p,children:m,maximized:h,onMaximizedChange:g}){let _=Qt(),[v,y]=(0,Q.useState)(`portrait`),[b,x]=(0,Q.useState)(!1),S=h??b,C=e=>{x(e),g?.(e)},[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),A=o||O;ln(()=>T(!1),w&&!A),ln(()=>C(!1),S&&!w);let j=(0,Q.useRef)(null),M=et(),{showSuccessToast:N,showErrorToast:P}=vo(),ee=M&&!u&&!S,[F,I]=(0,Q.useState)(!1),te=!u&&!S&&!p&&!F;(0,Q.useEffect)(()=>{w&&j.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[w]);let L=async(e,t)=>{if(!(!r||A)){k(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>vs(t.workspaceName,e,a,t.treeName,t.treeType))),N(c),n(),i&&_(z_({...t,path:e[0]}),{replace:!0})}catch(e){P(e instanceof Error?e.message:`Failed to save`)}finally{k(!1)}}},ne=async e=>{if(!(!f||!l||e.targetIds.length===0)){D(!0);try{await Sc(l,f,e.predicate,e.targetIds,e.direction),N(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Lt(),T(!1)}catch(e){P(e instanceof Error?e.message:`Failed to create relations`)}finally{D(!1)}}},R=S?w?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:ee?void 0:v===`portrait`?{aspectRatio:`0.707 / 1`,height:`calc(var(--viewport-h) * 0.85)`,width:`auto`,maxWidth:`min(90vw, 100%)`,flexShrink:0}:{aspectRatio:`1 / 0.707`,width:`min(90vw, 900px)`,maxWidth:`100%`,height:`auto`,maxHeight:`calc(var(--viewport-h) * 0.85)`,flexShrink:0},re=!!(f&&l),z=r&&w&&(0,$.jsx)(pe,{onClose:()=>T(!1),onConfirm:L,fixedWorkspaceName:l,saving:A||E,savingContent:s,tabs:re?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:re?ne:void 0,relationWorkspaceName:l,relationExcludeIds:re?new Set([f]):void 0,sizeClassName:p?`h-full max-h-full w-full min-w-0 rounded-none border-0 shadow-none`:u?`h-full max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`:void 0}),ie=(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>y(e=>e===`portrait`?`landscape`:`portrait`),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground max-md:hidden touch-target`,"aria-label":`Toggle orientation`,title:`Toggle orientation`,children:(0,$.jsx)(Bn,{className:`h-4 w-4`})}),r&&(typeof m==`function`?(0,$.jsx)(`button`,{type:`button`,onClick:()=>T(!0),disabled:!a||A,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":A?`Saving…`:`Add relations / Link to…`,title:`Add relations / Link to…`,children:(0,$.jsx)(Pi,{className:`h-4 w-4`})}):(0,$.jsx)(X,{size:`sm`,variant:`outline`,onClick:()=>T(!0),disabled:!a||A,children:A?`Saving…`:`Save / Link to…`})),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p&&!S?p.onToggleExpanded():C(!S),className:q(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`,!S&&!p&&`max-md:hidden`),"aria-label":p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,title:p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,children:S||p?.expanded?(0,$.jsx)(Qr,{className:`h-4 w-4`}):(0,$.jsx)(Qi,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{type:`button`,onClick:n,disabled:A,className:q(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`),"aria-label":`Close`,children:(0,$.jsx)(ur,{className:`h-4 w-4`})})]}),ae=(0,$.jsxs)(`div`,{style:{...p&&!S?{width:`100%`,height:`100%`,minWidth:0}:R,"--document-reading-width":S&&!d?`48rem`:`100%`},onAnimationEnd:e=>{te&&e.target===e.currentTarget&&I(!0)},className:q(`flex flex-col overflow-hidden`,p&&!S?`strip-document-card`:`rounded-(--card-radius) border bg-card shadow-elevation-4 transition-[width,height]`,u&&!S&&!p&&`w-full`,ee&&`fixed inset-2 z-40 shadow-elevation-5`,te&&`animate-card-in`),children:[typeof m!=`function`&&(0,$.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,$.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate`,children:e})]}),ie]}),(0,$.jsx)(Kt.Provider,{value:()=>C(!S),children:(0,$.jsx)(`div`,{className:q(`min-h-0 flex-1 overflow-y-auto`,S&&!d&&typeof m!=`function`&&`mx-auto w-full max-w-3xl`),children:p&&z?z:typeof m==`function`?m(ie):m})})]});return S?(0,Md.createPortal)((0,$.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[ae,z&&(0,$.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:z})]}),document.body):(0,$.jsxs)($.Fragment,{children:[ae,!p&&z&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!A&&T(!1),"aria-hidden":!0}),(0,$.jsx)(`div`,{ref:j,className:`relative shrink-0 md:z-panel md:ml-2 md:pr-2 max-md:fixed max-md:bottom-2 max-md:left-2 max-md:right-2 max-md:top-2 max-md:z-card-overlay max-md:animate-fade-in`,children:z})]})]})}function V_({onClose:e,initialData:t,draftId:n}){let r=Pf(void 0,void 0,`home-card:${n}`);return(0,Q.useEffect)(()=>{t?.title&&r.setTitle(t.title),t?.content&&r.setContent(t.content)},[]),(0,$.jsx)(B_,{title:`New Note`,icon:ya,onClose:e,onSave:async e=>{let t=await r.save({mode:`workspace`,...e});return r.finish(),t},canSave:r.canSave,saving:r.saving,successMessage:`Note created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{htmlFor:`qa-note-title`,children:`Title`}),(0,$.jsx)(J,{id:`qa-note-title`,value:r.title,onChange:e=>r.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,$.jsx)(K,{children:`Body`}),(0,$.jsx)(`div`,{className:`flex-1`,children:(0,$.jsx)(Bc,{kind:`markdown`,value:r.content,onChange:r.setContent,placeholder:`Write your note…`})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{children:`Tags`}),(0,$.jsx)(jt,{tags:r.tags,onChange:r.setTags})]}),(0,$.jsx)(Hc,{...r,onRetry:r.retry}),(0,$.jsx)(R_,{geotag:r.geotag,idPrefix:`qa-note-geotag`})]})})}var H_=`data/schema/tab`,U_=`2.0`;function W_(e){try{return new URL(e),!0}catch{return!1}}function G_(){let[e,t]=(0,Q.useState)(``),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),c=sn(),l=e.trim(),u=W_(l),d=l.length>0&&!u,f=u&&!o;async function p(e){if(!u)throw Error(`Enter a valid URL`);s(!0);try{let t=await c.capture(),r=i.map(e=>e.trim()).filter(Boolean),a={schema:H_,schemaVersion:U_,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:Gc(i),...t?{geo:t}:{}}};return await gl(e,[a])}finally{s(!1)}}return{url:e,setUrl:t,title:n,setTitle:r,tags:i,setTags:a,saving:o,canSave:f,urlValid:u,showUrlError:d,save:p,geotag:c}}function K_({onClose:e,initialData:t}){let n=G_();return(0,Q.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,$.jsx)(B_,{title:`New Link`,icon:Ji,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{htmlFor:`qa-link-url`,children:`URL`}),(0,$.jsx)(J,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{htmlFor:`qa-link-title`,children:`Title`}),(0,$.jsx)(J,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{children:`Tags`}),(0,$.jsx)(jt,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsx)(R_,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function q_({onClose:e,initialData:t}){let n=ft();return(0,Q.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,$.jsx)(B_,{title:`New Todo`,icon:wi,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsx)(Cn,{...n,idPrefix:`qa-todo`}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{children:`Tags`}),(0,$.jsx)(jt,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`qa-todo-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,$.jsx)(R_,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function J_({onClose:e,initialData:t}){let n=Ce();return(0,Q.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,$.jsx)(B_,{title:`New Identity`,icon:Lr,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsx)(ce,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{children:`Tags`}),(0,$.jsx)(jt,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`qa-identity-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]})]})})}var Y_=3;function X_(e){return`${e.name}:${e.size}:${e.lastModified}`}function Z_(e=[]){let[t,n]=(0,Q.useState)(()=>e.map(e=>({id:X_(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(t),o=(0,Q.useRef)(null),s=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,Q.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,Q.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,Q.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(X_(e))).map(e=>({id:X_(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,Q.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,Q.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,Q.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,Q.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await al(e),d=r===`backends`?await fl(n,u):null,f=JSON.stringify([n,r,u]);o.current!==null&&o.current!==f&&c(a.current.map(({id:e,file:t})=>({id:e,file:t,status:`queued`,progress:0}))),o.current=f;let p=new AbortController;s.current=p,i(!0);let m=a.current.filter(e=>e.status!==`done`);for(let e of m)l(e.id,{status:`queued`,progress:0,error:void 0});try{if(d){let e=0;await Promise.all(Array.from({length:Math.min(Y_,m.length)},async()=>{for(;e<m.length&&!p.signal.aborted;){let t=m[e++];try{l(t.id,{status:`uploading`,progress:0,resumed:!1});let e=await _o(n,{...d,key:wl(d.key,t.file.name)},t.file,{signal:p.signal,onProgress:(e,n)=>l(t.id,{progress:n?e/n:0})});l(t.id,{status:`done`,progress:1,docId:e.docId??void 0})}catch(e){l(t.id,{status:`error`,error:e instanceof Error?e.message:`Upload failed`})}}}))}else{let r=new Map;for(let e of m){if(p.signal.aborted)throw new DOMException(`cancelled`,`AbortError`);if(!(e.file.size>=8388608)){l(e.id,{status:`hashing`});try{let t=await Tl(e.file,t=>l(e.id,{progress:t}));r.set(e.id,t),l(e.id,{status:`checking`,progress:0})}catch(t){l(e.id,{status:`error`,error:t instanceof Error?t.message:`Failed to read file`})}}}let i={};if(r.size)try{i=await ho(n,[...new Set(r.values())])}catch{i={}}let a=m.filter(e=>r.has(e.id)||e.file.size>=8388608),o=0;await Promise.all(Array.from({length:Math.min(Y_,a.length)},async()=>{for(;o<a.length;){if(p.signal.aborted)return;let s=a[o++],c=r.get(s.id);try{let r=c?i[c]??null:null;r?l(s.id,{status:`linking`,progress:1,resumed:!0}):(l(s.id,{status:`uploading`,progress:0}),r=await po(n,s.file,{sha256:c,signal:p.signal,onProgress:(e,t)=>l(s.id,{progress:t?e/t:0})}),l(s.id,{status:`linking`,progress:1}));let a=await gl(e,[t(r,s.file)],{refresh:!1});l(s.id,{status:`done`,docId:a[0]})}catch(e){let t=e instanceof DOMException&&e.name===`AbortError`;l(s.id,{status:`error`,error:t?`Cancelled`:e instanceof Error?e.message:`Upload failed`})}}}))}}finally{if(p.signal.aborted)for(let e of a.current)e.status!==`done`&&e.status!==`error`&&l(e.id,{status:`error`,error:`Cancelled`});i(!1),s.current===p&&(s.current=null),a.current.some(e=>e.status===`done`)&&vl(e)}let h=a.current;return{done:h.filter(e=>e.status===`done`).length,resumed:h.filter(e=>e.status===`done`&&e.resumed).length,failed:h.filter(e=>e.status===`error`).length,total:h.length,docIds:h.flatMap(e=>e.status===`done`&&e.docId!=null?[e.docId]:[])}},[l,c]),cancel:p}}function Q_(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function $_(e){switch(e.status){case`hashing`:return`hashing`;case`checking`:return`checking`;case`uploading`:return`${Math.round(e.progress*100)}%`;case`linking`:return`saving`;case`done`:return e.resumed?`already uploaded`:`done`;case`error`:return e.error||`failed`;default:return Q_(e.file.size)}}function ev({item:e}){switch(e.status){case`done`:return(0,$.jsx)($n,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,$.jsx)(Kn,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,$.jsx)(fa,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,$.jsx)(Sa,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function tv({item:e}){if(e.status===`queued`)return null;let t=e.status===`done`||e.status===`error`||e.status===`linking`?1:e.status===`checking`?0:e.progress;return(0,$.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:q(`h-full rounded-full transition-[width] duration-normal`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function nv({items:e,running:t,onRemove:n}){let r=e.filter(e=>e.status===`done`).length,i=e.filter(e=>e.status===`error`).length;return(0,$.jsx)($.Fragment,{children:e.length>0&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(K,{children:[e.length,` file(s)`,r>0&&(0,$.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,$.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,$.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(ev,{item:e}),(0,$.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,$.jsx)(`span`,{className:q(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:$_(e)}),!t&&e.status!==`done`&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(tv,{item:e})]},e.id))})]})})}function rv({items:e,running:t,onCancel:n}){return(0,$.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,$.jsx)(nv,{items:e,running:!0,onRemove:()=>{}}),(0,$.jsx)(X,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function iv(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return So(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var av=`data/schema/file`,ov=`3.0`;function sv(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:iv(e),geotag:sn()}}function cv(e,t,n={}){let r=Gc(n.tags??[]),i=n.comment?.trim();return{schema:av,schemaVersion:ov,data:{},checksumArray:[`sha256/${e.checksum}`],locations:[{url:e.url,metadata:{filename:t.name}}],...i?{comment:i}:{},metadata:{contentType:t.type,size:e.size,...r.length?{features:r}:{},...n.geo?{geo:n.geo}:{}}}}var lv=`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function uv({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{children:`Tags`}),(0,$.jsx)(jt,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(K,{htmlFor:`${t}-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`${t}-comment`,value:e.comment,onChange:t=>e.setComment(t.target.value),rows:3,placeholder:`Optional; searchable, and the only text a photo has`,className:lv}),n&&e.tags.length+e.comment.trim().length>0&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,$.jsx)(R_,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var dv={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,heic:`image/heic`,heif:`image/heif`,bmp:`image/bmp`,tif:`image/tiff`,tiff:`image/tiff`,svg:`image/svg+xml`,mp4:`video/mp4`,mov:`video/quicktime`,webm:`video/webm`,"3gp":`video/3gpp`};function fv(e){return/^(image|video)\//.test(e.type)}async function pv(e){let t=await Promise.all(e.map(async e=>{let t=new Uint8Array(await e.slice(0,64).arrayBuffer()),n=(e,n)=>String.fromCharCode(...t.slice(e,e+n)),r=``;if(t[0]===255&&t[1]===216&&t[2]===255)r=`image/jpeg`;else if(n(0,8)===`PNG\r
|
|
5
5
|
|
|
@@ -9,7 +9,7 @@ import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import
|
|
|
9
9
|
`).trim():``:``}function py(e){if(!e)return;let t=fy(e),n={...e.api?{api:e.api}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.stopReason?{stopReason:e.stopReason}:{},...e.timestamp===void 0?{}:{timestamp:e.timestamp},...e.responseId?{responseId:e.responseId}:{},...e.usage?{usage:e.usage}:{},...e.metadata?.toolCalls?{toolCalls:e.metadata.toolCalls}:{},...t?{reasoning:t}:{}};return Object.keys(n).length>0?n:void 0}function my(e){if(typeof e==`number`)return new Date(e).toISOString();if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}return new Date().toISOString()}function hy(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:dy(e),timestamp:my(e.timestamp),...e.role===`assistant`?{metadata:py(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function gy(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:hy(e?.messages||[])}}function _y(e){return{current:gy(e?.current),sessions:e?.sessions}}new class{connectors=new Map;wsService=null;messageCallbacks=new Map;constructor(){this.initializeWebSocketFallback()}async initializeWebSocketFallback(){try{let e=`${window.location.protocol===`https:`?`wss:`:`ws:`}//${window.location.host}/ws`;this.wsService=new uy(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new ly(e.apiKey||``,e.endpoint||`${lo}/agents/${e.id}`);this.connectors.set(e.id,t)}}async sendMessage(e,t,n={}){let{onMessage:r,onError:i,onComplete:a,useWebSocketFallback:o=!1}=n,s=`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;r&&this.messageCallbacks.set(s,r);try{if(o&&this.wsService){await this.sendMessageViaWebSocket(e,s,t,r,i),a&&a();return}let n=this.connectors.get(e);n?await n.chatStream(t,{agentId:e,messageId:s,onMessage:e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},onError:n=>{if(console.error(`Agent connector error:`,n),n.message.includes(`getReader is not a function`)&&this.wsService){console.log(`Falling back to WebSocket streaming...`),this.sendMessageViaWebSocket(e,s,t,r,i);return}i&&i(n)},onComplete:a}):await this.sendMessageViaAPI(e,s,t,r,i,a)}catch(e){console.error(`Agent communication error:`,e),i&&i(e instanceof Error?e:Error(String(e)))}finally{this.messageCallbacks.delete(s)}}async sendMessageViaAPI(e,t,n,r,i,a){try{await Y.stream(`${lo}/agents/${e}/chat/stream`,{message:n,messageId:t},{onChunk:n=>{try{let i=JSON.parse(n),a={id:t,agentId:e,content:i.content||n,timestamp:new Date,type:`agent`,streaming:!i.done,error:i.error};r&&r(a)}catch{r&&r({id:t,agentId:e,content:n,timestamp:new Date,type:`agent`,streaming:!0})}},onError:e=>{console.error(`API streaming error:`,e),i&&i(e)},onComplete:a})}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async sendMessageViaWebSocket(e,t,n,r,i){if(!this.wsService){i&&i(Error(`WebSocket service not available`));return}try{this.wsService.socket?.readyState!==WebSocket.OPEN&&await this.wsService.connect(),this.wsService.startChatStream(e,t,n,e=>{let t={id:e.messageId,agentId:e.agentId,content:e.content||``,timestamp:new Date,type:`agent`,streaming:!e.done,error:e.error};r&&r(t)},i)}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}async getAvailableAgents(){try{return(await Y.get(`${lo}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await Y.post(`${lo}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function vy(e){return await Y.get(`${lo}/agents/${e}/access`)||null}async function yy(e,t){return await Y.put(`${lo}/agents/${e}/access`,t)}async function by(e){return await Y.post(`${lo}/agents/${e}/access/token`)}async function xy(e){await Y.delete(`${lo}/agents/${e}/access`)}async function Sy(e){return await Y.get(`${lo}/agents/${e}/tools`)||{tools:[],config:{}}}async function Cy(){try{return await Y.get(`${lo}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function wy(e){return await Y.get(`${lo}/agents/${e}`)}async function Ty(e){return gy(await Y.get(`${lo}/agents/${e}/session`))}async function Ey(e){return await Y.get(`${lo}/agents/${e}/sessions`)}async function Dy(e,t){return _y(await Y.post(`${lo}/agents/${e}/sessions`,t))}async function Oy(e,t){return _y(await Y.put(`${lo}/agents/${e}/session`,t))}async function ky(e,t,n){return _y(await Y.patch(`${lo}/agents/${e}/sessions/${t}`,n))}async function Ay(e,t){return _y(await Y.delete(`${lo}/agents/${e}/sessions/${t}`))}async function jy(e){return await Y.get(`${lo}/agents/${e}/skills`)||[]}async function My(e,t){return await Y.post(`${lo}/agents/${e}/skills`,t)||[]}async function Ny(e,t){return await Y.delete(`${lo}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function Py(e){return await Y.post(`${lo}/agents`,e)}async function Fy(e,t){return await Y.put(`${lo}/agents/${e}`,t)}async function Iy(e){await Y.delete(`${lo}/agents/${e}`)}async function Ly(e){return await Y.post(`${lo}/agents/${e}/start`)}async function Ry(e){return await Y.post(`${lo}/agents/${e}/stop`)}async function zy(e){return await Y.get(`${lo}/agents/${e}/status`)}async function By(e,t,n={}){let{onStart:r,onMessage:i,onError:a,onComplete:o,context:s,mcpContext:c,maxTokens:l,temperature:u,images:d}=n,f=``;await Y.stream(`${lo}/agents/${e}/prompt/stream`,{message:t,images:d,context:s,mcpContext:c,maxTokens:l,temperature:u},{onOpen:()=>{r?.()},onChunk:e=>{f+=e;let t=f.split(`
|
|
10
10
|
|
|
11
11
|
`);f=t.pop()||``;for(let e of t){let t=e.split(`
|
|
12
|
-
`).map(e=>e.trim()).filter(Boolean);for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t!==`[DONE]`)try{let e=JSON.parse(t);if(!i)continue;if(e.type===`chunk`)i(e.delta||``,!1,e.metadata||{});else if(e.type===`thinking`)i(``,!1,{...e.metadata||{},reasoningDelta:e.delta||``});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null;i(``,!0,{...e.metadata||{},...py(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function Vy(e,t){let{message:n,onMessage:r,onError:i,onComplete:a,context:o,mcpContext:s,maxTokens:c,temperature:l,images:u}=t;try{let t=await Y.post(`${lo}/agents/${e}/prompt`,{message:n,images:u,context:o,mcpContext:s,maxTokens:c,temperature:l}),i=Array.isArray(t.messages)?[...t.messages].reverse().find(e=>e?.role===`assistant`):null,d={content:dy(i),metadata:py(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function Hy(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function Uy(){return await Y.get(`${lo}/voice/status`)}async function Wy(e,t,n={}){let r=new FormData,i=(t.type.split(`/`)[1]||`webm`).split(`;`)[0];r.append(`file`,t,`voice.${i}`);let a=new URLSearchParams;n.tts===!1&&a.set(`tts`,`false`),n.voice&&a.set(`voice`,n.voice);let o=a.toString()?`?${a.toString()}`:``;return await Y.post(`${lo}/agents/${e}/voice${o}`,r)}var Gy=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:ty,load:async()=>(await rs()).map(e=>({id:e.name,label:e.label||e.name}))},{id:`context`,label:`Context`,path:`contexts`,description:`Choose the tree and path a context opens, and who can access that view. File storage belongs to its workspace.`,sections:iy,load:async()=>(await ol()).map(e=>({id:e.id,label:e.name||e.id}))},{id:`agent`,label:`Agent`,path:`agents`,description:`Configure one assistant: its instructions, chat model, tools and access to Canvas.`,sections:oy,load:async()=>(await Cy()).map(e=>({id:e.id,label:e.label||e.name}))}];function Ky({to:e,label:t,description:n,icon:r}){return(0,$.jsxs)(Le,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,$.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,$.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,$.jsx)(fi,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function qy({group:e,query:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(`loading`),[c,l]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>Dh(t,e.label,n.label,n.description));return u.length?(0,$.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,$.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,$.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,$.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,$.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,$.jsx)(Ky,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function Jy(){let{state:e}=Xh(),[t,n]=(0,Q.useState)(``),r=Th.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>Dh(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Gy.some(e=>e.sections.some(n=>Dh(t,e.label,n.label,n.description)));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,$.jsx)(lh,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,$.jsx)(J,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Ky,{to:e.path,...e},e.path))})]},e.id)),Gy.map(e=>(0,$.jsx)(qy,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Ky,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Yy=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],Xy=`/wallpapers`;function Zy(e){return Yy.find(t=>t.id===e)}function Qy(e,t={}){let n=typeof e==`string`?Zy(e):e;if(!n)return null;let{base:r=Xy,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function $y(e,t=Xy){let n=typeof e==`string`?Zy(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var eb=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],tb=`canvas:wallpaper`,nb=`canvas-wallpaper`,rb=`settings`,ib=`builtin:`,ab=Yy;function ob(e){return $y(e)??``}function sb(e){return`${ib}${e}`}function cb(e){return e?.startsWith(ib)?e.slice(8):null}function lb(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function ub(){try{let e=localStorage.getItem(tb);if(e){let t=lb(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var db=ub(),fb=null;function pb(){return db}async function mb(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(nb,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(rb),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(rb,e?`readwrite`:`readonly`),a=i.objectStore(rb),o=e?a.put(e,tb):a.get(tb);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function hb(){try{localStorage.removeItem(tb)}catch{}}function gb(){return fb||=(async()=>{try{let e=lb(await mb());e?db=e:await mb(db),hb()}catch{}return wb(db),db})(),fb.then(()=>db)}async function _b(e){await gb(),await mb(e),db=e,hb(),wb(e)}function vb(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var yb=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function bb(e){if(!e)return null;let t=cb(e);if(t===null)return`url("${e}")`;let n=Zy(t);if(!n)return null;let r=`url("${Qy(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!yb||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Qy(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function xb(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var Sb=null;function Cb(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function wb(e=pb()){let t=document.documentElement.style,n=Sb,r=e.image;if(r?.startsWith(`data:`))try{Sb?.dataUrl!==r&&(Sb={dataUrl:r,objectUrl:URL.createObjectURL(Cb(r))}),r=Sb.objectUrl}catch{Sb=null,r=null}else Sb=null;let i=bb(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,xb(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==Sb&&URL.revokeObjectURL(n.objectUrl)}var Tb=[{id:`cards`,name:`Cards`,description:`Nested cards with connector lines. Each level indents.`},{id:`accordion-mobile`,name:`Accordion on phones (beta)`,description:`Experimental. Full-width accordion rows on a phone, cards on wider screens.`},{id:`accordion`,name:`Accordion (beta)`,description:`Experimental. Full-width rows at every depth; a depth rail, tint and colour swatch replace the indent, and open parents stick to the top while you scroll.`}],Eb=`canvas:treeStyle`;function Db(){try{let e=localStorage.getItem(Eb);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var Ob=Db(),kb=new Set;function Ab(){return Ob}function jb(e){try{e===`cards`?localStorage.removeItem(Eb):localStorage.setItem(Eb,e)}catch{}Ob=e;for(let e of kb)e()}function Mb(e){kb.add(e);let t=t=>{(t.key===Eb||t.key===null)&&(Ob=Db(),e())};return window.addEventListener(`storage`,t),()=>{kb.delete(e),window.removeEventListener(`storage`,t)}}function Nb(){return(0,Q.useSyncExternalStore)(Mb,Ab,()=>`cards`)}function Pb(){let e=Nb(),t=et();return e===`accordion`||e===`accordion-mobile`&&t}var Fb=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],Ib=Fb.map(e=>e.id),Lb=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],Rb=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],zb={theme:`canvas`,scheme:`light`,density:`auto`},Bb=`canvas.ui.theme`;function Vb(e){return typeof e==`string`&&Ib.includes(e)}function Hb(e){return e===`light`||e===`dark`||e===`system`}function Ub(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function Wb(e){let t=typeof e==`object`&&e?e:{};return{theme:Vb(t.theme)?t.theme:zb.theme,scheme:Hb(t.scheme)?t.scheme:zb.scheme,density:Ub(t.density)?t.density:zb.density}}var Gb=`(prefers-color-scheme: dark)`;function Kb(){return typeof document<`u`}function qb(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(Gb).matches}function Jb(e){return e===`system`?qb()?`dark`:`light`:e}function Yb(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(Gb),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function Xb(e){return Yb(e)}function Zb(){return qb()?`dark`:`light`}function Qb(){return`light`}function $b(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function ex(e,t=Kb()?document.documentElement:void 0){let n=Jb(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,$b(t),n):n}function tx(e,t=Kb()?document.documentElement:void 0){if(!t||typeof window>`u`)return ex(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=ex(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function nx(e){let t=e??ax();if(!t)return zb;try{let e=t.getItem(Bb);return e?Wb(JSON.parse(e)):zb}catch{return zb}}function rx(e,t){let n=t??ax();if(n)try{n.setItem(Bb,JSON.stringify(e))}catch{}}function ix(e){let t=e??ax();if(t)try{t.removeItem(Bb)}catch{}}function ax(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function ox({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Q.useState)(()=>({...nx(n),...t})),o=(0,Q.useSyncExternalStore)(Xb,Zb,Qb),s=i.scheme===`system`?o:i.scheme;(0,Q.useEffect)(()=>{tx({...i,scheme:s})},[i,s]),(0,Q.useEffect)(()=>{r&&rx(i,n)},[i,r,n]);let c=(0,Q.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Q.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Q.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Q.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?Zb():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Q.useCallback)(()=>{ix(n),a(zb)},[n]),p=(0,Q.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,$.jsx)(El.Provider,{value:p,children:e})}var sx={system:la,light:xi,dark:lr};function cx(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Dl(),c=ht(),l=Lh(),u=Nb(),d=Kh();return(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,$.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:Fb.map(t=>{let n=t.id===e;return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:q(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,$.jsx)($n,{className:`size-4 shrink-0 text-primary`})]}),(0,$.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,$.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,$.jsx)(px,{options:Lb.map(e=>{let t=sx[e.id];return{id:e.id,label:e.name,icon:(0,$.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,$.jsx)(px,{options:Rb.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Rb.find(e=>e.id===n)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,$.jsx)(px,{options:Oh.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:Fh}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Oh.find(e=>e.id===l)?.description}),l===`strip`&&(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,$.jsx)(px,{options:Rh.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:Wh}),(0,$.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[Rh.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,$.jsx)(px,{options:Tb.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:jb}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Tb.find(e=>e.id===u)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,$.jsx)(px,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:lt}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,$.jsx)(lx,{}),(0,$.jsx)(`section`,{children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s(),lt(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function lx(){let[e,t]=(0,Q.useState)(pb),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=!1;return gb().then(()=>{e||(t(pb()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await vb(n)}:e;await _b(i),t(i),r(null)}catch(e){r(e instanceof Error&&e.name!==`QuotaExceededError`?e.message:`Could not store the wallpaper. Free some browser storage or try a smaller image.`)}finally{c.current=!1,s(!1)}}},u=t=>{t&&l(e,t)},d=e.image!==null&&cb(e.image)===null,f=bb(e.image);return(0,$.jsx)(`section`,{children:(0,$.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,$.jsx)(fx,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,$.jsx)(dx,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,$.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),ab.map(t=>(0,$.jsx)(dx,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:cb(e.image)===t.id,onSelect:()=>l({...e,image:sb(t.id)}),children:(0,$.jsx)(`img`,{src:ob(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,$.jsx)(dx,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,$.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,$.jsx)(ux,{}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:xb(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,$.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>l({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,$.jsx)(px,{options:eb.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function ux(){let e=ab.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function dx({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:q(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,$.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,$.jsx)($n,{className:`size-3`})})]})}function fx({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function px({options:e,value:t,onChange:n}){return(0,$.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:q(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function mx(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`Appearance`,onBack:Gv(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,$.jsx)(cx,{})]})}var hx={previousTree:`Alt+Q`,nextTree:`Alt+W`},gx=`canvas:key-bindings`,_x=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function vx(){try{let e=JSON.parse(localStorage.getItem(gx)||`{}`),t={...hx};for(let n of Object.keys(t))(e[n]===``||_x.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...hx}:t}catch{return{...hx}}}function yx(e){localStorage.setItem(gx,JSON.stringify(e))}function bx(e){return/^Key[A-Z]$/.test(e.code)?[e.ctrlKey&&`Ctrl`,e.altKey&&`Alt`,e.metaKey&&`Meta`,e.shiftKey&&`Shift`,e.code.slice(3)].filter(Boolean).join(`+`):``}function xx(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function Sx(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Cx(){let[e,t]=(0,Q.useState)(vx),[n,r]=(0,Q.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{yx(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`Key bindings`,onBack:Gv(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,$.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,$.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||hx[t].slice(-1)}`:``}),children:[(0,$.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]}),(0,$.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||hx[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,$.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...hx}),children:`Restore defaults`}),(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var wx=`offline-content-v1`,Tx=`offline-api-v1`,Ex=1073741824,Dx={enabled:!1,budgetBytes:4*Ex,excludedWorkspaces:[]},Ox=1e3;function kx(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function Ax(e,t,n){return`${e}:${t}:${kx(n)}`}var jx=`canvas-offline`,Mx=2,Nx=null;function Px(){return Nx||(Nx=new Promise((e,t)=>{let n=indexedDB.open(jx,Mx);n.onupgradeneeded=e=>{let t=n.result;if(t.objectStoreNames.contains(`config`)||t.createObjectStore(`config`),t.objectStoreNames.contains(`entries`)||t.createObjectStore(`entries`,{keyPath:`url`}),e.oldVersion>=1&&t.objectStoreNames.contains(`pins`)){t.deleteObjectStore(`pins`);let e=n.transaction.objectStore(`entries`).openCursor();e.onsuccess=()=>{let t=e.result;if(!t)return;let n=t.value;n.pinned&&t.update({...n,pinned:!1}),t.continue()}}t.objectStoreNames.contains(`scopes`)||t.createObjectStore(`scopes`,{keyPath:`id`})},n.onsuccess=()=>{n.result.onversionchange=()=>{n.result.close(),Nx=null},e(n.result)},n.onerror=()=>{Nx=null,t(n.error)}}),Nx)}function Fx(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function Ix(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function Lx(e,t){return Ix((await Px()).transaction(e).objectStore(e).get(t))}async function Rx(e){return Ix((await Px()).transaction(e).objectStore(e).getAll())}async function zx(e,t,n){let r=(await Px()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),Fx(r)}async function Bx(e,t){let n=(await Px()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),Fx(n)}async function Vx(e){let t=(await Px()).transaction(e,`readwrite`);return t.objectStore(e).clear(),Fx(t)}async function Hx(){try{let e=await Lx(`config`,`settings`);return e?{...Dx,...e}:Dx}catch{return Dx}}async function Ux(e){await zx(`config`,e,`settings`)}async function Wx(e,t){let n=(await Px()).transaction(`entries`,`readwrite`),r=n.objectStore(`entries`);for(let n of e){let e=r.get(n);e.onsuccess=()=>{let i=e.result;i?r.put({...i,pinned:t}):t&&r.put({url:n,kind:`content`,size:0,lastAccess:Date.now(),pinned:t})}}return Fx(n)}async function Gx(e){let t=await Rx(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-Ox)),i=t.filter(e=>e.kind===`content`),a=i.reduce((e,t)=>e+t.size,0),o=i.filter(e=>!e.pinned).sort((e,t)=>e.lastAccess-t.lastAccess),s=[];for(let t of o){if(a<=e)break;s.push(t),a-=t.size}if(!r.length&&!s.length)return;let[c,l]=await Promise.all([caches.open(Tx),caches.open(wx)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await Bx(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await Bx(`entries`,e.url)})])}async function Kx(){let e=await Rx(`entries`),t=e.filter(e=>e.kind===`content`);return{contentBytes:t.reduce((e,t)=>e+t.size,0),contentCount:t.length,pinnedBytes:t.filter(e=>e.pinned).reduce((e,t)=>e+t.size,0),apiCount:e.length-t.length}}async function qx(){await Promise.all([caches.delete(wx),caches.delete(Tx)]),await Vx(`entries`),await Vx(`scopes`)}async function Jx(){return Rx(`scopes`)}async function Yx(e){return Lx(`scopes`,e)}async function Xx(e){await zx(`scopes`,e)}async function Zx(e){let t=await Lx(`scopes`,e);await Bx(`scopes`,e),t?.urls.length&&await Qx(t.urls)}async function Qx(e){let t=await Rx(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await Wx(r,!1)}var $x=3,eS=`data/schema/file`,tS=128;async function nS({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await Hx();if(!a.enabled)throw Error(`Enable the offline cache first`);if(a.excludedWorkspaces.includes(e))throw Error(`Workspace "${e}" is excluded from offline caching`);let o=Ax(e,n,t),s=kx(t),c=await Yx(o),l=((await Ks(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===eS),u=[],d=0,f=0,p=!1,m=l.length;i?.({done:f,total:m,bytes:d});let h=0;await Promise.all(Array.from({length:Math.min($x,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Nc(e,t.id);d+=n.size,u.push(`${qa.workspaces}/${e}/documents/${t.id}/content`);try{await Co(e,t.id,tS),u.push(`${qa.workspaces}/${e}/documents/${t.id}/thumbnail?size=${tS}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await Wx(u,!0);let g={id:o,workspaceRef:e,treeName:n,treeType:r,path:s,urls:u,bytes:d,warmedAt:Date.now(),...p?{truncated:!0}:{}};if(await Xx(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await Qx(t)}return g}var rS=[{label:`1 GB`,bytes:1*Ex},{label:`2 GB`,bytes:2*Ex},{label:`4 GB`,bytes:4*Ex},{label:`8 GB`,bytes:8*Ex}];function iS(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/Ex).toFixed(2)} GB`}function aS(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function oS(){let{showSuccessToast:e,showErrorToast:t}=vo(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)({}),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useCallback)(()=>{Hx().then(r).catch(()=>{}),Kx().then(a).catch(()=>{}),Jx().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,Q.useEffect)(()=>{v(),rs().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await Ux(e),aS(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),Gx(e.budgetBytes).then(v).catch(()=>{})},b=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];y({...n,excludedWorkspaces:t})},x=async()=>{h(!0);try{await qx(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},S=async n=>{let r=Ax(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await nS(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${iS(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${iS(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},C=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},w=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),T=async e=>{await Zx(e),v()};return n?(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(sS,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:q(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,$.jsx)(Ba,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,$.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,$.jsx)($n,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:rS.map(e=>(0,$.jsx)(X,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,$.jsxs)(`span`,{children:[iS(i.contentBytes),` of `,iS(n.budgetBytes),` used`]}),(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${iS(i.pinnedBytes)} pinned`:``]})]}),(0,$.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,$.jsx)(`div`,{children:(0,$.jsxs)(X,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,$.jsx)(Sa,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(Kr,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(sS,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,$.jsx)(`div`,{className:`mb-3`,children:(0,$.jsxs)(X,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,$.jsx)(wr,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,$.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,$.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Sa,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${iS(t.bytes)}`:`listing…`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[iS(e.bytes),e.truncated?` (partial)`:``]}),(0,$.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>S(w(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,$.jsx)(Un,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>T(e.id),"aria-label":`Unpin ${e.id}`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,$.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(sS,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,$.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(`span`,{className:q(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,$.jsx)(ua,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,$.jsx)(X,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,$.jsx)(zt,{onClose:()=>_(!1),children:(0,$.jsx)(pe,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:C,onClose:()=>_(!1)})})]}):null}function sS({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function cS(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`Offline`,onBack:Gv(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,$.jsx)(oS,{})]})}function lS(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function uS({name:e,version:t,detail:n}){return(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,$.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function dS(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!0;return Y.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&r(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let i=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${lS(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`About`,onBack:Gv(),description:`Versions of every Canvas component this installation is running.`}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,$.jsx)(uS,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.7`}),e?.version&&(0,$.jsx)(uS,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,$.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,$.jsx)(uS,{name:e,version:`v${t}`},e))})]}),n&&(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,$.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var fS=[`onnx`,`clip`,`blip`,`openai`],pS=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],mS=[{id:`openai`,baseUrl:`https://api.openai.com/v1`,label:`OpenAI`},{id:`vllm`,baseUrl:`http://127.0.0.1:8000/v1`,label:`vLLM`},{id:`ollama`,baseUrl:`http://127.0.0.1:11434/v1`,label:`Ollama`}],hS=e=>`${qa.workspaces}/${encodeURIComponent(e)}/inferd`;function gS(e,t){let n={};for(let[r,i]of Object.entries(e.providers||{})){let e={...i};delete e.apiKeySet,delete e.headerNames,t.has(r)&&i.apiKey?e.apiKey=i.apiKey:delete e.apiKey,n[r]=e}return{...e,providers:n}}async function _S(e){return await Y.get(`${hS(e)}/status`)}async function vS(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await Y.post(`${hS(e)}/summarize/images`,n)}async function yS(e){return await Y.post(`${hS(e)}/summarize/images/stop`,{})}async function bS(e){return await Y.get(`${hS(e)}/config`)}async function xS(e,t){return await Y.put(`${hS(e)}/config`,t)}async function SS(e,t={}){let n={};return t.space&&(n.space=t.space),t.reindex!==void 0&&(n.reindex=t.reindex),t.scope&&(n.scope=t.scope),await Y.post(`${hS(e)}/reindex`,n)}async function CS(e){return await Y.get(`${hS(e)}/vector-tables`)}async function wS(e,t){return await Y.delete(`${hS(e)}/vector-tables/${encodeURIComponent(t)}`)}async function TS(){return await Y.get(`${qa.inferd}/config`)}async function ES(e){return await Y.put(`${qa.inferd}/config`,e)}async function DS(){return await Y.get(`${qa.inferd}/defaults`)}async function OS(e){return await Y.put(`${qa.inferd}/defaults`,e)}async function kS(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await Y.post(`${qa.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function AS(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await Y.post(`${qa.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var jS=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,MS=`font-semibold uppercase tracking-[0.08em]`,NS={openai:{url:{key:`baseUrl`,label:`Base URL`,placeholder:`http://gpu.local:8000/v1`,hint:`OpenAI-compatible embeddings endpoint — Ollama, vLLM, TEI, infinity, LM Studio and OpenAI itself all speak this. A trailing /v1 is optional; both http://host:8000 and http://host:8000/v1 work.`},apiKey:"Sent as `Authorization: Bearer …`. Leave empty for servers that do not check it.",imageInput:!0,timeoutMs:!0,headers:!0,where:e=>e.baseUrl||`no endpoint set`},ollama:{url:{key:`host`,label:`Host (legacy)`,placeholder:`http://127.0.0.1:11434`,hint:`Written by an older version. Switch the type to openai — the host becomes the base URL and the /v1 suffix is added for you.`},apiKey:"Sent as `Authorization: Bearer …`.",where:e=>e.host||`http://127.0.0.1:11434`},onnx:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`},clip:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`}},PS=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],FS=[{value:`data-uri`,label:`data-uri (default)`,hint:"Images ride in the ordinary `input` array as data URIs (infinity, TEI-style servers)."},{value:`messages`,label:`messages`,hint:`vLLM's multimodal shape: one request per image, wrapped in a chat message.`}],IS=12e4;function LS(e){if(typeof e!=`string`||e.trim()===``)return null;let t;try{t=new URL(e.trim())}catch{return`Must be an absolute URL including the scheme, e.g. http://127.0.0.1:11434`}return t.protocol!==`http:`&&t.protocol!==`https:`?`Unsupported scheme '${t.protocol.replace(`:`,``)}'. Use http or https.`:null}function RS({title:e,hint:t}){return(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`h3`,{className:q(`text-[11px] text-muted-foreground`,MS),children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function zS({overridden:e,source:t}){return e?(0,$.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function BS({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,$.jsx)(zS,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,$.jsx)(J,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:q(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,$.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function VS({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,$.jsx)(zS,{overridden:n})]})}function HS({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,Q.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,$.jsx)(zS,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,$.jsxs)($.Fragment,{children:[`Stored: `,(0,$.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(J,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,$.jsx)(J,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,$.jsx)(Bi,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function US({open:e,onClick:t,label:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,$.jsx)(Hr,{className:q(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var WS={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function GS({value:e,effective:t,inherited:n,resolvedSpaces:r,invalid:i,attention:a,onFill:o,saving:s=!1,disabled:c=!1,saveLabel:l=`Save`,onSave:u}){let{showToast:d}=Z(),[f,p]=(0,Q.useState)(()=>structuredClone(e)),[m,h]=(0,Q.useState)(new Set),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?NS[i.type]?.url?.key:void 0,o=a?LS(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await kS(i,r)===!1&&(y(!0),d({title:`Downloading model`,description:`'${r??`the configured model`}' is not in the server's cache yet; downloading now. A first test can take a few minutes; the model is then cached for good.`}))}catch{}let n=await AS(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,Q.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?NS[i]?.url?.key:void 0;if(!a)continue;let o=LS(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,Q.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),L=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(gS(f,m)),h(new Set)},ne=e=>T(t=>t===e?null:e);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,$.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,$.jsx)(nr,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,$.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(RS,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,$.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`span`,{className:q(`absolute inset-y-0 left-0 w-[3px]`,WS[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:q(`text-[11px]`,MS),children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,$.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,$.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,$.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,$.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,$.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,$.jsx)(tr,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,$.jsx)(US,{open:m,onClick:()=>ne(p),label:`Edit ${e}`})]})]}),m&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,$.jsx)(zS,{overridden:s.provider!==void 0,source:u.provider})]}),(0,$.jsxs)(`select`,{className:jS,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]})]}),(0,$.jsx)(BS,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,$.jsx)(BS,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,$.jsx)(BS,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,$.jsx)(VS,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,$.jsx)(VS,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(J,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,$.jsx)(Bi,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(RS,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=pS.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?NS[l]:void 0,d=u?.url?LS(n[u.url.key]):null,p={...r,...n},h=PS.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,$.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(US,{open:s,onClick:()=>ne(o),label:`Edit ${e}`})]})]}),s&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,$.jsx)(zS,{overridden:n.type!==void 0,source:r.type})]}),(0,$.jsxs)(`select`,{className:jS,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),fS.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),l&&!fS.includes(l)&&(0,$.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,$.jsx)(BS,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,$.jsx)(BS,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,$.jsx)(zS,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,$.jsxs)(`select`,{className:jS,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),FS.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:FS.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,$.jsx)(BS,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??IS,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,$.jsx)(J,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,$.jsx)(HS,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[`Not used by type `,(0,$.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,$.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,$.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,$.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(J,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,$.jsx)(Bi,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),mS.filter(e=>!D.includes(e.id)).map(e=>(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,$.jsx)(X,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:L,disabled:s||!te||I.length>0,children:s?`Saving…`:l}),(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,$.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function KS(){let{showToast:e}=Z(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=(0,Q.useCallback)(()=>TS().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,Q.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,$.jsx)(lh,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:Gv(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,$.jsx)(Un,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(Un,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,$.jsx)(GS,{value:t.user||{},effective:t.effective||{},inherited:t.serverDefaults||{},invalid:t.invalid,saving:a,saveLabel:`Save defaults`,onSave:async t=>{o(!0);try{let n=await ES(t);e({title:`Defaults saved`,description:n.restartRequired?`${n.workspaces.length} running workspace(s) keep their current tables until restarted. Set the config on a workspace directly to change it live.`:`New workspaces will inherit this.`}),await l()}catch(t){e({title:`Save failed`,description:t instanceof Error?t.message:`Failed to save`,variant:`destructive`})}finally{o(!1)}}},JSON.stringify(t.user))]})}function qS(){let e=Bt(),{showToast:t}=Z(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,Q.useState)(i),[c,l]=(0,Q.useState)(a),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),g=(0,Q.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await Y.get(e,{skipAuth:!0,headers:_()});d(t);let n=await Y.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,Q.useRef)(v);return(0,Q.useEffect)(()=>{y.current()},[]),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(lh,{onBack:Gv(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(J,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,$.jsx)(J,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,$.jsx)(X,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,$.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,$.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,$.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,$.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,$.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,$.jsx)(Yl,{className:`mt-8`})]})}function JS(e={}){let t=new URLSearchParams;e.tail&&t.set(`tail`,String(e.tail)),e.level&&t.set(`level`,e.level),e.module&&t.set(`module`,e.module);let n=t.toString();return n?`?${n}`:``}function YS(){let e=localStorage.getItem(`authToken`);if(!e)throw Error(`Authentication required`);let t=localStorage.getItem(`appName`)||window.location.hostname;return{Authorization:`Bearer ${e}`,"X-App-Name":t,Accept:`text/event-stream`}}var XS={users:{async listUsers(e){let t=new URLSearchParams;e?.status&&t.append(`status`,e.status),e?.userType&&t.append(`userType`,e.userType);let n=t.toString(),r=n?`${qa.admin.users}?${n}`:qa.admin.users;return await Y.get(r)},async getUser(e){return await Y.get(`${qa.admin.users}/${e}`)},async createUser(e){return await Y.post(qa.admin.users,e)},async updateUser(e,t){return await Y.put(`${qa.admin.users}/${e}`,t)},async deleteUser(e){await Y.delete(`${qa.admin.users}/${e}`)}},workspaces:{async listAllWorkspaces(){return await Y.get(qa.admin.workspaces)},async createWorkspace(e){return await Y.post(qa.admin.workspaces,e)},async deleteWorkspace(e){await Y.delete(`${qa.admin.workspaces}/${e}`)}},logs:{async getLogs(e={}){return(await Y.get(`${qa.admin.logs}${JS(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${qa.admin.logsStream}${JS(e)}`,{method:`GET`,headers:YS(),credentials:`include`,signal:n});if(!t.ok)throw Error(`Failed to open log stream (${t.status})`);if(!t.body)throw Error(`Streaming is not supported by this browser`);let i=t.body.getReader(),a=new TextDecoder,o=``,s=e=>{let t=e.split(`
|
|
12
|
+
`).map(e=>e.trim()).filter(Boolean);for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t!==`[DONE]`)try{let e=JSON.parse(t);if(!i)continue;if(e.type===`chunk`)i(e.delta||``,!1,e.metadata||{});else if(e.type===`thinking`)i(``,!1,{...e.metadata||{},reasoningDelta:e.delta||``});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null;i(``,!0,{...e.metadata||{},...py(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function Vy(e,t){let{message:n,onMessage:r,onError:i,onComplete:a,context:o,mcpContext:s,maxTokens:c,temperature:l,images:u}=t;try{let t=await Y.post(`${lo}/agents/${e}/prompt`,{message:n,images:u,context:o,mcpContext:s,maxTokens:c,temperature:l}),i=Array.isArray(t.messages)?[...t.messages].reverse().find(e=>e?.role===`assistant`):null,d={content:dy(i),metadata:py(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function Hy(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function Uy(){return await Y.get(`${lo}/voice/status`)}async function Wy(e,t,n={}){let r=new FormData,i=(t.type.split(`/`)[1]||`webm`).split(`;`)[0];r.append(`file`,t,`voice.${i}`);let a=new URLSearchParams;n.tts===!1&&a.set(`tts`,`false`),n.voice&&a.set(`voice`,n.voice);let o=a.toString()?`?${a.toString()}`:``;return await Y.post(`${lo}/agents/${e}/voice${o}`,r)}var Gy=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:ty,load:async()=>(await rs()).map(e=>({id:e.name,label:e.label||e.name}))},{id:`context`,label:`Context`,path:`contexts`,description:`Choose the tree and path a context opens, and who can access that view. File storage belongs to its workspace.`,sections:iy,load:async()=>(await ol()).map(e=>({id:e.id,label:e.name||e.id}))},{id:`agent`,label:`Agent`,path:`agents`,description:`Configure one assistant: its instructions, chat model, tools and access to Canvas.`,sections:oy,load:async()=>(await Cy()).map(e=>({id:e.id,label:e.label||e.name}))}];function Ky({to:e,label:t,description:n,icon:r}){return(0,$.jsxs)(Le,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,$.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,$.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,$.jsx)(fi,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function qy({group:e,query:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(`loading`),[c,l]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>Dh(t,e.label,n.label,n.description));return u.length?(0,$.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,$.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,$.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,$.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,$.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,$.jsx)(Ky,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function Jy(){let{state:e}=Xh(),[t,n]=(0,Q.useState)(``),r=Th.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>Dh(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Gy.some(e=>e.sections.some(n=>Dh(t,e.label,n.label,n.description)));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,$.jsx)(lh,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,$.jsx)(J,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Ky,{to:e.path,...e},e.path))})]},e.id)),Gy.map(e=>(0,$.jsx)(qy,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(Ky,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Yy=[{id:`canvas_1`,title:`Canvas Deep`,scheme:`dark`,background:`#032940`,accent:`#f2f2f2`,sources:[{type:`image/svg+xml`,src:`files/canvas_1.svg`},{type:`image/avif`,src:`files/canvas_1.avif`},{type:`image/webp`,src:`files/canvas_1.webp`}],thumb:`thumbs/canvas_1.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`canvas_3`,title:`Canvas Mono Dark`,scheme:`dark`,background:`#000000`,accent:`#ffffff`,sources:[{type:`image/svg+xml`,src:`files/canvas_3.svg`},{type:`image/avif`,src:`files/canvas_3.avif`},{type:`image/webp`,src:`files/canvas_3.webp`}],thumb:`thumbs/canvas_3.webp`,author:`Canvas`,license:`LicenseRef-Canvas-Brand`},{id:`w1`,title:`Frost`,scheme:`dark`,background:`#164a6f`,accent:`#9ad9f0`,sources:[{type:`image/avif`,src:`files/w1.avif`},{type:`image/webp`,src:`files/w1.webp`},{type:`image/jpeg`,src:`files/w1.jpg`}],thumb:`thumbs/w1.webp`,author:`Peter Cui Bide`,source:`https://petercui.deviantart.com`,license:`LicenseRef-Attribution-Only`}],Xy=`/wallpapers`;function Zy(e){return Yy.find(t=>t.id===e)}function Qy(e,t={}){let n=typeof e==`string`?Zy(e):e;if(!n)return null;let{base:r=Xy,types:i}=t,a=(i?n.sources.find(e=>i.includes(e.type)):n.sources[0])??n.sources[n.sources.length-1];return`${r.replace(/\/$/,``)}/${a.src}`}function $y(e,t=Xy){let n=typeof e==`string`?Zy(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var eb=[{id:`cover`,label:`Scale and Crop`,description:`Fills the screen, cropping edges as needed`},{id:`fill`,label:`Fill`,description:`Stretches to the exact screen size`},{id:`center`,label:`Centered`,description:`Original size, centered on the desk`}],tb=`canvas:wallpaper`,nb=`canvas-wallpaper`,rb=`settings`,ib=`builtin:`,ab=Yy;function ob(e){return $y(e)??``}function sb(e){return`${ib}${e}`}function cb(e){return e?.startsWith(ib)?e.slice(8):null}function lb(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function ub(){try{let e=localStorage.getItem(tb);if(e){let t=lb(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var db=ub(),fb=null;function pb(){return db}async function mb(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(nb,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(rb),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(rb,e?`readwrite`:`readonly`),a=i.objectStore(rb),o=e?a.put(e,tb):a.get(tb);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function hb(){try{localStorage.removeItem(tb)}catch{}}function gb(){return fb||=(async()=>{try{let e=lb(await mb());e?db=e:await mb(db),hb()}catch{}return wb(db),db})(),fb.then(()=>db)}async function _b(e){await gb(),await mb(e),db=e,hb(),wb(e)}function vb(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var yb=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function bb(e){if(!e)return null;let t=cb(e);if(t===null)return`url("${e}")`;let n=Zy(t);if(!n)return null;let r=`url("${Qy(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!yb||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Qy(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function xb(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var Sb=null;function Cb(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function wb(e=pb()){let t=document.documentElement.style,n=Sb,r=e.image;if(r?.startsWith(`data:`))try{Sb?.dataUrl!==r&&(Sb={dataUrl:r,objectUrl:URL.createObjectURL(Cb(r))}),r=Sb.objectUrl}catch{Sb=null,r=null}else Sb=null;let i=bb(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,xb(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==Sb&&URL.revokeObjectURL(n.objectUrl)}var Tb=[{id:`cards`,name:`Cards`,description:`Nested cards with connector lines. Each level indents.`},{id:`accordion-mobile`,name:`Accordion on phones (beta)`,description:`Experimental. Full-width accordion rows on a phone, cards on wider screens.`},{id:`accordion`,name:`Accordion (beta)`,description:`Experimental. Full-width rows at every depth; a depth rail, tint and colour swatch replace the indent, and open parents stick to the top while you scroll.`}],Eb=`canvas:treeStyle`;function Db(){try{let e=localStorage.getItem(Eb);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var Ob=Db(),kb=new Set;function Ab(){return Ob}function jb(e){try{e===`cards`?localStorage.removeItem(Eb):localStorage.setItem(Eb,e)}catch{}Ob=e;for(let e of kb)e()}function Mb(e){kb.add(e);let t=t=>{(t.key===Eb||t.key===null)&&(Ob=Db(),e())};return window.addEventListener(`storage`,t),()=>{kb.delete(e),window.removeEventListener(`storage`,t)}}function Nb(){return(0,Q.useSyncExternalStore)(Mb,Ab,()=>`cards`)}function Pb(){let e=Nb(),t=et();return e===`accordion`||e===`accordion-mobile`&&t}var Fb=[{id:`canvas`,name:`Canvas`,description:`Black and white with a teal accent. Sheets of paper on a grey desk.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.704 0.135 183)`]},{id:`nord`,name:`Nord`,description:`Cool arctic blues, lower contrast, softer corners.`,swatches:[`oklch(0.976 0.006 251)`,`oklch(0.588 0.056 244)`,`oklch(0.686 0.062 213)`]},{id:`contrast`,name:`High Contrast`,description:`WCAG AAA text contrast, square corners, hard borders, no shadows.`,swatches:[`oklch(1 0 0)`,`oklch(0 0 0)`,`oklch(0.32 0.16 258)`]},{id:`frost`,name:`Frosted Glass`,description:`Translucent, blurred surfaces over a soft backdrop. Best with a wallpaper.`,swatches:[`oklch(0.92 0.008 250)`,`oklch(0.31 0.025 255)`,`oklch(0.55 0.05 250)`]},{id:`terminal`,name:`Terminal`,description:`Monospaced and dense. Tighter rows and chrome for large displays.`,swatches:[`oklch(0.17 0.006 152)`,`oklch(0.8 0.19 148)`,`oklch(0.75 0.12 220)`]},{id:`halflife`,name:`Half-Life`,description:`Lambda orange on black steel. Square corners; the left rail is orange.`,swatches:[`oklch(0.724 0.181 52)`,`oklch(0 0 0)`,`oklch(1 0 0)`]}],Ib=Fb.map(e=>e.id),Lb=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],Rb=[{id:`auto`,name:`Auto`,description:`Match the pointer: touch on phones, mouse on desktop`},{id:`compact`,name:`Compact`,description:`Maximum rows per screen`},{id:`comfortable`,name:`Comfortable`,description:`Balanced for mouse use`},{id:`touch`,name:`Touch`,description:`Large targets for finger input`}],zb={theme:`canvas`,scheme:`light`,density:`auto`},Bb=`canvas.ui.theme`;function Vb(e){return typeof e==`string`&&Ib.includes(e)}function Hb(e){return e===`light`||e===`dark`||e===`system`}function Ub(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function Wb(e){let t=typeof e==`object`&&e?e:{};return{theme:Vb(t.theme)?t.theme:zb.theme,scheme:Hb(t.scheme)?t.scheme:zb.scheme,density:Ub(t.density)?t.density:zb.density}}var Gb=`(prefers-color-scheme: dark)`;function Kb(){return typeof document<`u`}function qb(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(Gb).matches}function Jb(e){return e===`system`?qb()?`dark`:`light`:e}function Yb(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(Gb),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function Xb(e){return Yb(e)}function Zb(){return qb()?`dark`:`light`}function Qb(){return`light`}function $b(e){let t=getComputedStyle(e).getPropertyValue(`--background`).trim();if(!t)return;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.name=`theme-color`,document.head.appendChild(n)),n.content=t}function ex(e,t=Kb()?document.documentElement:void 0){let n=Jb(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,$b(t),n):n}function tx(e,t=Kb()?document.documentElement:void 0){if(!t||typeof window>`u`)return ex(e,t);let n=document.createElement(`style`);n.appendChild(document.createTextNode(`*,*::before,*::after{transition:none!important;animation:none!important}`)),document.head.appendChild(n);let r=ex(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function nx(e){let t=e??ax();if(!t)return zb;try{let e=t.getItem(Bb);return e?Wb(JSON.parse(e)):zb}catch{return zb}}function rx(e,t){let n=t??ax();if(n)try{n.setItem(Bb,JSON.stringify(e))}catch{}}function ix(e){let t=e??ax();if(t)try{t.removeItem(Bb)}catch{}}function ax(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function ox({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Q.useState)(()=>({...nx(n),...t})),o=(0,Q.useSyncExternalStore)(Xb,Zb,Qb),s=i.scheme===`system`?o:i.scheme;(0,Q.useEffect)(()=>{tx({...i,scheme:s})},[i,s]),(0,Q.useEffect)(()=>{r&&rx(i,n)},[i,r,n]);let c=(0,Q.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Q.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Q.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Q.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?Zb():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Q.useCallback)(()=>{ix(n),a(zb)},[n]),p=(0,Q.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,$.jsx)(El.Provider,{value:p,children:e})}var sx={system:la,light:xi,dark:lr};function cx(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Dl(),c=ht(),l=Lh(),u=Nb(),d=Kh();return(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,$.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:Fb.map(t=>{let n=t.id===e;return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:q(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,$.jsx)($n,{className:`size-4 shrink-0 text-primary`})]}),(0,$.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,$.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,$.jsx)(px,{options:Lb.map(e=>{let t=sx[e.id];return{id:e.id,label:e.name,icon:(0,$.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,$.jsx)(px,{options:Rb.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Rb.find(e=>e.id===n)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,$.jsx)(px,{options:Oh.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:Fh}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Oh.find(e=>e.id===l)?.description}),l===`strip`&&(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,$.jsx)(px,{options:Rh.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:Wh}),(0,$.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[Rh.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,$.jsx)(px,{options:Tb.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:jb}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:Tb.find(e=>e.id===u)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(fx,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,$.jsx)(px,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:lt}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,$.jsx)(lx,{}),(0,$.jsx)(`section`,{children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s(),lt(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function lx(){let[e,t]=(0,Q.useState)(pb),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=!1;return gb().then(()=>{e||(t(pb()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await vb(n)}:e;await _b(i),t(i),r(null)}catch(e){r(e instanceof Error&&e.name!==`QuotaExceededError`?e.message:`Could not store the wallpaper. Free some browser storage or try a smaller image.`)}finally{c.current=!1,s(!1)}}},u=t=>{t&&l(e,t)},d=e.image!==null&&cb(e.image)===null,f=bb(e.image);return(0,$.jsx)(`section`,{children:(0,$.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,$.jsx)(fx,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,$.jsx)(dx,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,$.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),ab.map(t=>(0,$.jsx)(dx,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:cb(e.image)===t.id,onSelect:()=>l({...e,image:sb(t.id)}),children:(0,$.jsx)(`img`,{src:ob(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,$.jsx)(dx,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,$.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,$.jsx)(ux,{}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:xb(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,$.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>l({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,$.jsx)(px,{options:eb.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function ux(){let e=ab.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function dx({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:q(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,$.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,$.jsx)($n,{className:`size-3`})})]})}function fx({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function px({options:e,value:t,onChange:n}){return(0,$.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:q(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function mx(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`Appearance`,onBack:Gv(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,$.jsx)(cx,{})]})}var hx={previousTree:`Alt+Q`,nextTree:`Alt+W`},gx=`canvas:key-bindings`,_x=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function vx(){try{let e=JSON.parse(localStorage.getItem(gx)||`{}`),t={...hx};for(let n of Object.keys(t))(e[n]===``||_x.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...hx}:t}catch{return{...hx}}}function yx(e){localStorage.setItem(gx,JSON.stringify(e))}function bx(e){return/^Key[A-Z]$/.test(e.code)?[e.ctrlKey&&`Ctrl`,e.altKey&&`Alt`,e.metaKey&&`Meta`,e.shiftKey&&`Shift`,e.code.slice(3)].filter(Boolean).join(`+`):``}function xx(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function Sx(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function Cx(){let[e,t]=(0,Q.useState)(vx),[n,r]=(0,Q.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{yx(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`Key bindings`,onBack:Gv(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,$.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,$.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||hx[t].slice(-1)}`:``}),children:[(0,$.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]}),(0,$.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||hx[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,$.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...hx}),children:`Restore defaults`}),(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var wx=`offline-content-v1`,Tx=`offline-api-v1`,Ex=1073741824,Dx={enabled:!1,budgetBytes:4*Ex,excludedWorkspaces:[]},Ox=1e3;function kx(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function Ax(e,t,n){return`${e}:${t}:${kx(n)}`}var jx=`canvas-offline`,Mx=2,Nx=null;function Px(){return Nx||(Nx=new Promise((e,t)=>{let n=indexedDB.open(jx,Mx);n.onupgradeneeded=e=>{let t=n.result;if(t.objectStoreNames.contains(`config`)||t.createObjectStore(`config`),t.objectStoreNames.contains(`entries`)||t.createObjectStore(`entries`,{keyPath:`url`}),e.oldVersion>=1&&t.objectStoreNames.contains(`pins`)){t.deleteObjectStore(`pins`);let e=n.transaction.objectStore(`entries`).openCursor();e.onsuccess=()=>{let t=e.result;if(!t)return;let n=t.value;n.pinned&&t.update({...n,pinned:!1}),t.continue()}}t.objectStoreNames.contains(`scopes`)||t.createObjectStore(`scopes`,{keyPath:`id`})},n.onsuccess=()=>{n.result.onversionchange=()=>{n.result.close(),Nx=null},e(n.result)},n.onerror=()=>{Nx=null,t(n.error)}}),Nx)}function Fx(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function Ix(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function Lx(e,t){return Ix((await Px()).transaction(e).objectStore(e).get(t))}async function Rx(e){return Ix((await Px()).transaction(e).objectStore(e).getAll())}async function zx(e,t,n){let r=(await Px()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),Fx(r)}async function Bx(e,t){let n=(await Px()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),Fx(n)}async function Vx(e){let t=(await Px()).transaction(e,`readwrite`);return t.objectStore(e).clear(),Fx(t)}async function Hx(){try{let e=await Lx(`config`,`settings`);return e?{...Dx,...e}:Dx}catch{return Dx}}async function Ux(e){await zx(`config`,e,`settings`)}async function Wx(e,t){let n=(await Px()).transaction(`entries`,`readwrite`),r=n.objectStore(`entries`);for(let n of e){let e=r.get(n);e.onsuccess=()=>{let i=e.result;i?r.put({...i,pinned:t}):t&&r.put({url:n,kind:`content`,size:0,lastAccess:Date.now(),pinned:t})}}return Fx(n)}async function Gx(e){let t=await Rx(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-Ox)),i=t.filter(e=>e.kind===`content`),a=i.reduce((e,t)=>e+t.size,0),o=i.filter(e=>!e.pinned).sort((e,t)=>e.lastAccess-t.lastAccess),s=[];for(let t of o){if(a<=e)break;s.push(t),a-=t.size}if(!r.length&&!s.length)return;let[c,l]=await Promise.all([caches.open(Tx),caches.open(wx)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await Bx(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await Bx(`entries`,e.url)})])}async function Kx(){let e=await Rx(`entries`),t=e.filter(e=>e.kind===`content`);return{contentBytes:t.reduce((e,t)=>e+t.size,0),contentCount:t.length,pinnedBytes:t.filter(e=>e.pinned).reduce((e,t)=>e+t.size,0),apiCount:e.length-t.length}}async function qx(){await Promise.all([caches.delete(wx),caches.delete(Tx)]),await Vx(`entries`),await Vx(`scopes`)}async function Jx(){return Rx(`scopes`)}async function Yx(e){return Lx(`scopes`,e)}async function Xx(e){await zx(`scopes`,e)}async function Zx(e){let t=await Lx(`scopes`,e);await Bx(`scopes`,e),t?.urls.length&&await Qx(t.urls)}async function Qx(e){let t=await Rx(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await Wx(r,!1)}var $x=3,eS=`data/schema/file`,tS=128;async function nS({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await Hx();if(!a.enabled)throw Error(`Enable the offline cache first`);if(a.excludedWorkspaces.includes(e))throw Error(`Workspace "${e}" is excluded from offline caching`);let o=Ax(e,n,t),s=kx(t),c=await Yx(o),l=((await Ks(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===eS),u=[],d=0,f=0,p=!1,m=l.length;i?.({done:f,total:m,bytes:d});let h=0;await Promise.all(Array.from({length:Math.min($x,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Nc(e,t.id);d+=n.size,u.push(`${qa.workspaces}/${e}/documents/${t.id}/content`);try{await Co(e,t.id,tS),u.push(`${qa.workspaces}/${e}/documents/${t.id}/thumbnail?size=${tS}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await Wx(u,!0);let g={id:o,workspaceRef:e,treeName:n,treeType:r,path:s,urls:u,bytes:d,warmedAt:Date.now(),...p?{truncated:!0}:{}};if(await Xx(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await Qx(t)}return g}var rS=[{label:`1 GB`,bytes:1*Ex},{label:`2 GB`,bytes:2*Ex},{label:`4 GB`,bytes:4*Ex},{label:`8 GB`,bytes:8*Ex}];function iS(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/Ex).toFixed(2)} GB`}function aS(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function oS(){let{showSuccessToast:e,showErrorToast:t}=vo(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)({}),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useCallback)(()=>{Hx().then(r).catch(()=>{}),Kx().then(a).catch(()=>{}),Jx().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,Q.useEffect)(()=>{v(),rs().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await Ux(e),aS(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),Gx(e.budgetBytes).then(v).catch(()=>{})},b=e=>{if(!n)return;let t=n.excludedWorkspaces.includes(e)?n.excludedWorkspaces.filter(t=>t!==e):[...n.excludedWorkspaces,e];y({...n,excludedWorkspaces:t})},x=async()=>{h(!0);try{await qx(),e(`Offline cache cleared`),v()}catch(e){t(e instanceof Error?e.message:`Failed to clear cache`)}finally{h(!1)}},S=async n=>{let r=Ax(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await nS(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${iS(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${iS(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},C=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},w=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),T=async e=>{await Zx(e),v()};return n?(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(sS,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:q(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,$.jsx)(Ba,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,$.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,$.jsx)($n,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:rS.map(e=>(0,$.jsx)(X,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,$.jsxs)(`span`,{children:[iS(i.contentBytes),` of `,iS(n.budgetBytes),` used`]}),(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${iS(i.pinnedBytes)} pinned`:``]})]}),(0,$.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,$.jsx)(`div`,{children:(0,$.jsxs)(X,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,$.jsx)(Sa,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(Kr,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(sS,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,$.jsx)(`div`,{className:`mb-3`,children:(0,$.jsxs)(X,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,$.jsx)(wr,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,$.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,$.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Sa,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${iS(t.bytes)}`:`listing…`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[iS(e.bytes),e.truncated?` (partial)`:``]}),(0,$.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>S(w(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,$.jsx)(Un,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(X,{variant:`ghost`,size:`sm`,onClick:()=>T(e.id),"aria-label":`Unpin ${e.id}`,children:(0,$.jsx)(ur,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,$.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(sS,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,$.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(`span`,{className:q(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,$.jsx)(ua,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,$.jsx)(X,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,$.jsx)(zt,{onClose:()=>_(!1),children:(0,$.jsx)(pe,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:C,onClose:()=>_(!1)})})]}):null}function sS({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function cS(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`Offline`,onBack:Gv(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,$.jsx)(oS,{})]})}function lS(e){let t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`}function uS({name:e,version:t,detail:n}){return(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,$.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function dS(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!0;return Y.get(`/ping`,{skipAuth:!0}).then(n=>{e&&t(n??{})}).catch(t=>{e&&r(t instanceof Error?t.message:`Failed to reach the server`)}),()=>{e=!1}},[]);let i=[e?.commit?`commit ${e.commit.slice(0,7)}`:null,typeof e?.uptime==`number`?`up ${lS(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(lh,{className:`mb-6`,title:`About`,onBack:Gv(),description:`Versions of every Canvas component this installation is running.`}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,$.jsx)(uS,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.8`}),e?.version&&(0,$.jsx)(uS,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,$.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,$.jsx)(uS,{name:e,version:`v${t}`},e))})]}),n&&(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,$.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var fS=[`onnx`,`clip`,`blip`,`openai`],pS=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],mS=[{id:`openai`,baseUrl:`https://api.openai.com/v1`,label:`OpenAI`},{id:`vllm`,baseUrl:`http://127.0.0.1:8000/v1`,label:`vLLM`},{id:`ollama`,baseUrl:`http://127.0.0.1:11434/v1`,label:`Ollama`}],hS=e=>`${qa.workspaces}/${encodeURIComponent(e)}/inferd`;function gS(e,t){let n={};for(let[r,i]of Object.entries(e.providers||{})){let e={...i};delete e.apiKeySet,delete e.headerNames,t.has(r)&&i.apiKey?e.apiKey=i.apiKey:delete e.apiKey,n[r]=e}return{...e,providers:n}}async function _S(e){return await Y.get(`${hS(e)}/status`)}async function vS(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await Y.post(`${hS(e)}/summarize/images`,n)}async function yS(e){return await Y.post(`${hS(e)}/summarize/images/stop`,{})}async function bS(e){return await Y.get(`${hS(e)}/config`)}async function xS(e,t){return await Y.put(`${hS(e)}/config`,t)}async function SS(e,t={}){let n={};return t.space&&(n.space=t.space),t.reindex!==void 0&&(n.reindex=t.reindex),t.scope&&(n.scope=t.scope),await Y.post(`${hS(e)}/reindex`,n)}async function CS(e){return await Y.get(`${hS(e)}/vector-tables`)}async function wS(e,t){return await Y.delete(`${hS(e)}/vector-tables/${encodeURIComponent(t)}`)}async function TS(){return await Y.get(`${qa.inferd}/config`)}async function ES(e){return await Y.put(`${qa.inferd}/config`,e)}async function DS(){return await Y.get(`${qa.inferd}/defaults`)}async function OS(e){return await Y.put(`${qa.inferd}/defaults`,e)}async function kS(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await Y.post(`${qa.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function AS(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await Y.post(`${qa.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var jS=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,MS=`font-semibold uppercase tracking-[0.08em]`,NS={openai:{url:{key:`baseUrl`,label:`Base URL`,placeholder:`http://gpu.local:8000/v1`,hint:`OpenAI-compatible embeddings endpoint — Ollama, vLLM, TEI, infinity, LM Studio and OpenAI itself all speak this. A trailing /v1 is optional; both http://host:8000 and http://host:8000/v1 work.`},apiKey:"Sent as `Authorization: Bearer …`. Leave empty for servers that do not check it.",imageInput:!0,timeoutMs:!0,headers:!0,where:e=>e.baseUrl||`no endpoint set`},ollama:{url:{key:`host`,label:`Host (legacy)`,placeholder:`http://127.0.0.1:11434`,hint:`Written by an older version. Switch the type to openai — the host becomes the base URL and the /v1 suffix is added for you.`},apiKey:"Sent as `Authorization: Bearer …`.",where:e=>e.host||`http://127.0.0.1:11434`},onnx:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`},clip:{cacheDir:`Where downloaded weights are cached on the server. Empty uses the server default.`,note:`Runs in-process on the server. No endpoint and no credentials.`,where:()=>`in-process`}},PS=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],FS=[{value:`data-uri`,label:`data-uri (default)`,hint:"Images ride in the ordinary `input` array as data URIs (infinity, TEI-style servers)."},{value:`messages`,label:`messages`,hint:`vLLM's multimodal shape: one request per image, wrapped in a chat message.`}],IS=12e4;function LS(e){if(typeof e!=`string`||e.trim()===``)return null;let t;try{t=new URL(e.trim())}catch{return`Must be an absolute URL including the scheme, e.g. http://127.0.0.1:11434`}return t.protocol!==`http:`&&t.protocol!==`https:`?`Unsupported scheme '${t.protocol.replace(`:`,``)}'. Use http or https.`:null}function RS({title:e,hint:t}){return(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`h3`,{className:q(`text-[11px] text-muted-foreground`,MS),children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function zS({overridden:e,source:t}){return e?(0,$.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function BS({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,$.jsx)(zS,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,$.jsx)(J,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:q(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,$.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function VS({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,$.jsx)(zS,{overridden:n})]})}function HS({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,Q.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,$.jsx)(zS,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,$.jsxs)($.Fragment,{children:[`Stored: `,(0,$.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(J,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,$.jsx)(J,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,$.jsx)(Bi,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function US({open:e,onClick:t,label:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,$.jsx)(Hr,{className:q(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var WS={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function GS({value:e,effective:t,inherited:n,resolvedSpaces:r,invalid:i,attention:a,onFill:o,saving:s=!1,disabled:c=!1,saveLabel:l=`Save`,onSave:u}){let{showToast:d}=Z(),[f,p]=(0,Q.useState)(()=>structuredClone(e)),[m,h]=(0,Q.useState)(new Set),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?NS[i.type]?.url?.key:void 0,o=a?LS(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await kS(i,r)===!1&&(y(!0),d({title:`Downloading model`,description:`'${r??`the configured model`}' is not in the server's cache yet; downloading now. A first test can take a few minutes; the model is then cached for good.`}))}catch{}let n=await AS(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,Q.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?NS[i]?.url?.key:void 0;if(!a)continue;let o=LS(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,Q.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),L=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(gS(f,m)),h(new Set)},ne=e=>T(t=>t===e?null:e);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,$.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,$.jsx)(nr,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,$.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(RS,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,$.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`span`,{className:q(`absolute inset-y-0 left-0 w-[3px]`,WS[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:q(`text-[11px]`,MS),children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,$.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,$.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,$.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,$.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,$.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,$.jsx)(tr,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,$.jsx)(US,{open:m,onClick:()=>ne(p),label:`Edit ${e}`})]})]}),m&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,$.jsx)(zS,{overridden:s.provider!==void 0,source:u.provider})]}),(0,$.jsxs)(`select`,{className:jS,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]})]}),(0,$.jsx)(BS,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,$.jsx)(BS,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,$.jsx)(BS,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,$.jsx)(VS,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,$.jsx)(VS,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(J,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,$.jsx)(Bi,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(RS,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=pS.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?NS[l]:void 0,d=u?.url?LS(n[u.url.key]):null,p={...r,...n},h=PS.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,$.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,$.jsx)(Kr,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(US,{open:s,onClick:()=>ne(o),label:`Edit ${e}`})]})]}),s&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,$.jsx)(zS,{overridden:n.type!==void 0,source:r.type})]}),(0,$.jsxs)(`select`,{className:jS,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),fS.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),l&&!fS.includes(l)&&(0,$.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,$.jsx)(BS,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,$.jsx)(BS,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,$.jsx)(zS,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,$.jsxs)(`select`,{className:jS,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),FS.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:FS.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,$.jsx)(BS,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??IS,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,$.jsx)(J,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,$.jsx)(HS,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[`Not used by type `,(0,$.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,$.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,$.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,$.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(J,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,$.jsx)(Bi,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),mS.filter(e=>!D.includes(e.id)).map(e=>(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,$.jsx)(X,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:L,disabled:s||!te||I.length>0,children:s?`Saving…`:l}),(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,$.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function KS(){let{showToast:e}=Z(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=(0,Q.useCallback)(()=>TS().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,Q.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,$.jsx)(lh,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:Gv(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,$.jsxs)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,$.jsx)(Un,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(Un,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,$.jsx)(X,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,$.jsx)(GS,{value:t.user||{},effective:t.effective||{},inherited:t.serverDefaults||{},invalid:t.invalid,saving:a,saveLabel:`Save defaults`,onSave:async t=>{o(!0);try{let n=await ES(t);e({title:`Defaults saved`,description:n.restartRequired?`${n.workspaces.length} running workspace(s) keep their current tables until restarted. Set the config on a workspace directly to change it live.`:`New workspaces will inherit this.`}),await l()}catch(t){e({title:`Save failed`,description:t instanceof Error?t.message:`Failed to save`,variant:`destructive`})}finally{o(!1)}}},JSON.stringify(t.user))]})}function qS(){let e=Bt(),{showToast:t}=Z(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,Q.useState)(i),[c,l]=(0,Q.useState)(a),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),g=(0,Q.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await Y.get(e,{skipAuth:!0,headers:_()});d(t);let n=await Y.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,Q.useRef)(v);return(0,Q.useEffect)(()=>{y.current()},[]),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(lh,{onBack:Gv(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(J,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,$.jsx)(J,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,$.jsx)(X,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,$.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,$.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,$.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,$.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,$.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,$.jsx)(Yl,{className:`mt-8`})]})}function JS(e={}){let t=new URLSearchParams;e.tail&&t.set(`tail`,String(e.tail)),e.level&&t.set(`level`,e.level),e.module&&t.set(`module`,e.module);let n=t.toString();return n?`?${n}`:``}function YS(){let e=localStorage.getItem(`authToken`);if(!e)throw Error(`Authentication required`);let t=localStorage.getItem(`appName`)||window.location.hostname;return{Authorization:`Bearer ${e}`,"X-App-Name":t,Accept:`text/event-stream`}}var XS={users:{async listUsers(e){let t=new URLSearchParams;e?.status&&t.append(`status`,e.status),e?.userType&&t.append(`userType`,e.userType);let n=t.toString(),r=n?`${qa.admin.users}?${n}`:qa.admin.users;return await Y.get(r)},async getUser(e){return await Y.get(`${qa.admin.users}/${e}`)},async createUser(e){return await Y.post(qa.admin.users,e)},async updateUser(e,t){return await Y.put(`${qa.admin.users}/${e}`,t)},async deleteUser(e){await Y.delete(`${qa.admin.users}/${e}`)}},workspaces:{async listAllWorkspaces(){return await Y.get(qa.admin.workspaces)},async createWorkspace(e){return await Y.post(qa.admin.workspaces,e)},async deleteWorkspace(e){await Y.delete(`${qa.admin.workspaces}/${e}`)}},logs:{async getLogs(e={}){return(await Y.get(`${qa.admin.logs}${JS(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${qa.admin.logsStream}${JS(e)}`,{method:`GET`,headers:YS(),credentials:`include`,signal:n});if(!t.ok)throw Error(`Failed to open log stream (${t.status})`);if(!t.body)throw Error(`Streaming is not supported by this browser`);let i=t.body.getReader(),a=new TextDecoder,o=``,s=e=>{let t=e.split(`
|
|
13
13
|
`),n=`message`,i=[];for(let e of t)if(!(!e||e.startsWith(`:`))){if(e.startsWith(`event:`)){n=e.slice(6).trim();continue}e.startsWith(`data:`)&&i.push(e.slice(5).trim())}if(n!==`log`||i.length===0)return;let a=JSON.parse(i.join(`
|
|
14
14
|
`));r?.(a)};try{for(;;){let{done:e,value:t}=await i.read();if(e)break;o+=a.decode(t,{stream:!0});let n=o.split(`
|
|
15
15
|
|