@augmentd-labs/canvas-web 2.14.15 → 2.14.16
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,13 +1,13 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdf-Ciz5_WNq.js","assets/preload-helper-Czpn1I53.js","assets/markdown-html-bKd2bDZi.js","assets/rolldown-runtime-C0FnF6B9.js","assets/react-DQazvoR7.js","assets/sanitize-DrVcFY1Q.js","assets/punycode.es6-ZbLrB_Dn.js","assets/markdown-html-T86c6cqD.css","assets/SketchEditor-BbXQRr1e.js","assets/ui-BX_B5WCf.js","assets/utils-BxVxyehK.js","assets/workspace-CBQfK-Dr.js","assets/utils-2pl1SbIp.js","assets/blobs-Cn7cVptE.js","assets/sha256-OKSsHPWr.js","assets/chunk-K2UTITRG-D0fgw4vC.js","assets/chunk-SRAX5OIU-Dhm3gOdh.js","assets/chunk-6U3AYISY-C6-Mtja1.js","assets/chunk-Z3N5DIM6-D9TMVU7m.js","assets/EditorOverlay-y6SK-pjT.js","assets/SketchEditor-DtRVLazd.css","assets/TextDocumentEditor-BU0qu4aP.js","assets/text-documents-De1PQIC0.js","assets/LocationTab-ARqmeXmv.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/NextShell-DDBrRX1x.js","assets/NextShell-B4NeoNB5.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{Ct as a,St as o,_t as s,bt as c,st as l,vt as u,wt as d,xt as f,yt as p}from"./react-DQazvoR7.js";import{t as m}from"./preload-helper-Czpn1I53.js";import{$ as h,$n as g,$r as _,$t as v,An as y,Ar as b,At as x,B as S,Bn as C,Br as w,Bt as T,C as E,Cn as D,Cr as O,Ct as k,Dn as A,Dr as j,Dt as M,En as N,Er as P,Et as F,F as I,Fn as ee,Fr as te,Ft as ne,G as re,Gn as ie,Gr as L,Gt as R,H as ae,Hn as oe,Hr as se,Ht as ce,I as z,Ir as le,It as ue,J as de,Jn as fe,Jr as pe,Jt as me,K as he,Kn as ge,Kr as _e,Kt as ve,L as ye,Lr as B,Lt as be,Mn as V,Mr as xe,Mt as H,Nn as Se,Nr as Ce,Nt as U,On as W,Or as we,Ot as Te,Pn as Ee,Pr as De,Pt as Oe,Q as ke,Qn as Ae,Qr as je,Qt as Me,R as G,Rn as Ne,Rr as Pe,Rt as Fe,S as Ie,Sn as Le,Sr as Re,St as ze,T as Be,Tr as Ve,Tt as He,U as Ue,Un as We,Ur as Ge,Ut as Ke,V as qe,Vn as Je,Vr as Ye,Vt as Xe,W as Ze,Wn as Qe,Wr as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zr as dt,Zt as ft,_ as pt,_i as mt,_n as ht,_r as gt,_t,ai as vt,an as yt,ar as bt,at as xt,b as St,bn as Ct,br as wt,bt as Tt,ci as Et,cn as Dt,cr as Ot,ct as kt,d as At,di as jt,dn as Mt,dr as Nt,dt as Pt,ei as Ft,en as It,er as Lt,et as Rt,f as zt,fi as Bt,fr as Vt,ft as Ht,g as Ut,gi as Wt,gn as Gt,gr as Kt,gt as qt,h as Jt,hi as Yt,hn as Xt,hr as Zt,ht as Qt,ii as $t,in as en,ir as tn,it as nn,jn as rn,jr as an,jt as on,kn as sn,kr as cn,kt as ln,li as un,ln as dn,lr as fn,lt as pn,m as mn,mi as hn,mr as gn,mt as _n,ni as vn,nn as yn,nr as bn,nt as xn,oi as Sn,on as Cn,or as wn,ot as Tn,p as En,pi as Dn,pn as On,pr as kn,pt as An,q as jn,qn as Mn,qr as Nn,qt as Pn,rn as Fn,rr as In,rt as Ln,si as Rn,sn as zn,sr as Bn,st as Vn,ti as Hn,tn as Un,tr as Wn,tt as Gn,u as Kn,ui as qn,un as Jn,ur as Yn,ut as Xn,v as Zn,vi as Qn,vn as $n,vr as er,vt as tr,w as nr,wn as rr,wr as ir,wt as ar,x as or,xn as sr,xr as cr,xt as lr,y as ur,yn as dr,yr as fr,yt as pr,z as mr,zn as hr,zr as gr,zt as _r}from"./ui-BX_B5WCf.js";import{i as vr,n as yr,r as br}from"./utils-BxVxyehK.js";import{n as xr,t as K}from"./utils-2pl1SbIp.js";import{$ as Sr,$t as Cr,A as wr,An as Tr,At as Er,B as Dr,Bt as Or,C as kr,Cn as Ar,Ct as jr,D as Mr,Dn as Nr,Dt as Pr,E as Fr,En as Ir,Et as Lr,F as Rr,Fn as q,Ft as zr,G as Br,H as Vr,Ht as Hr,I as Ur,In as J,It as Wr,J as Gr,Jt as Kr,K as qr,Kt as Jr,L as Yr,Lt as Xr,M as Zr,Mn as Qr,Mt as $r,N as ei,Nn as ti,Nt as ni,O as ri,On as ii,Ot as ai,P as oi,Pn as si,Pt as ci,Q as li,Qt as ui,R as di,Rt as fi,S as pi,Sn as mi,St as hi,T as gi,Tn as Y,Tt as _i,U as vi,Ut as yi,V as bi,Vt as xi,W as Si,Wt as Ci,X as wi,Xt as Ti,Y as Ei,Yt as Di,Z as Oi,Zt as ki,_ as Ai,_n as ji,_t as Mi,a as Ni,an as Pi,at as Fi,b as Ii,bn as Li,bt as Ri,c as zi,cn as Bi,ct as Vi,d as Hi,dn as Ui,dt as Wi,en as Gi,et as Ki,f as qi,fn as Ji,ft as Yi,g as Xi,gn as Zi,gt as Qi,h as $i,hn as ea,ht as ta,i as na,in as ra,it as ia,jn as aa,jt as oa,k as sa,kn as ca,kt as la,l as ua,ln as da,lt as fa,m as pa,mn as ma,mt as ha,n as ga,nn as _a,nt as va,o as ya,on as ba,ot as xa,p as Sa,pn as Ca,pt as wa,q as Ta,qt as Ea,r as Da,rn as Oa,rt as ka,s as Aa,sn as ja,st as Ma,t as Na,tn as Pa,tt as Fa,u as Ia,un as La,ut as Ra,v as za,vn as Ba,vt as Va,w as Ha,wn as Ua,wt as Wa,x as Ga,xn as Ka,xt as qa,y as Ja,yn as Ya,yt as Xa,z as Za,zt as Qa}from"./workspace-CBQfK-Dr.js";import{t as $a}from"./socket-hM4c-ZSl.js";import{_ as eo,a as to,d as no,g as ro,h as io,i as ao,l as oo,m as so,n as co,o as lo,p as uo,t as fo,v as po}from"./blobs-Cn7cVptE.js";import{_ as mo,a as ho,c as go,d as _o,f as vo,g as yo,h as bo,i as xo,l as So,m as Co,n as wo,o as To,p as Eo,r as Do,s as Oo,t as ko,u as Ao,v as jo}from"./text-documents-De1PQIC0.js";import{n as Mo,t as No}from"./map-BxCwdK0d.js";import{t as Po}from"./search-COMZIxA7.js";import{A as Fo,B as Io,C as Lo,D as Ro,E as zo,F as Bo,H as Vo,I as Ho,L as Uo,M as Wo,N as Go,O as Ko,P as qo,R as Jo,S as Yo,T as Xo,V as Zo,_ as Qo,a as $o,b as es,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,o as ds,p as fs,r as ps,s as ms,t as hs,u as gs,v as _s,w as vs,x as ys,y as bs,z as xs}from"./sha256-OKSsHPWr.js";import{t as Ss}from"./sanitize-DrVcFY1Q.js";import{n as Cs,t as ws}from"./use-theme-pnVLU4Kg.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 X=n(d(),1),Ts=o(),Es=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,Ds=/^[\\/]{2}/;function Os(e,t){return t+e.replace(/\\/g,`/`)}var ks=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(ks||{}),As=`popstate`;function js(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function Ms(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return Ls(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:Rs(t)}return Bs(t,n,null,e)}function Ns(e,t){if(e===!1||e==null)throw Error(t)}function Ps(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function Fs(){return Math.random().toString(36).substring(2,10)}function Is(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function Ls(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?zs(t):t,state:n,key:t&&t.key||r||Fs(),mask:i}}function Rs({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function zs(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function Bs(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=js(e)?e:Ls(h.location,e,t);n&&n(r,e),l=u()+1;let d=Is(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=js(e)?e:Ls(h.location,e,t);n&&n(r,e),l=u();let i=Is(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return Vs(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(As,d),c=e,()=>{i.removeEventListener(As,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function Vs(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Ns(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:Rs(t);return i=i.replace(/ $/,`%20`),!n&&Ds.test(i)&&(i=r+i),new URL(i,r)}function Hs(e,t,n=`/`){return Us(e,t,n,!1)}function Us(e,t,n,r,i){let a=cc((typeof t==`string`?zs(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Ws(e),s=null,c=sc(a);for(let e=0;s==null&&e<o.length;++e)s=rc(o[e],c,r);return s}function Ws(e){let t=Gs(e);return qs(t),t}function Gs(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;Ns(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=gc([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Ns(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),Gs(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:tc(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=oc(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of Ks(e.path))a(e,t,!0,n)}),t}function Ks(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=Ks(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function qs(e){e.sort((e,t)=>e.score===t.score?nc(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var Js=/^:[\w-]+$/,Ys=3,Xs=2,Zs=1,Qs=10,$s=-2,ec=e=>e===`*`;function tc(e,t){let n=e.split(`/`),r=n.length;return n.some(ec)&&(r+=$s),t&&(r+=Xs),n.filter(e=>!ec(e)).reduce((e,t)=>e+(Js.test(t)?Ys:t===``?Zs:Qs),r)}function nc(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function rc(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?ac(u,l,s.matcher,s.compiledParams):ic(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=ic({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:gc([a,d.pathname]),pathnameBase:vc(gc([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=gc([a,d.pathnameBase]))}return o}function ic(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=oc(e.path,e.caseSensitive,e.end);return ac(e,t,n,r)}function ac(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function oc(e,t=!1,n=!0){Ps(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function sc(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return Ps(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function cc(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function lc(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?zs(e):e,a;return n?(n=hc(n),a=n.startsWith(`/`)?uc(n.substring(1),`/`):uc(n,t)):a=t,{pathname:a,search:yc(r),hash:bc(i)}}function uc(e,t){let n=_c(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function dc(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function fc(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function pc(e){let t=fc(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function mc(e,t,n,r=!1){let i;typeof e==`string`?i=zs(e):(i={...e},Ns(!i.pathname||!i.pathname.includes(`?`),dc(`?`,`pathname`,`search`,i)),Ns(!i.pathname||!i.pathname.includes(`#`),dc(`#`,`pathname`,`hash`,i)),Ns(!i.search||!i.search.includes(`#`),dc(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=lc(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var hc=e=>e.replace(/[\\/]{2,}/g,`/`),gc=e=>hc(e.join(`/`)),_c=e=>e.replace(/\/+$/,``),vc=e=>_c(e).replace(/^\/*/,`/`),yc=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,bc=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,xc=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function Sc(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Cc(e){return gc(e.map(e=>e.route.path).filter(Boolean))||`/`}var wc=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Tc(e,t){let n=e;if(typeof n!=`string`||!Es.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(wc)try{let e=new URL(window.location.href),r=Ds.test(n)?new URL(Os(n,e.protocol)):new URL(n),a=cc(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{Ps(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var Ec=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Ec);var Dc=[`GET`,...Ec];new Set(Dc);var Oc=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function kc(e){try{return Oc.includes(new URL(e).protocol)}catch{return!1}}var Ac=X.createContext(null);Ac.displayName=`DataRouter`;var jc=X.createContext(null);jc.displayName=`DataRouterState`;var Mc=X.createContext(!1);function Nc(){return X.useContext(Mc)}var Pc=X.createContext({isTransitioning:!1});Pc.displayName=`ViewTransition`;var Fc=X.createContext(new Map);Fc.displayName=`Fetchers`;var Ic=X.createContext(null);Ic.displayName=`Await`;var Lc=X.createContext(null);Lc.displayName=`Navigation`;var Rc=X.createContext(null);Rc.displayName=`Location`;var zc=X.createContext({outlet:null,matches:[],isDataRoute:!1});zc.displayName=`Route`;var Bc=X.createContext(null);Bc.displayName=`RouteError`;var Vc=`REACT_ROUTER_ERROR`,Hc=`REDIRECT`,Uc=`ROUTE_ERROR_RESPONSE`;function Wc(e){if(e.startsWith(`${Vc}:${Hc}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function Gc(e){if(e.startsWith(`${Vc}:${Uc}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new xc(t.status,t.statusText,t.data)}catch{}}function Kc(e,{relative:t}={}){Ns(qc(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=X.useContext(Lc),{hash:i,pathname:a,search:o}=nl(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:gc([n,a])),r.createHref({pathname:s,search:o,hash:i})}function qc(){return X.useContext(Rc)!=null}function Jc(){return Ns(qc(),`useLocation() may be used only in the context of a <Router> component.`),X.useContext(Rc).location}var Yc=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Xc(e){X.useContext(Lc).static||X.useLayoutEffect(e)}function Zc(){let{isDataRoute:e}=X.useContext(zc);return e?yl():Qc()}function Qc(){Ns(qc(),`useNavigate() may be used only in the context of a <Router> component.`);let e=X.useContext(Ac),{basename:t,navigator:n}=X.useContext(Lc),{matches:r}=X.useContext(zc),{pathname:i}=Jc(),a=JSON.stringify(pc(r)),o=X.useRef(!1);return Xc(()=>{o.current=!0}),X.useCallback((r,s={})=>{if(Ps(o.current,Yc),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=mc(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:gc([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var $c=X.createContext(null);function el(e){let t=X.useContext(zc).outlet;return X.useMemo(()=>t&&X.createElement($c.Provider,{value:e},t),[t,e])}function tl(){let{matches:e}=X.useContext(zc);return e[e.length-1]?.params??{}}function nl(e,{relative:t}={}){let{matches:n}=X.useContext(zc),{pathname:r}=Jc(),i=JSON.stringify(pc(n));return X.useMemo(()=>mc(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function rl(e,t){return il(e,t)}function il(e,t,n){Ns(qc(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=X.useContext(Lc),{matches:i}=X.useContext(zc),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;xl(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${s}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
|
|
3
3
|
|
|
4
|
-
Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=Jc(),d;if(t){let e=typeof t==`string`?zs(t):t;Ns(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):Hs(e,{pathname:p});Ps(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Ps(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=dl(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:gc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:gc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?X.createElement(Rc.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function al(){let e=vl(),t=Sc(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=X.createElement(X.Fragment,null,X.createElement(`p`,null,`💿 Hey developer 👋`),X.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,X.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,X.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),X.createElement(X.Fragment,null,X.createElement(`h2`,null,`Unexpected Application Error!`),X.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?X.createElement(`pre`,{style:i},n):null,o)}var ol=X.createElement(al,null),sl=class extends X.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=Gc(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:X.createElement(zc.Provider,{value:this.props.routeContext},X.createElement(Bc.Provider,{value:e,children:this.props.component}));return this.context?X.createElement(ll,{error:e},t):t}};sl.contextType=Mc;var cl=new WeakMap;function ll({children:e,error:t}){let{basename:n}=X.useContext(Lc);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Wc(t.digest);if(e){let r=cl.get(t);if(r)throw r;let i=Tc(e.location,n),a=i.absoluteURL||i.to;if(kc(a))throw Error(`Invalid redirect location`);if(wc&&!cl.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw cl.set(t,n),n}}return X.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function ul({routeContext:e,match:t,children:n}){let r=X.useContext(Ac);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),X.createElement(zc.Provider,{value:e},n)}function dl(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);Ns(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Cc(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||ol,o&&(s<0&&c===0?(xl(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?X.createElement(n.route.Component,null):n.route.element?n.route.element:e,X.createElement(ul,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?X.createElement(sl,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function fl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function pl(e){let t=X.useContext(Ac);return Ns(t,fl(e)),t}function ml(e){let t=X.useContext(jc);return Ns(t,fl(e)),t}function hl(e){let t=X.useContext(zc);return Ns(t,fl(e)),t}function gl(e){let t=hl(e),n=t.matches[t.matches.length-1];return Ns(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function _l(){return gl(`useRouteId`)}function vl(){let e=X.useContext(Bc),t=ml(`useRouteError`),n=gl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function yl(){let{router:e}=pl(`useNavigate`),t=gl(`useNavigate`),n=X.useRef(!1);return Xc(()=>{n.current=!0}),X.useCallback(async(r,i={})=>{Ps(n.current,Yc),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var bl={};function xl(e,t,n){!t&&!bl[e]&&(bl[e]=!0,Ps(!1,n))}X.memo(Sl);function Sl({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return il(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Cl({to:e,replace:t,state:n,relative:r}){Ns(qc(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=X.useContext(Lc);Ps(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=X.useContext(zc),{pathname:o}=Jc(),s=Zc(),c=mc(e,pc(a),o,r===`path`),l=JSON.stringify(c);return X.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function wl(e){return el(e.context)}function Tl(e){Ns(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function El({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Ns(!qc(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=X.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=zs(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=X.useMemo(()=>{let e=cc(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return Ps(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:X.createElement(Lc.Provider,{value:c},X.createElement(Rc.Provider,{children:t,value:h}))}function Dl({children:e,location:t}){return rl(Ol(e),t)}X.Component;function Ol(e,t=[]){let n=[];return X.Children.forEach(e,(e,r)=>{if(!X.isValidElement(e))return;let i=[...t,r];if(e.type===X.Fragment){n.push.apply(n,Ol(e.props.children,i));return}Ns(e.type===Tl,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Ns(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=Ol(e.props.children,i)),n.push(a)}),n}var kl=`get`,Al=`application/x-www-form-urlencoded`;function jl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Ml(e){return jl(e)&&e.tagName.toLowerCase()===`button`}function Nl(e){return jl(e)&&e.tagName.toLowerCase()===`form`}function Pl(e){return jl(e)&&e.tagName.toLowerCase()===`input`}function Fl(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Il(e,t){return e.button===0&&(!t||t===`_self`)&&!Fl(e)}function Ll(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function Rl(e,t){let n=Ll(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var zl=null;function Bl(){if(zl===null)try{new FormData(document.createElement(`form`),0),zl=!1}catch{zl=!0}return zl}var Vl=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Hl(e){return e!=null&&!Vl.has(e)?(Ps(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Al}"`),null):e}function Ul(e,t){let n,r,i,a,o;if(Nl(e)){let o=e.getAttribute(`action`);r=o?cc(o,t):null,n=e.getAttribute(`method`)||kl,i=Hl(e.getAttribute(`enctype`))||Al,a=new FormData(e)}else if(Ml(e)||Pl(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?cc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||kl,i=Hl(e.getAttribute(`formenctype`))||Hl(o.getAttribute(`enctype`))||Al,a=new FormData(o,e),!Bl()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(jl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=kl,r=null,i=Al,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function Wl(e,t){if(e===!1||e==null)throw Error(t)}function Gl(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return i.pathname=n?i.pathname.endsWith(`/`)?`${i.pathname}_.${r}`:`${i.pathname}.${r}`:i.pathname===`/`?`_root.${r}`:t&&cc(i.pathname,t)===`/`?`${_c(t)}/_root.${r}`:`${_c(i.pathname)}.${r}`,i}async function Kl(e,t){if(e.id in t)return t[e.id];try{let n=await m(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function ql(e){return e!=null&&typeof e.page==`string`}function Jl(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function Yl(e,t,n){return eu((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Kl(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Jl).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Xl(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function Zl(e,t,{includeHydrateFallback:n}={}){return Ql(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function Ql(e){return[...new Set(e)]}function $l(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function eu(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!ql(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify($l(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function tu(){let e=X.useContext(Ac);return Wl(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function nu(){let e=X.useContext(jc);return Wl(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var ru=X.createContext(void 0);ru.displayName=`FrameworkContext`;function iu(){let e=X.useContext(ru);return Wl(e,`You must render this element inside a <HydratedRouter> element`),e}function au(e,t){let n=X.useContext(ru),[r,i]=X.useState(!1),[a,o]=X.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=X.useRef(null);X.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),X.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:ou(s,p),onBlur:ou(c,m),onMouseEnter:ou(l,p),onMouseLeave:ou(u,m),onTouchStart:ou(d,p)}]:[a,f,{}]:[!1,f,{}]}function ou(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function su({page:e,...t}){let n=Nc(),{nonce:r}=iu(),{router:i}=tu(),a=X.useMemo(()=>Hs(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?X.createElement(lu,{page:e,matches:a,...t}):X.createElement(uu,{page:e,matches:a,...t})):null}function cu(e){let{manifest:t,routeModules:n}=iu(),[r,i]=X.useState([]);return X.useEffect(()=>{let r=!1;return Yl(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function lu({page:e,matches:t,...n}){let r=Jc(),{future:i}=iu(),{basename:a}=tu(),o=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=Gl(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return X.createElement(X.Fragment,null,o.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function uu({page:e,matches:t,...n}){let r=Jc(),{future:i,manifest:a,routeModules:o}=iu(),{basename:s}=tu(),{loaderData:c,matches:l}=nu(),u=X.useMemo(()=>Xl(e,t,l,a,r,`data`),[e,t,l,a,r]),d=X.useMemo(()=>Xl(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=Gl(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=X.useMemo(()=>Zl(d,a),[d,a]),m=cu(d);return X.createElement(X.Fragment,null,f.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>X.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>X.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function du(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}X.Component;var fu=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{fu&&(window.__reactRouterVersion=`7.18.2`)}catch{}function pu({basename:e,children:t,useTransitions:n,window:r}){let i=X.useRef();i.current??=Ms({window:r,v5Compat:!0});let a=i.current,[o,s]=X.useState({action:a.action,location:a.location}),c=X.useCallback(e=>{n===!1?s(e):X.startTransition(()=>s(e))},[n]);return X.useLayoutEffect(()=>a.listen(c),[a,c]),X.createElement(El,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var mu=X.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=X.useContext(Lc),v=typeof l==`string`&&Es.test(l),y=Tc(l,h);l=y.to;let b=Kc(l,{relative:r}),x=Jc(),S=null;if(o){let e=mc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:gc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=au(n,p),E=yu(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=X.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:du(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?X.createElement(X.Fragment,null,k,X.createElement(su,{page:b})):k});mu.displayName=`Link`;var hu=X.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=nl(a,{relative:c.relative}),d=Jc(),f=X.useContext(jc),{navigator:p,basename:m}=X.useContext(Lc),h=f!=null&&Tu(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=cc(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return X.createElement(mu,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});hu.displayName=`NavLink`;var gu=X.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=kl,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=X.useContext(Lc),g=Cu(),_=wu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Es.test(s);return X.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?X.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});gu.displayName=`Form`;function _u(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function vu(e){let t=X.useContext(Ac);return Ns(t,_u(e)),t}function yu(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Zc(),d=Jc(),f=nl(e,{relative:o});return X.useCallback(p=>{if(Il(p,t)){p.preventDefault();let t=n===void 0?Rs(d)===Rs(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?X.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function bu(e){Ps(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=X.useRef(Ll(e)),n=X.useRef(!1),r=Jc(),i=X.useMemo(()=>Rl(r.search,n.current?null:t.current),[r.search]),a=Zc();return[i,X.useCallback((e,t)=>{let r=Ll(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var xu=0,Su=()=>`__${String(++xu)}__`;function Cu(){let{router:e}=vu(`useSubmit`),{basename:t}=X.useContext(Lc),n=_l(),r=e.fetch,i=e.navigate;return X.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Ul(e,t);if(a.navigate===!1){let e=a.fetcherKey||Su();await r(e,n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync})}else await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function wu(e,{relative:t}={}){let{basename:n}=X.useContext(Lc),r=X.useContext(zc);Ns(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...nl(e||`.`,{relative:t})},o=Jc();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:gc([n,a.pathname])),Rs(a)}function Tu(e,{relative:t}={}){let n=X.useContext(Pc);Ns(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=vu(`useViewTransitionState`),i=nl(e,{relative:t});if(!n.isTransitioning)return!1;let a=cc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=cc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return ic(i.pathname,o)!=null||ic(i.pathname,a)!=null}var Z=f(),Eu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Qn,{ref:n,className:K(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Eu.displayName=Qn.displayName;var Du=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-lg border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Du.displayName=`Card`;var Ou=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Ou.displayName=`CardHeader`;var ku=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));ku.displayName=`CardTitle`;var Au=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));Au.displayName=`CardDescription`;var ju=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));ju.displayName=`CardContent`;var Mu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Mu.displayName=`CardFooter`;var Nu=`2.14.15`,Pu=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Fu(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Pu(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`),Pu(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Iu=`session.open`,Lu=`session.set`,Ru=`session.ids`,zu=`session.materialize`,Bu=`session.close`,Vu=`session.delta`;function Hu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.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 Uu=`https://github.com/canvas-ui/canvas-server`,Wu=null;function Gu(){return Wu||=Y.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||Uu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Wu=null,{sourceUrl:Uu,version:null,commit:null,license:null})),Wu}function Ku(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return Gu().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function qu({className:e=``}){let t=Ku();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.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,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function Ju({children:e}){Fu(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Hu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(Du,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(mu,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Nu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.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,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.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,Z.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,Z.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,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(qu,{className:`mt-4 text-center`})]})]})})]})})}function Yu(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var Xu=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=si,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||Yu();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=$a(this.baseUrl,{transports:[`websocket`],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.5,timeout:1e4,forceNew:!0,extraHeaders:{Authorization:`Bearer ${t}`,"X-Connection-ID":this.connectionId},auth:{token:t}}),this.setupDefaultHandlers(),this.registerHandlers(),this.socket.connect())}cleanupSocket(){this.socket?.removeAllListeners(),this.socket?.disconnect(),this.socket=null,this.connected=!1,this.socketWrappers.clear()}setupDefaultHandlers(){this.socket&&(this.socket.on(`connect`,()=>{this.connected=!0;for(let e of this.desiredSubscriptions)this.socket?.emit(`subscribe`,{channel:e})}),this.socket.on(`disconnect`,()=>{this.connected=!1}),this.socket.on(`connect_error`,()=>{this.connected=!1}))}registerHandlers(){this.socket&&this.handlers.forEach((e,t)=>{e.forEach(e=>{this.attach(t,e)})})}attach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e);if(n||(n=new Map,this.socketWrappers.set(e,n)),n.has(t))return;let r=(...e)=>t(...e);n.set(t,r),this.socket.on(e,r)}detach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e),r=n?.get(t);r&&(this.socket.off(e,r),n?.delete(t),n&&n.size===0&&this.socketWrappers.delete(e))}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);let n=this.handlers.get(e);return n.has(t)?()=>this.off(e,t):(n.add(t),this.socket&&this.attach(e,t),()=>this.off(e,t))}off(e,t){let n=this.handlers.get(e);n&&n.has(t)&&(n.delete(t),n.size===0&&this.handlers.delete(e),this.detach(e,t))}request(e,t,n=1e4){return new Promise((r,i)=>{if(!this.socket||!this.connected){i(Error(`Socket not connected`));return}let a=!1,o=setTimeout(()=>{a||(a=!0,i(Error(`Socket request timed out: ${e}`)))},n);try{this.socket.emit(e,t??{},t=>{a||(a=!0,clearTimeout(o),t?.status===`error`?i(Error(t.message||`${e} failed`)):r(t?.payload??t))})}catch(e){a=!0,clearTimeout(o),i(e instanceof Error?e:Error(String(e)))}})}emit(e,...t){if(e===`subscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.add(e)}else if(e===`unsubscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.delete(e)}if(this.socket&&this.connected)try{this.socket.emit(e,...t)}catch(t){console.error(`Error emitting event ${e}:`,t),this.reconnect()}else this.connect()}disconnect(){this.cleanupSocket(),this.authToken=null,this.desiredSubscriptions.clear()}isConnected(){return this.connected}retryNow(){this.connected||(this.cleanupSocket(),this.connect())}reconnect(){this.connect()}};async function Zu(e,t,n=`auto`){try{let r=await Y.post(Qr.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),Xu.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),Xu.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 Qu(e,t,n){try{return await Y.post(Qr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function $u(e){return e instanceof Error&&/^Network error/i.test(e.message)}function ed(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return br(e).exp*1e3>Date.now()}catch{return!1}}function td(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=br(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 nd(){try{if(!Y.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await Y.get(Qr.me);return console.log(`Current user response:`,e),e&&e?(Xu.isConnected()||Xu.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),$u(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(),Xu.disconnect(),null):null}}function rd(){return Y.isAuthenticated()}async function id(){try{let e=await Y.get(Qr.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 ad(e){try{await Y.post(Qr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var od=e=>e?.strategies?.local?.enabled!==!1,sd=e=>e?.allowUserRegistrations!==!1;function cd(){let e=Zc(),[t,n]=X.useState(!1),[r,i]=X.useState({}),[a,o]=X.useState(null),[s,c]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{rd()&&e(`/workspaces`),id().then(e=>{o(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let l=()=>{let e={};return s.email?/\S+@\S+\.\S+/.test(s.email)||(e.email=`Email is invalid`):e.email=`Email is required`,s.password||(e.password=`Password is required`),i(e),Object.keys(e).length===0},u=e=>{let{name:t,value:n}=e.target;c(e=>({...e,[t]:n}))};async function d(t){if(t.preventDefault(),l()){n(!0);try{console.log(`Attempting login with:`,s.email,`strategy:`,s.strategy);let t=await Zu(s.email,s.password,s.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),i({}),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)}i({password:t})}finally{n(!1)}}}return(0,Z.jsx)(Ju,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:d,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[a?.strategies?.imap?.enabled&&a.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:s.strategy,onChange:u,disabled:t,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,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:t,value:s.email,onChange:u}),r.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:r.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:t,value:s.password,onChange:u}),r.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:r.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:t,children:t?`Signing in...`:`Sign In`}),od(a)&&sd(a)&&(0,Z.jsx)(J,{variant:`outline`,type:`button`,disabled:t,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function ld(){let e=Zc(),{showToast:t}=po(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await id(),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=X.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,Z.jsxs)(Ju,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.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,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(J,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(mu,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(Ju,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await Qu(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,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{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,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(J,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(mu,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.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,Z.jsx)(mu,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(mu,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function ud({className:e=`h-5 w-5`,...t}){return(0,Z.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,Z.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Z.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}function dd({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!rd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await nd();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),$u(e)){n(ed()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),Y.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(ud,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(Cl,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function fd({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.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,Z.jsx)(Cl,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var pd=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})}))})),md=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)}})),hd=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=ce,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=ne,e.setTopLeft=ie,e.setTransform=re,e.sortLayoutItems=L,e.sortLayoutItemsByColRow=ae,e.sortLayoutItemsByRowCol=R,e.synchronizeLayoutWithChildren=oe,e.validateLayout=se,e.withLayoutItem=p;var t=pd(),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=md();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=L(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=L(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)}},F=(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)}},I=(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)}},ee=(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],F(...arguments),arguments.length<=2?void 0:arguments[2])},e:F,se:function(){return ee(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},s:ee,sw:function(){return ee(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])},w:I,nw:function(){return P(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])}};function ne(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function re(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 ie(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 L(e,t){return t===`horizontal`?ae(e):t===`vertical`?R(e):e}function R(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 ae(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 oe(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 se(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 ce(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),gd=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)}})),_d=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),vd=i(((e,t)=>{var n=_d();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}})),yd=i(((e,t)=>{t.exports=vd()()})),bd=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,a)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&r(e,s,{get:()=>t[s],enumerable:!(a=i(t,s))||a.enumerable});return e},f=(e,t,i)=>(i=e==null?{}:n(s(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),p=e=>u(r({},`__esModule`,{value:!0}),e),m={};l(m,{DraggableCore:()=>Se,default:()=>Ce}),t.exports=p(m);var h=f(d()),g=f(yd()),_=f(a()),v=yr();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 F(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function I(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function ee(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 ne(e,t){let n=ie(e,t,`px`);return{[E(`transform`,O)]:n}}function re(e,t){return ie(e,t,``)}function ie({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 L(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function R(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ae(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function oe(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??ae();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
4
|
+
Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=Jc(),d;if(t){let e=typeof t==`string`?zs(t):t;Ns(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):Hs(e,{pathname:p});Ps(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Ps(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=dl(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:gc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:gc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?X.createElement(Rc.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function al(){let e=vl(),t=Sc(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=X.createElement(X.Fragment,null,X.createElement(`p`,null,`💿 Hey developer 👋`),X.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,X.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,X.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),X.createElement(X.Fragment,null,X.createElement(`h2`,null,`Unexpected Application Error!`),X.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?X.createElement(`pre`,{style:i},n):null,o)}var ol=X.createElement(al,null),sl=class extends X.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=Gc(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:X.createElement(zc.Provider,{value:this.props.routeContext},X.createElement(Bc.Provider,{value:e,children:this.props.component}));return this.context?X.createElement(ll,{error:e},t):t}};sl.contextType=Mc;var cl=new WeakMap;function ll({children:e,error:t}){let{basename:n}=X.useContext(Lc);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Wc(t.digest);if(e){let r=cl.get(t);if(r)throw r;let i=Tc(e.location,n),a=i.absoluteURL||i.to;if(kc(a))throw Error(`Invalid redirect location`);if(wc&&!cl.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw cl.set(t,n),n}}return X.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function ul({routeContext:e,match:t,children:n}){let r=X.useContext(Ac);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),X.createElement(zc.Provider,{value:e},n)}function dl(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);Ns(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Cc(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||ol,o&&(s<0&&c===0?(xl(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?X.createElement(n.route.Component,null):n.route.element?n.route.element:e,X.createElement(ul,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?X.createElement(sl,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function fl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function pl(e){let t=X.useContext(Ac);return Ns(t,fl(e)),t}function ml(e){let t=X.useContext(jc);return Ns(t,fl(e)),t}function hl(e){let t=X.useContext(zc);return Ns(t,fl(e)),t}function gl(e){let t=hl(e),n=t.matches[t.matches.length-1];return Ns(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function _l(){return gl(`useRouteId`)}function vl(){let e=X.useContext(Bc),t=ml(`useRouteError`),n=gl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function yl(){let{router:e}=pl(`useNavigate`),t=gl(`useNavigate`),n=X.useRef(!1);return Xc(()=>{n.current=!0}),X.useCallback(async(r,i={})=>{Ps(n.current,Yc),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var bl={};function xl(e,t,n){!t&&!bl[e]&&(bl[e]=!0,Ps(!1,n))}X.memo(Sl);function Sl({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return il(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Cl({to:e,replace:t,state:n,relative:r}){Ns(qc(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=X.useContext(Lc);Ps(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=X.useContext(zc),{pathname:o}=Jc(),s=Zc(),c=mc(e,pc(a),o,r===`path`),l=JSON.stringify(c);return X.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function wl(e){return el(e.context)}function Tl(e){Ns(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function El({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Ns(!qc(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=X.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=zs(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=X.useMemo(()=>{let e=cc(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return Ps(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:X.createElement(Lc.Provider,{value:c},X.createElement(Rc.Provider,{children:t,value:h}))}function Dl({children:e,location:t}){return rl(Ol(e),t)}X.Component;function Ol(e,t=[]){let n=[];return X.Children.forEach(e,(e,r)=>{if(!X.isValidElement(e))return;let i=[...t,r];if(e.type===X.Fragment){n.push.apply(n,Ol(e.props.children,i));return}Ns(e.type===Tl,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),Ns(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=Ol(e.props.children,i)),n.push(a)}),n}var kl=`get`,Al=`application/x-www-form-urlencoded`;function jl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Ml(e){return jl(e)&&e.tagName.toLowerCase()===`button`}function Nl(e){return jl(e)&&e.tagName.toLowerCase()===`form`}function Pl(e){return jl(e)&&e.tagName.toLowerCase()===`input`}function Fl(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Il(e,t){return e.button===0&&(!t||t===`_self`)&&!Fl(e)}function Ll(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function Rl(e,t){let n=Ll(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var zl=null;function Bl(){if(zl===null)try{new FormData(document.createElement(`form`),0),zl=!1}catch{zl=!0}return zl}var Vl=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Hl(e){return e!=null&&!Vl.has(e)?(Ps(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Al}"`),null):e}function Ul(e,t){let n,r,i,a,o;if(Nl(e)){let o=e.getAttribute(`action`);r=o?cc(o,t):null,n=e.getAttribute(`method`)||kl,i=Hl(e.getAttribute(`enctype`))||Al,a=new FormData(e)}else if(Ml(e)||Pl(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?cc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||kl,i=Hl(e.getAttribute(`formenctype`))||Hl(o.getAttribute(`enctype`))||Al,a=new FormData(o,e),!Bl()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(jl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=kl,r=null,i=Al,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function Wl(e,t){if(e===!1||e==null)throw Error(t)}function Gl(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return i.pathname=n?i.pathname.endsWith(`/`)?`${i.pathname}_.${r}`:`${i.pathname}.${r}`:i.pathname===`/`?`_root.${r}`:t&&cc(i.pathname,t)===`/`?`${_c(t)}/_root.${r}`:`${_c(i.pathname)}.${r}`,i}async function Kl(e,t){if(e.id in t)return t[e.id];try{let n=await m(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function ql(e){return e!=null&&typeof e.page==`string`}function Jl(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function Yl(e,t,n){return eu((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Kl(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Jl).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Xl(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function Zl(e,t,{includeHydrateFallback:n}={}){return Ql(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function Ql(e){return[...new Set(e)]}function $l(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function eu(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!ql(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify($l(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function tu(){let e=X.useContext(Ac);return Wl(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function nu(){let e=X.useContext(jc);return Wl(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var ru=X.createContext(void 0);ru.displayName=`FrameworkContext`;function iu(){let e=X.useContext(ru);return Wl(e,`You must render this element inside a <HydratedRouter> element`),e}function au(e,t){let n=X.useContext(ru),[r,i]=X.useState(!1),[a,o]=X.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=X.useRef(null);X.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),X.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:ou(s,p),onBlur:ou(c,m),onMouseEnter:ou(l,p),onMouseLeave:ou(u,m),onTouchStart:ou(d,p)}]:[a,f,{}]:[!1,f,{}]}function ou(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function su({page:e,...t}){let n=Nc(),{nonce:r}=iu(),{router:i}=tu(),a=X.useMemo(()=>Hs(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?X.createElement(lu,{page:e,matches:a,...t}):X.createElement(uu,{page:e,matches:a,...t})):null}function cu(e){let{manifest:t,routeModules:n}=iu(),[r,i]=X.useState([]);return X.useEffect(()=>{let r=!1;return Yl(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function lu({page:e,matches:t,...n}){let r=Jc(),{future:i}=iu(),{basename:a}=tu(),o=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=Gl(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return X.createElement(X.Fragment,null,o.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function uu({page:e,matches:t,...n}){let r=Jc(),{future:i,manifest:a,routeModules:o}=iu(),{basename:s}=tu(),{loaderData:c,matches:l}=nu(),u=X.useMemo(()=>Xl(e,t,l,a,r,`data`),[e,t,l,a,r]),d=X.useMemo(()=>Xl(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=Gl(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=X.useMemo(()=>Zl(d,a),[d,a]),m=cu(d);return X.createElement(X.Fragment,null,f.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>X.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>X.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function du(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}X.Component;var fu=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{fu&&(window.__reactRouterVersion=`7.18.2`)}catch{}function pu({basename:e,children:t,useTransitions:n,window:r}){let i=X.useRef();i.current??=Ms({window:r,v5Compat:!0});let a=i.current,[o,s]=X.useState({action:a.action,location:a.location}),c=X.useCallback(e=>{n===!1?s(e):X.startTransition(()=>s(e))},[n]);return X.useLayoutEffect(()=>a.listen(c),[a,c]),X.createElement(El,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var mu=X.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=X.useContext(Lc),v=typeof l==`string`&&Es.test(l),y=Tc(l,h);l=y.to;let b=Kc(l,{relative:r}),x=Jc(),S=null;if(o){let e=mc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:gc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=au(n,p),E=yu(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=X.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:du(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?X.createElement(X.Fragment,null,k,X.createElement(su,{page:b})):k});mu.displayName=`Link`;var hu=X.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=nl(a,{relative:c.relative}),d=Jc(),f=X.useContext(jc),{navigator:p,basename:m}=X.useContext(Lc),h=f!=null&&Tu(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=cc(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return X.createElement(mu,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});hu.displayName=`NavLink`;var gu=X.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=kl,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=X.useContext(Lc),g=Cu(),_=wu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Es.test(s);return X.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?X.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});gu.displayName=`Form`;function _u(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function vu(e){let t=X.useContext(Ac);return Ns(t,_u(e)),t}function yu(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Zc(),d=Jc(),f=nl(e,{relative:o});return X.useCallback(p=>{if(Il(p,t)){p.preventDefault();let t=n===void 0?Rs(d)===Rs(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?X.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function bu(e){Ps(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=X.useRef(Ll(e)),n=X.useRef(!1),r=Jc(),i=X.useMemo(()=>Rl(r.search,n.current?null:t.current),[r.search]),a=Zc();return[i,X.useCallback((e,t)=>{let r=Ll(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var xu=0,Su=()=>`__${String(++xu)}__`;function Cu(){let{router:e}=vu(`useSubmit`),{basename:t}=X.useContext(Lc),n=_l(),r=e.fetch,i=e.navigate;return X.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Ul(e,t);if(a.navigate===!1){let e=a.fetcherKey||Su();await r(e,n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync})}else await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function wu(e,{relative:t}={}){let{basename:n}=X.useContext(Lc),r=X.useContext(zc);Ns(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...nl(e||`.`,{relative:t})},o=Jc();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:gc([n,a.pathname])),Rs(a)}function Tu(e,{relative:t}={}){let n=X.useContext(Pc);Ns(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=vu(`useViewTransitionState`),i=nl(e,{relative:t});if(!n.isTransitioning)return!1;let a=cc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=cc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return ic(i.pathname,o)!=null||ic(i.pathname,a)!=null}var Z=f(),Eu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Qn,{ref:n,className:K(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Eu.displayName=Qn.displayName;var Du=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-lg border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Du.displayName=`Card`;var Ou=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Ou.displayName=`CardHeader`;var ku=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));ku.displayName=`CardTitle`;var Au=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));Au.displayName=`CardDescription`;var ju=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));ju.displayName=`CardContent`;var Mu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Mu.displayName=`CardFooter`;var Nu=`2.14.16`,Pu=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Fu(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Pu(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`),Pu(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Iu=`session.open`,Lu=`session.set`,Ru=`session.ids`,zu=`session.materialize`,Bu=`session.close`,Vu=`session.delta`;function Hu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.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 Uu=`https://github.com/canvas-ui/canvas-server`,Wu=null;function Gu(){return Wu||=Y.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||Uu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Wu=null,{sourceUrl:Uu,version:null,commit:null,license:null})),Wu}function Ku(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return Gu().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function qu({className:e=``}){let t=Ku();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.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,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function Ju({children:e}){Fu(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Hu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(Du,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(mu,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Nu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.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,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.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,Z.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,Z.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,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(qu,{className:`mt-4 text-center`})]})]})})]})})}function Yu(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var Xu=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=si,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||Yu();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=$a(this.baseUrl,{transports:[`websocket`],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.5,timeout:1e4,forceNew:!0,extraHeaders:{Authorization:`Bearer ${t}`,"X-Connection-ID":this.connectionId},auth:{token:t}}),this.setupDefaultHandlers(),this.registerHandlers(),this.socket.connect())}cleanupSocket(){this.socket?.removeAllListeners(),this.socket?.disconnect(),this.socket=null,this.connected=!1,this.socketWrappers.clear()}setupDefaultHandlers(){this.socket&&(this.socket.on(`connect`,()=>{this.connected=!0;for(let e of this.desiredSubscriptions)this.socket?.emit(`subscribe`,{channel:e})}),this.socket.on(`disconnect`,()=>{this.connected=!1}),this.socket.on(`connect_error`,()=>{this.connected=!1}))}registerHandlers(){this.socket&&this.handlers.forEach((e,t)=>{e.forEach(e=>{this.attach(t,e)})})}attach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e);if(n||(n=new Map,this.socketWrappers.set(e,n)),n.has(t))return;let r=(...e)=>t(...e);n.set(t,r),this.socket.on(e,r)}detach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e),r=n?.get(t);r&&(this.socket.off(e,r),n?.delete(t),n&&n.size===0&&this.socketWrappers.delete(e))}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);let n=this.handlers.get(e);return n.has(t)?()=>this.off(e,t):(n.add(t),this.socket&&this.attach(e,t),()=>this.off(e,t))}off(e,t){let n=this.handlers.get(e);n&&n.has(t)&&(n.delete(t),n.size===0&&this.handlers.delete(e),this.detach(e,t))}request(e,t,n=1e4){return new Promise((r,i)=>{if(!this.socket||!this.connected){i(Error(`Socket not connected`));return}let a=!1,o=setTimeout(()=>{a||(a=!0,i(Error(`Socket request timed out: ${e}`)))},n);try{this.socket.emit(e,t??{},t=>{a||(a=!0,clearTimeout(o),t?.status===`error`?i(Error(t.message||`${e} failed`)):r(t?.payload??t))})}catch(e){a=!0,clearTimeout(o),i(e instanceof Error?e:Error(String(e)))}})}emit(e,...t){if(e===`subscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.add(e)}else if(e===`unsubscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.delete(e)}if(this.socket&&this.connected)try{this.socket.emit(e,...t)}catch(t){console.error(`Error emitting event ${e}:`,t),this.reconnect()}else this.connect()}disconnect(){this.cleanupSocket(),this.authToken=null,this.desiredSubscriptions.clear()}isConnected(){return this.connected}retryNow(){this.connected||(this.cleanupSocket(),this.connect())}reconnect(){this.connect()}};async function Zu(e,t,n=`auto`){try{let r=await Y.post(Qr.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),Xu.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),Xu.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 Qu(e,t,n){try{return await Y.post(Qr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function $u(e){return e instanceof Error&&/^Network error/i.test(e.message)}function ed(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return br(e).exp*1e3>Date.now()}catch{return!1}}function td(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=br(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 nd(){try{if(!Y.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await Y.get(Qr.me);return console.log(`Current user response:`,e),e&&e?(Xu.isConnected()||Xu.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),$u(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(),Xu.disconnect(),null):null}}function rd(){return Y.isAuthenticated()}async function id(){try{let e=await Y.get(Qr.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 ad(e){try{await Y.post(Qr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var od=e=>e?.strategies?.local?.enabled!==!1,sd=e=>e?.allowUserRegistrations!==!1;function cd(){let e=Zc(),[t,n]=X.useState(!1),[r,i]=X.useState({}),[a,o]=X.useState(null),[s,c]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{rd()&&e(`/workspaces`),id().then(e=>{o(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let l=()=>{let e={};return s.email?/\S+@\S+\.\S+/.test(s.email)||(e.email=`Email is invalid`):e.email=`Email is required`,s.password||(e.password=`Password is required`),i(e),Object.keys(e).length===0},u=e=>{let{name:t,value:n}=e.target;c(e=>({...e,[t]:n}))};async function d(t){if(t.preventDefault(),l()){n(!0);try{console.log(`Attempting login with:`,s.email,`strategy:`,s.strategy);let t=await Zu(s.email,s.password,s.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),i({}),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)}i({password:t})}finally{n(!1)}}}return(0,Z.jsx)(Ju,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:d,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[a?.strategies?.imap?.enabled&&a.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:s.strategy,onChange:u,disabled:t,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,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:t,value:s.email,onChange:u}),r.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:r.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:t,value:s.password,onChange:u}),r.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:r.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:t,children:t?`Signing in...`:`Sign In`}),od(a)&&sd(a)&&(0,Z.jsx)(J,{variant:`outline`,type:`button`,disabled:t,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function ld(){let e=Zc(),{showToast:t}=po(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await id(),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=X.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,Z.jsxs)(Ju,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.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,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(J,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(mu,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(Ju,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await Qu(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,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{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,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Eu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(J,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(mu,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.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,Z.jsx)(mu,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(mu,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function ud({className:e=`h-5 w-5`,...t}){return(0,Z.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,Z.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Z.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}function dd({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!rd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await nd();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),$u(e)){n(ed()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),Y.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(ud,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(Cl,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function fd({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.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,Z.jsx)(Cl,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var pd=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})}))})),md=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)}})),hd=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=ce,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=ne,e.setTopLeft=ie,e.setTransform=re,e.sortLayoutItems=L,e.sortLayoutItemsByColRow=ae,e.sortLayoutItemsByRowCol=R,e.synchronizeLayoutWithChildren=oe,e.validateLayout=se,e.withLayoutItem=p;var t=pd(),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=md();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=L(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=L(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)}},F=(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)}},I=(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)}},ee=(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],F(...arguments),arguments.length<=2?void 0:arguments[2])},e:F,se:function(){return ee(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},s:ee,sw:function(){return ee(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])},w:I,nw:function(){return P(arguments.length<=0?void 0:arguments[0],I(...arguments),arguments.length<=2?void 0:arguments[2])}};function ne(e,t,n,r){let i=te[e];return i?i(t,a(a({},t),n),r):n}function re(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 ie(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 L(e,t){return t===`horizontal`?ae(e):t===`vertical`?R(e):e}function R(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 ae(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 oe(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 se(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 ce(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),gd=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)}})),_d=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),vd=i(((e,t)=>{var n=_d();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}})),yd=i(((e,t)=>{t.exports=vd()()})),bd=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,a)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&r(e,s,{get:()=>t[s],enumerable:!(a=i(t,s))||a.enumerable});return e},f=(e,t,i)=>(i=e==null?{}:n(s(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),p=e=>u(r({},`__esModule`,{value:!0}),e),m={};l(m,{DraggableCore:()=>Se,default:()=>Ce}),t.exports=p(m);var h=f(d()),g=f(yd()),_=f(a()),v=yr();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 F(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function I(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function ee(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 ne(e,t){let n=ie(e,t,`px`);return{[E(`transform`,O)]:n}}function re(e,t){return ie(e,t,``)}function ie({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 L(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function R(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ae(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function oe(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??ae();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
5
5
|
`,n.innerHTML+=`.react-draggable-transparent-selection *::selection {all: inherit;}
|
|
6
6
|
`,e.getElementsByTagName(`head`)[0].appendChild(n)}e.body&&z(e.body,`react-draggable-transparent-selection`)}function se(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{ce(e)}):ce(e)}function ce(e){if(e)try{e.body&&le(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 z(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function le(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function ue(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:_e(r);let i=ve(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:ee(a)-F(i)-i.offsetLeft+S(s.paddingRight)-S(o.marginRight),bottom:I(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 de(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function fe(e){return e.props.axis===`both`||e.props.axis===`x`}function pe(e){return e.props.axis===`both`||e.props.axis===`y`}function me(e,t,n){let r=typeof t==`number`?L(e,t):null;if(typeof t==`number`&&!r)return null;let i=ve(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return te(r||e,a,n.props.scale)}function he(e,t,n){let r=!x(e.lastX),i=ve(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 ge(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 _e(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function ve(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var ye=f(d()),B=f(yd()),be=f(a()),V=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},xe={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},H=xe.mouse,Se=class extends ye.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=R(e);this.touchIdentifier=r;let i=me(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=he(this,a,o);V(`DraggableCore: handleDragStart: %j`,s),V(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&oe(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,H.move,this.handleDrag),M(n,H.stop,this.handleDragStop))},this.handleDrag=e=>{let t=me(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]=de(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=he(this,n,r);if(V(`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=me(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]=de(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=he(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&se(a.ownerDocument),V(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(V(`DraggableCore: Removing handlers`),N(a.ownerDocument,H.move,this.handleDrag),N(a.ownerDocument,H.stop,this.handleDragStop))},this.onMouseDown=e=>(H=xe.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(H=xe.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(H=xe.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(H=xe.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,xe.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,xe.mouse.move,this.handleDrag),N(t,xe.touch.move,this.handleDrag),N(t,xe.mouse.stop,this.handleDragStop),N(t,xe.touch.stop,this.handleDragStop),N(e,xe.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&se(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=be.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(V(`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 ye.cloneElement(ye.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};Se.displayName=`DraggableCore`,Se.propTypes={allowAnyClick:B.default.bool,allowMobileScroll:B.default.bool,children:B.default.node.isRequired,disabled:B.default.bool,enableUserSelectHack:B.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:B.default.arrayOf(B.default.number),handle:B.default.string,cancel:B.default.string,nodeRef:B.default.object,nonce:B.default.string,onStart:B.default.func,onDrag:B.default.func,onStop:B.default.func,onMouseDown:B.default.func,scale:B.default.number,className:C,style:C,transform:C},Se.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var Ce=class extends h.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(V(`Draggable: onDragStart: %j`,t),this.props.onStart(e,ge(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;V(`Draggable: onDrag: %j`,t);let n=ge(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]=ue(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,ge(this,t))===!1)return!1;V(`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)?(V(`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,m=s||r,g={x:fe(this)&&p?this.state.x:m.x,y:pe(this)&&p?this.state.y:m.y};this.state.isElementSVG?f=re(g,c):d=ne(g,c);let _=h.Children.only(n),y=(0,v.clsx)(_.props.className||``,i,{[a]:this.state.dragging,[o]:this.state.dragged});return h.createElement(Se,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},h.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};Ce.displayName=`Draggable`,Ce.propTypes={...Se.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},Ce.defaultProps={...Se.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:Se})})),xd=i(((e,t)=>{var n=bd(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),Sd=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)}})),Cd=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(yd());xd();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)}}})),wd=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=xd(),r=Sd(),i=Cd(),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}})),Td=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(yd()),r=o(wd()),i=Cd(),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})})),Ed=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=wd().default,t.exports.ResizableBox=Td().default})),Dd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(yd()),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&&hd().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}})),Od=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=f(d()),n=a(),r=f(yd()),i=xd(),o=Ed(),s=hd(),c=gd(),l=Dd(),u=f(yr());function f(e){return e&&e.__esModule?e:{default:e}}function p(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 m(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?p(Object(n),!0).forEach(function(t){h(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):p(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function h(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),h(this,`state`,{resizing:null,dragging:null,className:``}),h(this,`elementRef`,t.default.createRef()),h(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 s=o.getBoundingClientRect(),l=n.getBoundingClientRect(),u=l.left/i,d=s.left/i,f=l.top/i,p=s.top/i;a.left=u-d+o.scrollLeft,a.top=f-p+o.scrollTop,this.setState({dragging:a});let{x:m,y:h}=(0,c.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})}),h(this,`onDrag`,(e,t,r)=>{let{node:i,deltaX:a,deltaY:o}=t,{onDrag:s}=this.props;if(!s)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,c.calcGridItemWHPx)(m,n,t[1]);l=(0,c.clamp)(l,0,r);let i=(0,c.calcGridColWidth)(g),a=h-(0,c.calcGridItemWHPx)(p,i,t[0]);u=(0,c.clamp)(u,0,a)}}let _={top:l,left:u};r?this.setState({dragging:_}):(0,n.flushSync)(()=>{this.setState({dragging:_})});let{x:v,y}=(0,c.calcXY)(g,l,u,p,m);return s.call(this,f,v,y,{e,node:i,newPosition:_})}),h(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:s,top:l}=this.state.dragging,u={top:l,left:s};this.setState({dragging:null});let{x:d,y:f}=(0,c.calcXY)(this.getPositionParams(),l,s,i,a);return r.call(this,o,d,f,{e,node:n,newPosition:u})}),h(this,`onResizeStop`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStop`)),h(this,`onResizeStart`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStart`)),h(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,c.calcGridItemPosition)(this.getPositionParams(this.props),this.props.x,this.props.y,this.props.w,this.props.h,this.state),r=(0,c.calcGridItemPosition)(this.getPositionParams(e),e.x,e.y,e.w,e.h,t);return!(0,s.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,s.setTransform)(e):(i=(0,s.setTopLeft)(e),t&&(i.left=(0,s.perc)(e.left/n),i.width=(0,s.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:a,minH:s,maxW:l,maxH:u,transformScale:d,resizeHandles:f,resizeHandle:p}=this.props,m=this.getPositionParams(),h=(0,c.calcGridItemPosition)(m,0,0,i,0).width,g=(0,c.calcGridItemPosition)(m,0,0,a,s),_=(0,c.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(o.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:o,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=o;a&&(y=(0,s.resizeItemInDirection)(l,r,o,g),(0,n.flushSync)(()=>{this.setState({resizing:i===`onResizeStop`?null:y})}));let{w:b,h:x}=(0,c.calcWH)(this.getPositionParams(),y.width,y.height,d,f,l);b=(0,c.clamp)(b,Math.max(_,1),v),x=(0,c.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:s,useCSSTransforms:l}=this.props,d=(0,c.calcGridItemPosition)(this.getPositionParams(),e,n,r,i,this.state),f=t.default.Children.only(this.props.children),p=t.default.cloneElement(f,{ref:this.elementRef,className:(0,u.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:!!s,cssTransforms:l}),style:m(m(m({},this.props.style),f.props.style),this.createStyle(d))});return p=this.mixinResizable(p,d,o),p=this.mixinDraggable(p,a),p}};e.default=v,h(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:l.resizeHandleAxesType,resizeHandle:l.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})}),h(v,`defaultProps`,{className:``,cancel:``,handle:``,minH:1,minW:1,maxH:1/0,maxW:1/0,transformScale:1})})),kd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=pd(),r=c(yr()),i=hd(),a=gd(),o=c(Od()),s=c(Dd());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})})),Ad=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=hd();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]})}})),jd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(yd()),r=pd(),i=hd(),a=Ad(),o=c(kd()),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})})),Md=r({default:()=>cf});function Nd(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){Kd(a)}function s(){var e=Date.now();if(n){if(e-i<qd)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function Pd(e){return parseFloat(e)||0}function Fd(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+Pd(r)},0)}function Id(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]=Pd(o)}return n}function Ld(e){var t=e.getBBox();return Hd(0,0,t.width,t.height)}function Rd(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return ef;var r=$d(e).getComputedStyle(e),i=Id(r),a=i.left+i.right,o=i.top+i.bottom,s=Pd(r.width),c=Pd(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=Fd(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=Fd(r,`top`,`bottom`)+o)),!zd(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 Hd(i.left,i.top,s,c)}function zd(e){return e===$d(e).document.documentElement}function Bd(e){return Wd?tf(e)?Ld(e):Rd(e):ef}function Vd(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return Qd(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function Hd(e,t,n,r){return{x:e,y:t,width:n,height:r}}var Ud,Wd,Gd,Kd,qd,Jd,Yd,Xd,Zd,Qd,$d,ef,tf,nf,rf,af,of,sf,cf,lf=t((()=>{Ud=(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}()})(),Wd=typeof window<`u`&&typeof document<`u`&&window.document===document,Gd=(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`)()})(),Kd=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(Gd):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),qd=2,Jd=20,Yd=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],Xd=typeof MutationObserver<`u`,Zd=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=Nd(this.refresh.bind(this),Jd)}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(){!Wd||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),Xd?(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(){!Wd||!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;Yd.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),Qd=(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}),$d=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||Gd}),ef=Hd(0,0,0,0),tf=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof $d(e).SVGGraphicsElement}:function(e){return e instanceof $d(e).SVGElement&&typeof e.getBBox==`function`}})(),nf=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=Hd(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=Bd(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}(),rf=function(){function e(e,t){var n=Vd(t);Qd(this,{target:e,contentRect:n})}return e}(),af=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new Ud,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 $d(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new nf(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 $d(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 rf(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}(),of=typeof WeakMap<`u`?new WeakMap:new Ud,sf=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 af(t,Zd.getInstance(),this);of.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){sf.prototype[e]=function(){var t;return(t=of.get(this))[e].apply(t,arguments)}}),cf=(function(){return Gd.ResizeObserver===void 0?sf:Gd.ResizeObserver})()})),uf=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(yd()),i=s((lf(),e(Md))),a=s(yr()),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}})),df=n(i(((e,t)=>{t.exports=kd().default,t.exports.utils=hd(),t.exports.calculateUtils=gd(),t.exports.Responsive=jd().default,t.exports.Responsive.utils=Ad(),t.exports.WidthProvider=uf().default}))(),1),ff=new Map;function pf(e){ff.set(e.type,e)}function mf(e){return ff.get(e)}function hf(){return[...ff.values()]}function gf(){let e,t,n=!1,r=()=>{clearTimeout(e),e=void 0,t=void 0};return{cancel:r,start(i,a,o){r(),n=!1,t={x:i,y:a},e=setTimeout(()=>{e=void 0,n=!0,o()},500)},move(e,n){t&&Math.hypot(e-t.x,n-t.y)>10&&r()},consumeClick(){let e=n;return n=!1,e},contextMenu(){let e=n;return t&&(n=!0),r(),e},reset(){r(),n=!1}}}function _f(){let[e]=(0,X.useState)(gf);return(0,X.useEffect)(()=>e.cancel,[e]),{onPointerDown:t=>{if(e.reset(),t.pointerType!==`touch`||!t.isPrimary)return;let n=t.target;if(!t.currentTarget.contains(n)||n.closest(`button, input, textarea, select, a, [contenteditable="true"], [role="dialog"]`))return;let{clientX:r,clientY:i}=t;e.start(r,i,()=>{n.dispatchEvent(new window.MouseEvent(`contextmenu`,{bubbles:!0,cancelable:!0,clientX:r,clientY:i}))})},onPointerMove:t=>e.move(t.clientX,t.clientY),onPointerUp:e.cancel,onPointerCancel:e.cancel,onPointerLeave:e.cancel,onDragStartCapture:t=>{e.cancel(),e.consumeClick()&&t.preventDefault()},onContextMenuCapture:t=>{t.isTrusted&&e.contextMenu()&&(t.preventDefault(),t.stopPropagation())},onClickCapture:t=>{e.consumeClick()&&(t.preventDefault(),t.stopPropagation())}}}function vf(e,t,n,r,i=!1){let a=e.indexOf(n);if(a<0)return new Set(r);let o=t===null?-1:e.indexOf(t),s=o<0?a:o,c=i?new Set(r):new Set;for(let t of e.slice(Math.min(s,a),Math.max(s,a)+1))c.add(t);return c}var yf=n(a(),1),bf=[];function xf(e){if(e.key!==`Escape`||e.isComposing||e.defaultPrevented)return;let t=bf[bf.length-1];t&&(e.preventDefault(),t())}function Sf(e,t=!0){let n=(0,X.useRef)(e);(0,X.useEffect)(()=>{n.current=e});let r=t&&!!e;(0,X.useEffect)(()=>{if(!r)return;let e=()=>n.current?.();return bf.push(e),bf.length===1&&window.addEventListener(`keydown`,xf),()=>{let t=bf.indexOf(e);t>=0&&bf.splice(t,1),bf.length===0&&window.removeEventListener(`keydown`,xf)}},[r])}function Cf({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,X.useRef)(null),[o,s]=(0,X.useState)({x:e,y:t});return Sf(n),(0,X.useLayoutEffect)(()=>{let n=a.current;if(!n)return;let{width:r,height:i}=n.getBoundingClientRect();s({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})},[e,t]),(0,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,Z.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:K(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r),children:i})]}),document.body)}var wf=null;function Tf(){return wf||=fetch(`https://api.iconify.design/collection?prefix=ph`).then(e=>e.json()).then(e=>[...e.uncategorized??[],...Object.values(e.categories??{}).flat()].filter(e=>e.endsWith(`-fill`)).map(e=>`ph:${e}`)).catch(()=>(wf=null,[])),wf}async function Ef(e,t=120){let n=e.trim();if(!n)return[];try{let e=await(await fetch(`https://api.iconify.design/search?query=${encodeURIComponent(n)}&limit=${t}`)).json();return Array.isArray(e.icons)?e.icons:[]}catch{return[]}}var Df=[`#ef4444`,`#f97316`,`#f59e0b`,`#eab308`,`#84cc16`,`#22c55e`,`#14b8a6`,`#06b6d4`,`#3b82f6`,`#6366f1`,`#8b5cf6`,`#a855f7`,`#ec4899`,`#f43f5e`,`#64748b`,`#78716c`],Of={home:{icon:`ph:house-fill`,color:`#3b82f6`},travel:{icon:`ph:airplane-tilt-fill`,color:`#06b6d4`},work:{icon:`ph:briefcase-fill`,color:`#64748b`},books:{icon:`ph:books-fill`,color:`#a855f7`},workouts:{icon:`ph:barbell-fill`,color:`#22c55e`},sport:{icon:`ph:barbell-fill`,color:`#22c55e`},sports:{icon:`ph:barbell-fill`,color:`#22c55e`},fitness:{icon:`ph:barbell-fill`,color:`#22c55e`},beauty:{icon:`ph:flower-lotus-fill`,color:`#ec4899`},recipes:{icon:`ph:cooking-pot-fill`,color:`#f97316`},"to watch":{icon:`ph:monitor-play-fill`,color:`#f43f5e`},"to read":{icon:`ph:book-open-text-fill`,color:`#8b5cf6`},learning:{icon:`ph:graduation-cap-fill`,color:`#6366f1`},tech:{icon:`ph:cpu-fill`,color:`#14b8a6`},music:{icon:`ph:music-notes-fill`,color:`#eab308`},finance:{icon:`ph:piggy-bank-fill`,color:`#84cc16`},shopping:{icon:`ph:shopping-cart-fill`,color:`#f59e0b`},ideas:{icon:`ph:lightbulb-filament-fill`,color:`#facc15`},data:{icon:`ph:database-fill`,color:`#14b8a6`}},kf={"workspace:home":{icon:`ph:house-fill`,color:`#3b82f6`},"workspace:data":{icon:`ph:database-fill`,color:`#14b8a6`}},Af={file:{icon:`ph:folder-fill`,color:`#64748b`},cacache:{icon:`ph:database-fill`,color:`#14b8a6`},s3:{icon:`ph:cloud-fill`,color:`#0ea5e9`},gdrive:{icon:`mdi:google-drive`,color:`#fbbc04`},http:{icon:`ph:globe-fill`,color:`#0ea5e9`},imap:{icon:`ph:envelope-fill`,color:`#a855f7`}},jf={icon:`ph:hard-drive-fill`,color:`#64748b`};function Mf(e){let t=e.config?.ui??{},n=e.address&&kf[e.address]||e.driver&&Af[e.driver]||jf;return{icon:typeof t.icon==`string`?t.icon:n.icon??jf.icon,color:typeof t.color==`string`?t.color:n.color??jf.color}}function Nf(e){let t=e.metadata?.ui??{},n=Of[String(e.label??e.name??``).trim().toLowerCase()];return{icon:typeof t.icon==`string`?t.icon:n?.icon,color:typeof t.color==`string`?t.color:e.color??n?.color}}function Pf(e){let t=Of[(e.split(`/`).filter(Boolean).pop()??``).trim().toLowerCase()];return t?{metadata:Ff(void 0,t)}:null}function Ff(e,t){let n={...e??{}},r={...n.ui??{}};return`icon`in t&&(t.icon?r.icon=t.icon:delete r.icon),`color`in t&&(t.color?r.color=t.color:delete r.color),n.ui=r,n}var If=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,Lf=()=>({h:If(0,360),s:If(42,98),l:If(40,90)}),Rf=(e,t,n)=>{t/=100,n/=100;let r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),a=n-r/2,o=0,s=0,c=0;0<=e&&e<60?(o=r,s=i):60<=e&&e<120?(o=i,s=r):120<=e&&e<180?(s=r,c=i):180<=e&&e<240?(s=i,c=r):240<=e&&e<300?(o=i,c=r):300<=e&&e<360&&(o=r,c=i),o=Math.round((o+a)*255),s=Math.round((s+a)*255),c=Math.round((c+a)*255);let l=e=>e.toString(16).padStart(2,`0`);return`#${l(o)}${l(s)}${l(c)}`},zf=()=>{let{h:e,s:t,l:n}=Lf();return Rf(e,t,n)},Bf=e=>{let t=e.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!t)return null;let n=t[1];n.length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=e=>{let t=parseInt(n.slice(e*2,e*2+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(1)+.0722*r(2)},Vf=(e,t=.82)=>{let n=Bf(e);return n===null||n>t},Hf=e=>e&&!Vf(e)?e:void 0,Uf=e=>{if(!e)return`text-muted-foreground/70`;let t=Bf(e);return t!==null&&t>.5?`text-black/45`:`text-white/80`},Wf=e=>{let t=Bf(e);return t!==null&&t>.45?`text-black`:`text-white`},Gf=[{color:`text-data-1`,chip:`bg-data-1/15`},{color:`text-data-2`,chip:`bg-data-2/15`},{color:`text-data-3`,chip:`bg-data-3/15`},{color:`text-data-4`,chip:`bg-data-4/15`},{color:`text-data-5`,chip:`bg-data-5/15`},{color:`text-data-6`,chip:`bg-data-6/15`},{color:`text-data-7`,chip:`bg-data-7/15`},{color:`text-data-8`,chip:`bg-data-8/15`},{color:`text-data-9`,chip:`bg-data-9/15`},{color:`text-data-10`,chip:`bg-data-10/15`},{color:`text-data-11`,chip:`bg-data-11/15`},{color:`text-data-12`,chip:`bg-data-12/15`}];function Kf(e,t){return{Icon:e,...Gf[t-1]}}var qf={tab:Kf(oe,7),link:Kf(oe,7),email:Kf(Cn,3),note:Kf(xn,3),task:Kf(Tn,5),message:Kf(Me,6),identity:Kf(Ze,2),contact:Kf(Ze,2),device:Kf(me,10),application:Kf(et,11),dotfile:Kf(qt,4),document:Kf(wn,9)},Jf=[{test:/^image\//,spec:Kf(y,5)},{test:/^video\//,spec:Kf(tn,11)},{test:/^audio\//,spec:Kf(R,10)},{test:/pdf$/,spec:Kf(wn,1)},{test:/zip|tar|gzip|7z|rar|compressed/,spec:Kf(Nt,12)},{test:/json|javascript|typescript|xml|html|css|x-sh|python/,spec:Kf(Yn,6)},{test:/^text\//,spec:Kf(wn,12)}],Yf=Kf(bt,6),Xf=Kf(bt,9);function Zf(e){let t=(e.schema||``).split(`/`).pop()||``;if(t===`file`){let t=String(e.metadata?.contentType||``).toLowerCase();return Jf.find(({test:e})=>e.test(t))?.spec||Yf}return qf[t]||Xf}var Qf={3.5:`h-3.5 w-3.5`,4:`h-4 w-4`,5:`h-5 w-5`,10:`h-10 w-10`};function $f(e){let t=[],n=typeof e?.favIconUrl==`string`?e.favIconUrl:``;/^https?:\/\//i.test(n)&&t.push(n);let r=typeof e?.url==`string`?e.url:``;try{let e=new URL(r).origin;if(/^https?:/i.test(e)){let n=`${e}/favicon.ico`;t.includes(n)||t.push(n)}}catch{}return t}function ep({document:e,size:t=4,chip:n=!1,className:r}){let i=Zf(e),a=e.schema===`data/schema/tab`?$f(e.data):[],[o,s]=(0,X.useState)(0),c=a[o]??null,l=c?(0,Z.jsx)(`img`,{src:c,alt:``,loading:`lazy`,onError:()=>s(e=>e+1),className:K(Qf[t],`rounded-xs object-contain`,!n&&`shrink-0`,!n&&r)}):(0,Z.jsx)(i.Icon,{className:K(Qf[t],i.color,!n&&`shrink-0`,!n&&r)});return n?(0,Z.jsx)(`span`,{className:K(`inline-flex shrink-0 items-center justify-center rounded-md`,t>=10?`p-3`:`p-1`,i.chip,r),children:l}):l}var tp={context:(0,Z.jsx)(We,{className:`h-3.5 w-3.5`}),directory:(0,Z.jsx)(Mn,{className:`h-3.5 w-3.5`}),backends:(0,Z.jsx)(hr,{className:`h-3.5 w-3.5`}),relations:(0,Z.jsx)(_n,{className:`h-3.5 w-3.5`})},np={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function rp(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function ip(e,t){let n=(0,X.useRef)(null),r=(0,X.useRef)(!1),i=()=>{n.current&&=(clearTimeout(n.current),null)},a=e=>()=>{if(r.current){r.current=!1;return}e()};return t?{guardClick:a,handlers:{onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),t({clientX:n.clientX,clientY:n.clientY,path:e})},onPointerDown:a=>{if(a.pointerType!==`touch`)return;let{clientX:o,clientY:s}=a;i(),n.current=setTimeout(()=>{r.current=!0,t({clientX:o,clientY:s,path:e})},500)},onPointerUp:i,onPointerLeave:i,onPointerMove:i}}:{handlers:{},guardClick:a}}function ap(e,t,n){let r=rp(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>ap(e,r,n))??!1}var op=200;function sp({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,X.useState)(``);return(0,Z.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-md bg-card px-3 py-2.5 text-sm shadow-elevation-1`,children:[(0,Z.jsx)(ir,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:n=>{n.key===`Enter`&&r.trim()&&e(r.trim()),n.key===`Escape`&&t()},onBlur:()=>{n||t()},placeholder:`New folder name…`,autoFocus:!0,disabled:n,className:`w-full flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),n&&(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function cp({node:e,parentPath:t,query:n,selected:r,onToggle:i,onActivate:a,onRowMenu:o,createParent:s,onCreateConfirm:l,onCreateCancel:u,creating:d}){let f=rp(t,e.name),p=!!e.children?.length,[m,h]=(0,X.useState)(!1),{handlers:g,guardClick:_}=ip(f,o);if(n&&!ap(e,t,n))return null;let v=s===f,y=m||n.length>0||v,b=r.has(f),x=e.type===`canvas`,S=Nf(e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,b?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:_(()=>i(f)),onDoubleClick:a?()=>a(f):void 0,title:f,...g,children:[(0,Z.jsx)(`button`,{type:`button`,className:K(`shrink-0 text-muted-foreground hover:text-foreground`,!p&&`invisible`),onClick:e=>{e.stopPropagation(),h(e=>!e)},children:y?(0,Z.jsx)(Ge,{className:`w-4 h-4`}):(0,Z.jsx)(Ye,{className:`w-4 h-4`})}),(0,Z.jsx)(c,{icon:S.icon||(x?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:Hf(S.color),className:K(`shrink-0`,!Hf(S.color)&&(x?`text-primary`:`text-muted-foreground`))}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),y&&p||v?(0,Z.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[v&&l&&u&&(0,Z.jsx)(sp,{busy:d,onConfirm:e=>{h(!0),l(f,e)},onCancel:u}),y&&e.children?.map(e=>(0,Z.jsx)(cp,{node:e,parentPath:f,query:n,selected:r,onToggle:i,onActivate:a,onRowMenu:o,createParent:s,onCreateConfirm:l,onCreateCancel:u,creating:d},e.id||e.name))]}):null]})}function lp({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=Hf(e.color);return(0,Z.jsxs)(`div`,{onClick:()=>n(e.name),className:`group relative flex cursor-pointer items-center gap-2 rounded-md bg-card px-3 py-2.5 shadow-elevation-1 transition-all hover:bg-accent/50 hover:shadow`,style:{borderRight:`6px solid ${t||`transparent`}`,borderRadius:t?`6px 0 0 6px`:void 0},children:[(0,Z.jsx)(c,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:K(`shrink-0`,!t&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,Z.jsx)(Ye,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function up({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:a,excludeDocumentIds:o}){let[s,c]=(0,X.useState)(`folder`),[l,u]=(0,X.useState)(``),d=l.trim().toLowerCase(),[f,p]=(0,X.useState)(`/`),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)([]),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(``),[E,D]=(0,X.useState)(t),O=n?t:E,k=e=>{p(`/`),c(`folder`),C(``),T(``),a?.(`/`),n?n(e):D(e)},[A,j]=(0,X.useState)(O);O!==A&&(j(O),p(`/`),c(`folder`)),(0,X.useEffect)(()=>{let e=setTimeout(()=>T(S.trim()),300);return()=>clearTimeout(e)},[S]),(0,X.useEffect)(()=>{let t=!1;async function n(){_(!0);try{let n=await vi(e,O);t||h(n)}catch{t||h(null)}finally{t||_(!1)}}return n(),()=>{t=!0}},[e,O]),(0,X.useEffect)(()=>{if(s!==`documents`)return;let t=!1,n=O===`directory`?`directory`:Na,r=O===`context`?`context`:`directory`;async function i(){x(!0);try{let i=w?await Ki(e,f,[],{treeName:n,treeType:r,q:w,limit:op}):await Si(e,f,n,{limit:op});t||y(i.payload||[])}catch{t||y([])}finally{t||x(!1)}}return i(),()=>{t=!0}},[e,O,f,s,w]);let M=e=>`${O===`directory`?`dir`:`ctx`}://${e.replace(/^\/+/,``)}`,N=e=>{p(e),a?.(e)},P=o?.size?v.filter(e=>!o.has(e.id)):v;return s===`folder`?(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,Z.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>k(e),className:K(`flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors`,O===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Browse the ${np[e].toLowerCase()}`,children:[tp[e],(0,Z.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>c(`documents`),className:`inline-flex items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90`,children:[`Next `,(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5`})]})]}),(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Filter folders…`,value:l,onChange:e=>u(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:g?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,f===`/`?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:()=>N(`/`),onDoubleClick:()=>{N(`/`),c(`documents`)},title:`/`,children:[(0,Z.jsx)(Ge,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Z.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:m?.children?.length?m.children.map(e=>(0,Z.jsx)(cp,{node:e,parentPath:`/`,query:d,selected:new Set([f]),onToggle:N,onActivate:e=>{N(e),c(`documents`)}},e.id||e.name)):(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>c(`folder`),className:`inline-flex min-w-0 items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Back to folders`,children:[(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,Z.jsx)(`span`,{className:`truncate font-mono`,children:M(f)})]}),(0,Z.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Search documents in this folder…`,value:S,onChange:e=>C(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-7 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),S&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>C(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear document search`,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:b?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):P.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:w?`No documents match “${w}” here.`:`No documents in this folder.`}):P.map(e=>{let t=bo(e),n=r.has(e.id);return(0,Z.jsxs)(`div`,{onClick:()=>i(e.id),className:K(`flex min-h-9 items-center gap-2 rounded-md px-3 py-1.5 cursor-pointer transition-all select-none text-sm`,n?`bg-primary/[0.08] hover:bg-primary/[0.12]`:`hover:bg-primary/[0.04]`),children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,Z.jsx)(ep,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function dp({onClose:e,onConfirm:t,documentCount:n,fixedWorkspaceName:r,excludeWorkspace:i,multiple:a=!0,saving:o=!1,savingContent:s,sizeClassName:c,tabs:l=[`context`,`directory`],title:u,confirmLabel:d,onConfirmRelation:f,relationWorkspaceName:p,relationPredicates:m,relationExcludeIds:h}){let[g,_]=(0,X.useState)(r?`tree`:`workspace`);Sf(e,!o);let[v,y]=(0,X.useState)([]),[b,x]=(0,X.useState)(!r),[S,C]=(0,X.useState)(r??null),[w,T]=(0,X.useState)(l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`),E=m?.length?m:[...Da],[D,O]=(0,X.useState)(E[0]??`references`),[k,A]=(0,X.useState)(`out`),[j,M]=(0,X.useState)(new Set),[N,P]=(0,X.useState)(null),[F,I]=(0,X.useState)(`context`),[ee,te]=(0,X.useState)(!1),re=w===`pins`?F:w;(0,X.useEffect)(()=>{if(!S)return;let e=!1;return qa(S).then(t=>{e||P(t)}).catch(()=>{e||te(!0)}),()=>{e=!0}},[S]);let ie=w===`relations`,[L,R]=(0,X.useState)(null),[ae,oe]=(0,X.useState)(!1),[se,ce]=(0,X.useState)(new Set),[z,le]=(0,X.useState)(``),ue=z.trim().toLowerCase(),{showErrorToast:de}=to(),[fe,pe]=(0,X.useState)(null),[me,he]=(0,X.useState)(null),[ge,_e]=(0,X.useState)(!1),ve=ip(`/`,e=>pe(e)),ye=w!==`pins`&&w!==`backends`&&w!==`relations`,B=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!S||ge||!ye)){_e(!0);try{let t=`${e===`/`?``:e}/${n}`;await Vi(S,t,!0,w===`directory`?`directory`:Na),fa(S);let r=await vi(S,w);R(r),ce(e=>a?new Set([...e,t]):new Set([t])),he(null)}catch(e){de(e instanceof Error?e.message:`Failed to create folder`)}finally{_e(!1)}}},[be,V]=(0,X.useState)(r);r!==be&&(V(r),r||x(!0)),(0,X.useEffect)(()=>{r||Pr().then(e=>y(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>y([])).finally(()=>x(!1))},[r,i]),(0,X.useEffect)(()=>{if(!S||w===`relations`||w===`pins`)return;let e=!1;async function t(){oe(!0);try{let t=await vi(S,w);e||R(t)}catch{e||R(null)}finally{e||oe(!1)}}return t(),()=>{e=!0}},[S,w]);let xe=e=>{e!==S&&(P(null),te(!1)),T(l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`),C(e),ce(new Set),M(new Set),_(`tree`)},H=e=>{M(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Se=e=>{if(!a){ce(new Set([e]));return}ce(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ce=ie?j.size>0&&!!f:se.size>0,U=async()=>{if(!(!S||o||!Ce)){if(ie){await f?.({predicate:D,direction:k,targetIds:Array.from(j)},{workspaceName:p??S});return}await t(Array.from(se),{workspaceName:S,treeName:re===`context`?Na:re,treeType:re===`context`?`context`:`directory`})}},W=n??1;return o&&s?(0,Z.jsx)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:s}):(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Gt,{className:`h-4 w-4`}),u??(g===`workspace`?`Link to…`:ie?`Relate ${W} document${W===1?``:`s`} to…`:`Link ${W} document${W===1?``:`s`} to…`)]}),(0,Z.jsx)(`button`,{type:`button`,onClick:e,disabled:o,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Z.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-200`,style:{transform:g===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Z.jsx)(lp,{workspaces:v,loading:b,onPick:xe})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4 rotate-180`})}),(l.includes(`context`)||l.includes(`directory`))&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{T(`pins`),ce(new Set),he(null)},className:K(`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2 text-xs`,w===`pins`?`border-primary`:`border-transparent text-muted-foreground`),children:[(0,Z.jsx)(ne,{className:`h-3.5 w-3.5`}),`Pins`]}),l.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{T(e),ce(new Set),he(null)},className:K(`flex shrink-0 items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,w===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[tp[e],np[e]]},e))]}),!ie&&(0,Z.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:z,onChange:e=>le(e.target.value),className:`w-full rounded-md border border-input bg-background py-2 pl-9 pr-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})}),ie&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,Z.jsx)(`select`,{id:`relation-predicate`,value:D,onChange:e=>O(e.target.value),className:`min-w-0 flex-1 rounded-md border border-input bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,children:E.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]}),(0,Z.jsx)(`div`,{className:`flex items-center gap-1`,children:[{dir:`out`,label:`This → picked`,hint:`the ${W===1?`document`:`documents`} you started from ${D} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${D} the ${W===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,Z.jsx)(`button`,{type:`button`,title:n,onClick:()=>A(e),className:K(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,k===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!ie&&a&&se.size>0&&(0,Z.jsx)(`div`,{className:`flex shrink-0 flex-wrap gap-1.5 border-b bg-primary/[0.04] px-3 py-2`,children:Array.from(se).map(e=>(0,Z.jsxs)(`span`,{className:`inline-flex max-w-full items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>Se(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]},e))}),ie&&(p??S)&&(0,Z.jsx)(up,{workspaceName:p??S,treeTab:`context`,selectedDocIds:j,onToggleDoc:H,excludeDocumentIds:h}),w===`pins`&&(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!N&&!ee&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),ee&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!ee&&N?.length===0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),N?.filter(e=>e.resolvable!==!1&&l.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(ue)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,Z.jsxs)(`button`,{type:`button`,"aria-pressed":F===t&&se.has(e.path),className:K(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,F===t&&se.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{F===t?Se(e.path):(I(t),ce(new Set([e.path])))},children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(ne,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,Z.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,Z.jsx)(`div`,{className:K(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(ie||w===`pins`)&&`hidden`),children:ae?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,se.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:ve.guardClick(()=>Se(`/`)),title:`/`,...ye?ve.handlers:{},children:[(0,Z.jsx)(Ge,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Z.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[me===`/`&&(0,Z.jsx)(sp,{busy:ge,onConfirm:e=>B(`/`,e),onCancel:()=>he(null)}),L?.children?.length?L.children.map(e=>(0,Z.jsx)(cp,{node:e,parentPath:`/`,query:ue,selected:se,onToggle:Se,onRowMenu:ye?pe:void 0,createParent:me,onCreateConfirm:B,onCreateCancel:()=>he(null),creating:ge},e.id||e.name)):me===`/`?null:(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),g===`tree`&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:ie?`${j.size} document${j.size===1?``:`s`} selected`:`${se.size} path${se.size===1?``:`s`} selected`}),(0,Z.jsx)(J,{size:`sm`,onClick:U,disabled:!Ce||o,children:o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ud,{className:`mr-1.5 h-3.5 w-3.5`}),ie?`Relating…`:`Linking…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Gt,{className:`mr-1 h-3.5 w-3.5`}),ie?`Relate`:d??`Link`]})})]}),fe&&(0,Z.jsx)(Cf,{x:fe.clientX,y:fe.clientY,onClose:()=>pe(null),className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:(0,Z.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 rounded-sm px-3 py-1.5 text-left text-xs hover:bg-accent`,onClick:()=>{he(fe.path),pe(null)},children:[(0,Z.jsx)(ut,{className:`h-3 w-3`}),`New folder in `,fe.path]})})]})}var fp=`h-full w-[380px] max-w-[90vw] max-md:w-full`;function pp({onClose:e,children:t}){return(0,yf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-stretch justify-end bg-scrim animate-fade-in`,onClick:e,children:(0,Z.jsx)(`div`,{className:`h-full p-2 max-md:w-full max-md:p-1`,onClick:e=>e.stopPropagation(),children:t})}),window.document.body)}function mp(e){let t=2166136261;for(let e of localStorage.getItem(`authToken`)||``)t=Math.imul(t^e.charCodeAt(0),16777619);return`canvas:workspace-copy:${t>>>0}:${e}`}function hp({workspaceId:e,ids:t,onClose:n}){let[r]=(0,X.useState)(()=>{try{return mp(e)}catch{return``}}),[i,a]=(0,X.useState)(()=>{try{let e=JSON.parse(localStorage.getItem(r)||`null`);return e&&Array.isArray(e.ids)&&e.target&&e.index<e.ids.length?e:null}catch{return null}}),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(``),u=(0,X.useRef)(!1),d=(0,X.useRef)(!1);(0,X.useEffect)(()=>(u.current=!1,()=>{u.current=!0}),[]);let f=e=>{try{e.index>=e.ids.length?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(e))}catch{}u.current||a(e)},p=async t=>{if(d.current)return;d.current=!0,s(!0),l(``);let n=t;f(n);try{for(;n.index<n.ids.length&&!u.current;){if(!navigator.onLine)throw Error(`Offline. Your copy is saved; resume when connected.`);await Sa(e,n.ids[n.index],{destination:n.target.workspaceName,context:n.paths,treeType:n.target.treeType,treeNameOrTreeId:n.target.treeName,operationId:`${n.id}:${n.index}`}),n={...n,index:n.index+1},f(n)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}catch(e){u.current||l(`Document ${n.ids[n.index]}: ${e instanceof Error?e.message:`Copy failed`}. Resume to retry.`)}finally{d.current=!1,u.current||s(!1)}},m=()=>{u.current=!0,n()},h=i!=null&&i.index>=i.ids.length;return(0,Z.jsx)(pp,{onClose:m,children:i?(0,Z.jsxs)(`section`,{role:`dialog`,"aria-label":`Copy to workspace`,className:`${fp} flex flex-col rounded-2xl border bg-card p-4 shadow-elevation-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,Z.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[i.target.workspaceName,`: `,i.paths.join(`, `)]}),(0,Z.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[i.index,` of `,i.ids.length,` copied`,h?`.`:o?`…`:` — paused.`]}),c&&(0,Z.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:c}),(0,Z.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:`Files go to workspace:data. Destination rules handle storage placement. Relationships and sharing permissions are not copied. Source documents stay unchanged.`}),!h&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Closing lets the current item finish and pauses the rest. Reopen Copy to workspace to resume, including after reconnecting.`}),(0,Z.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!h&&!o&&(0,Z.jsx)(J,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(r)}catch{}a(null),l(``)},children:`Discard remaining`}),!h&&!o&&(0,Z.jsx)(J,{onClick:()=>void p(i),children:`Resume copy`}),(0,Z.jsx)(J,{variant:h?`default`:`outline`,onClick:m,children:h?`Done`:o?`Pause & close`:`Close`})]})]}):(0,Z.jsx)(dp,{title:`Copy to workspace…`,confirmLabel:`Copy documents`,excludeWorkspace:e,documentCount:t.length,sizeClassName:fp,onClose:m,onConfirm:(e,n)=>p({ids:t,target:n,paths:e,index:0,id:crypto.randomUUID()})})})}function gp({tags:e,onChange:t,placeholder:n=`Add tag, press Enter`,suggestions:r=[]}){let[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),c=i.trim().toLowerCase(),l=(c?r.filter(t=>t.toLowerCase().includes(c)&&!e.includes(t)):o?r.filter(t=>!e.includes(t)):[]).slice(0,8),u=()=>{let n=i.trim();n&&!e.includes(n)&&t([...e,n]),a(``)};return(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-2 py-1.5 focus-within:ring-1 focus-within:ring-ring`,children:[e.map(n=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs`,children:[n,(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e.filter(e=>e!==n)),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${n}`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]},n)),(0,Z.jsxs)(`div`,{className:`relative flex-1 min-w-[8ch]`,children:[(0,Z.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:n=>{n.key===`Enter`||n.key===`,`?(n.preventDefault(),u()):n.key===`Backspace`&&!i&&e.length&&t(e.slice(0,-1))},onFocus:()=>s(!0),onBlur:()=>{setTimeout(u,150),s(!1)},placeholder:e.length?``:n,className:`w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),l.length>0&&(0,Z.jsx)(`div`,{className:`absolute left-0 top-full z-50 mt-1 max-h-48 w-56 overflow-auto rounded-md border bg-popover p-1 text-sm shadow-elevation-2`,children:l.map(n=>(0,Z.jsx)(`button`,{type:`button`,onMouseDown:r=>{r.preventDefault(),e.includes(n)||t([...e,n]),a(``)},className:`block w-full rounded px-2 py-1 text-left hover:bg-accent`,children:n},n))})]})]})}function _p(e){let t=new Set;for(let n of e){let e=n.trim();e&&t.add(`tag/${e}`)}return Array.from(t)}function vp(e){return(e||[]).filter(e=>e.startsWith(`tag/`)).map(e=>e.slice(4))}function yp(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],..._p(e.data?.tags??[]),..._p(t)])]}:{},...n?{geo:n}:{}}}function bp(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:yp(e,t,n),...r===void 0?{}:{comment:r.trim()}}}var xp=n(Mo(),1),Sp=`#8b5cf6`,Cp=`https://nominatim.openstreetmap.org`,wp=700,Tp=e=>Math.round(e*1e6)/1e6;function Ep(){let e=`<div style="display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:9999px 9999px 9999px 2px;transform:rotate(-45deg);background:${Sp};border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.45)"><div style="width:8px;height:8px;border-radius:9999px;background:#fff"></div></div>`;return xp.default.divIcon({html:e,className:`canvas-map-pick`,iconSize:[28,28],iconAnchor:[14,28]})}function Dp({initial:e,onPick:t,onClose:n}){let r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.useRef)(null),o=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>o.current?.abort(),[]);let[s,c]=(0,X.useState)(e?{lat:e.lat,lon:e.lon}:null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)([]),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1);(0,X.useEffect)(()=>{let e=requestAnimationFrame(()=>S(!0));return()=>cancelAnimationFrame(e)},[]),Sf(n);let C=(0,X.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let o=xp.default.latLng(e,t);a.current?a.current.setLatLng(o):(a.current=xp.default.marker(o,{icon:Ep(),draggable:!0,autoPan:!0}).addTo(r),a.current.on(`dragend`,()=>{let e=a.current.getLatLng();c({lat:Tp(e.lat),lon:Tp(e.lng)})})),c({lat:Tp(e),lon:Tp(t),...n?{label:n}:{}})},[]);(0,X.useEffect)(()=>{let t=r.current;if(!t||i.current)return;let n=xp.default.map(t,{center:e?[e.lat,e.lon]:[20,0],zoom:e?13:2,worldCopyJump:!0,zoomControl:!0});xp.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(n),i.current=n,e&&C(e.lat,e.lon),n.on(`click`,e=>C(e.latlng.lat,e.latlng.lng));let o=new ResizeObserver(()=>n.invalidateSize());o.observe(t);let s=setTimeout(()=>n.invalidateSize(),260);return()=>{clearTimeout(s),o.disconnect(),n.remove(),i.current=null,a.current=null}},[]),(0,X.useEffect)(()=>{if(!s||s.label)return;let{lat:e,lon:t}=s,n=new AbortController,r=setTimeout(()=>{v(!0),fetch(`${Cp}/reverse?format=jsonv2&zoom=16&lat=${e}&lon=${t}`,{signal:n.signal,headers:{Accept:`application/json`}}).then(e=>e.ok?e.json():null).then(n=>{let r=n?.display_name;typeof r==`string`&&r&&c(n=>n&&n.lat===e&&n.lon===t?{...n,label:r}:n)}).catch(()=>{}).finally(()=>v(!1))},wp);return()=>{clearTimeout(r),n.abort()}},[s]);let w=(0,X.useCallback)(async()=>{let e=l.trim();if(e.length<2)return;o.current?.abort();let t=new AbortController;o.current=t;let n=!1,r=window.setTimeout(()=>{n=!0,t.abort()},12e3);m(!0),f([]),g(null);try{let n=await fetch(`${Cp}/search?format=jsonv2&limit=6&q=${encodeURIComponent(e)}`,{signal:t.signal,headers:{Accept:`application/json`}});if(n.status===429)throw Error(`Place search is busy. Wait a moment and try again, or click the map`);if(!n.ok)throw Error(`Place search is unavailable (${n.status}). Try again, or click the map`);let r=await n.json();if(!Array.isArray(r))throw Error(`Place search returned an invalid response. Try again, or click the map`);if(t.signal.aborted||o.current!==t)return;f(r),r.length||g(`No match. Try a different spelling, or just click the map`)}catch(e){if(o.current!==t||t.signal.aborted&&!n)return;g(n?`Place search timed out. Try again, or click the map`:e instanceof TypeError?`Could not reach place search. Check your connection, or click the map`:e instanceof Error?e.message:`Search is unavailable right now. Click the map to place a pin`)}finally{window.clearTimeout(r),o.current===t&&(!t.signal.aborted||n)&&m(!1)}},[l]),T=(0,X.useCallback)(()=>{if(!navigator.geolocation){g(`This browser has no geolocation`);return}b(!0),g(null),navigator.geolocation.getCurrentPosition(e=>{b(!1),i.current?.setView([e.coords.latitude,e.coords.longitude],16),C(e.coords.latitude,e.coords.longitude)},()=>{b(!1),g(`Could not read your location. Search or click the map instead`)},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})},[C]),E=(0,X.useCallback)(e=>{let t=i.current,n=Number(e.lat),r=Number(e.lon);if(!t||!Number.isFinite(n)||!Number.isFinite(r))return;let a=e.boundingbox?.map(Number);a&&a.length===4&&a.every(Number.isFinite)?t.fitBounds(xp.default.latLngBounds([a[0],a[2]],[a[1],a[3]]),{maxZoom:16}):t.setView([n,r],15),C(n,r,e.display_name),f([])},[C]);return(0,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:K(`fixed inset-0 z-[60] bg-black/40 transition-opacity duration-200`,x?`opacity-100`:`opacity-0`),onClick:n}),(0,Z.jsxs)(`div`,{role:`dialog`,"aria-label":`Pick a location on the map`,className:K(`fixed inset-y-0 right-0 z-[61] flex w-[min(560px,100vw)] flex-col bg-background shadow-elevation-4 transition-transform duration-200 ease-out`,x?`translate-x-0`:`translate-x-full`),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(yt,{className:`h-4 w-4 text-info`}),`Custom geotag`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close map`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`relative z-10 shrink-0 border-b px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:l,autoFocus:!0,onChange:e=>{o.current?.abort(),o.current=null,m(!1),f([]),u(e.target.value),g(null)},"aria-label":`Search for a place or address`,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),w())},placeholder:`Search a place, e.g. Slavkovský štít`,spellCheck:!1,className:`h-8 w-full rounded-md border border-input bg-transparent pl-7 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:T,disabled:y,title:`Use my current location`,"aria-label":`Use my current location`,className:`inline-flex h-8 w-8 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50`,children:y?(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(Jn,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:w,disabled:p||l.trim().length<2,className:`inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs text-primary-foreground disabled:opacity-50`,children:[p?(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(pr,{className:`h-3.5 w-3.5`}),`Search`]})]}),h&&(0,Z.jsx)(`p`,{role:`status`,className:`mt-1 text-xs text-warning`,children:h}),d.length>0&&(0,Z.jsx)(`div`,{className:`absolute inset-x-3 top-full z-10 mt-1 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-elevation-4`,children:d.map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>E(e),className:`block w-full border-b border-border/60 px-3 py-2 text-left text-xs last:border-0 hover:bg-muted`,children:e.display_name},`${e.lat},${e.lon},${e.display_name}`))})]}),(0,Z.jsxs)(`div`,{className:`relative isolate z-0 min-h-0 flex-1`,children:[(0,Z.jsx)(`div`,{ref:r,className:`h-full w-full`}),!s&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-3 z-[1000] flex justify-center`,children:(0,Z.jsx)(`span`,{className:`rounded-full bg-background/90 px-3 py-1 text-xs text-muted-foreground shadow-elevation-2`,children:`Click the map to drop a pin, or drag it to fine-tune`})})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 text-xs`,children:s?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 tabular-nums text-foreground`,children:[(0,Z.jsx)(cr,{className:`h-3 w-3 shrink-0 text-muted-foreground`}),s.lat.toFixed(5),`, `,s.lon.toFixed(5),_&&(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin text-muted-foreground`})]}),s.label&&(0,Z.jsx)(`div`,{className:`truncate text-muted-foreground`,children:s.label})]}):(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`No point selected`})}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:`Cancel`}),(0,Z.jsxs)(`button`,{type:`button`,disabled:!s,onClick:()=>{s&&(t(s),n())},className:`inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-50`,children:[(0,Z.jsx)($e,{className:`h-3.5 w-3.5`}),`Use this point`]})]})]})]})]}),document.body)}var Op={exif:`from the photo's EXIF`,device:`from the device at capture`,manual:`placed by hand`};function kp(e){let t=`${e.lat.toFixed(5)}, ${e.lon.toFixed(5)}`,n=e.source?Op[e.source]:null;return[t,e.accuracy==null?null:`±${e.accuracy} m`,n].filter(Boolean).join(` · `)}function Ap({value:e,onChange:t,idPrefix:n=`edit-geo`}){let[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${n}-action`,children:`Location`}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 text-xs`,children:[(0,Z.jsx)(yt,{className:e?`h-4 w-4 shrink-0 text-info`:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:e?`truncate tabular-nums`:`truncate text-muted-foreground`,children:e?kp(e):`No location on this document`})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.jsxs)(`button`,{id:`${n}-action`,type:`button`,onClick:()=>i(!0),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,Z.jsx)(en,{className:`h-3.5 w-3.5`}),e?`Move pin`:`Set on map`]}),e&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(null),"aria-label":`Remove location`,title:`Remove location`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),r&&(0,Z.jsx)(Dp,{initial:e,onPick:e=>t({lat:e.lat,lon:e.lon,source:`manual`}),onClose:()=>i(!1)})]})}function jp({workspaceId:e,documentIds:t,onClose:n}){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(`keep`),[l,u]=(0,X.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,X.useState)(t),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(``);return Sf(n,!m),(0,yf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-scrim p-4`,children:(0,Z.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`bulk-edit-title`,className:`max-h-viewport-modal overflow-y-auto w-full max-w-md space-y-4 rounded-xl border bg-background p-5 shadow-elevation-4`,children:[(0,Z.jsxs)(`h2`,{id:`bulk-edit-title`,className:`font-semibold`,children:[`Bulk Edit · `,f.length,` documents`]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Add tags to all selected documents. Choosing a location replaces their existing geotags; leaving it unset keeps them.`}),(0,Z.jsxs)(`fieldset`,{disabled:m,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:`Add tags`}),(0,Z.jsx)(gp,{tags:r,onChange:i,suggestions:[]})]}),(0,Z.jsx)(Ap,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,Z.jsxs)(`select`,{id:`bulk-comment-mode`,value:s,onChange:e=>c(e.target.value),className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm`,children:[(0,Z.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,Z.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,Z.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,Z.jsx)(`textarea`,{id:`bulk-comment`,rows:3,value:l,onChange:e=>u(e.target.value),placeholder:`Comment for all selected documents…`,className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(J,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,Z.jsx)(J,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await Sr(e,n);await Ui(e,bp(t,r,a,s===`keep`?void 0:s===`clear`?``:l))}catch{t.push(n)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),h(!1),t.length?(p(t),_(`${f.length-t.length} saved; ${t.length} could not be updated. Retry applies only to those documents.`)):n()},disabled:m||!d,children:m?`Saving…`:g?`Retry failed`:`Apply to all`})]})]})}),window.document.body)}var Mp=[{mode:`copy`,label:`Copy to`,icon:(0,Z.jsx)(Ve,{className:`h-3.5 w-3.5`})},{mode:`move`,label:`Move to`,icon:(0,Z.jsx)(qn,{className:`h-3.5 w-3.5`})},{mode:`delete`,label:`Delete from`,icon:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}],Np=[{value:`rename`,label:`Rename mine (file-1.ext)`},{value:`overwrite`,label:`Overwrite the existing file`},{value:`error`,label:`Skip the document`}],Pp=`h-9 w-full rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`;function Fp(e){return e.driver===`cacache`?wt:e.config?.remote===!0?we:hr}function Ip({workspaceId:e,documentCount:t,initialMode:n=`copy`,defaultFilename:r=``,onConfirm:i,onClose:a,saving:o=!1,sizeClassName:s}){let{showErrorToast:c}=to(),[l,u]=(0,X.useState)(!1);Sf(a,!o&&!l);let[d,f]=(0,X.useState)(n),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(``),[C,w]=(0,X.useState)(r),[T,E]=(0,X.useState)(`rename`);(0,X.useEffect)(()=>{let t=!1;return wa(e).then(e=>{t||m(e.filter(e=>e.kind===`storage`))}).catch(e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let D=d===`move`,O=e=>d===`delete`?null:e.enabled===!1?`disabled`:e.config?.readOnly===!0?`read-only`:e.config?.supported===!1?`unsupported`:null,k=(0,X.useMemo)(()=>(p||[]).filter(e=>!O(e)).map(e=>e.address),[p,d]),A=e=>{f(e),v(t=>{let n=(p||[]).filter(t=>e===`delete`||t.enabled!==!1&&t.config?.readOnly!==!0&&t.config?.supported!==!1).map(e=>e.address),r=[...t].filter(e=>n.includes(e));return new Set(e===`move`?r.slice(0,1):r)})},j=e=>{v(t=>{if(D)return t.has(e)?new Set:new Set([e]);let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},M=(0,X.useMemo)(()=>(p||[]).filter(e=>_.has(e.address)&&ua(e)),[p,_]),N=d!==`delete`&&M.length>0,P=e=>{u(!1);let t=Ia(e[0]||``,p||[]),n=t?(p||[]).find(e=>e.address===t.address):null;if(!t||!n){c(`Pick a folder inside a storage backend`);return}if(O(n)){c(`${n.address} is ${O(n)}`);return}if(!ua(n)){c(`${n.address} does not keep folders — objects are stored by content`);return}S(t.key),v(e=>D?new Set([t.address]):new Set([...e,t.address]))},F=async()=>{_.size===0||o||await i([..._],d,{keepDocument:y,folder:N?x.trim():``,filename:N&&t===1?C.trim():``,onConflict:T})},I=t,ee=I===1?``:`s`,te=d===`delete`?`Delete ${I} document${ee} from…`:`${d===`move`?`Move`:`Copy`} ${I} document${ee} to…`,ne=d===`delete`?`Delete from`:d===`move`?`Move to`:`Copy to`,re=_.size===0?ne.split(` `)[0]:`${ne} ${_.size} backend${_.size===1?``:`s`}`;return(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,s||`max-h-viewport-card w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(hr,{className:`h-4 w-4`}),te]}),(0,Z.jsx)(`button`,{type:`button`,onClick:a,disabled:o,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:Mp.map(({mode:e,label:t,icon:n})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>A(e),disabled:o,className:K(`flex items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors disabled:opacity-50`,d===e?e===`delete`?`border-destructive text-destructive`:`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[n,t]},e))}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:[h&&(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-destructive`,children:h}),!p&&!h&&(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading backends…`}),p?.length===0&&(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`No storage backends configured.`}),p?.map(e=>{let t=Fp(e),n=O(e),r=_.has(e.address),i=e.config?.remote===!0;return(0,Z.jsxs)(`div`,{onClick:()=>!n&&!o&&j(e.address),className:K(`group relative flex min-h-10 items-center gap-2 rounded-md px-3 py-2 text-sm shadow-elevation-1 transition-all select-none`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,n?`cursor-not-allowed bg-muted/40 opacity-60 before:bg-transparent`:`cursor-pointer hover:shadow`,!n&&r?d===`delete`?`bg-destructive/[0.08] hover:bg-destructive/[0.12] before:bg-destructive`:`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:n?``:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),title:e.address,children:[(0,Z.jsx)(`input`,{type:D?`radio`:`checkbox`,checked:r,disabled:!!n||o,onChange:()=>j(e.address),onClick:e=>e.stopPropagation(),className:`h-4 w-4 shrink-0 accent-primary`,"aria-label":e.address}),(0,Z.jsx)(t,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.config?.label||e.address}),(0,Z.jsxs)(`span`,{className:`block truncate font-mono text-[10px] text-muted-foreground`,children:[e.driver,` · `,e.address]})]}),i&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-info-subtle px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,title:`Network mount${e.config?.transport?` (${e.config.transport})`:``} — transfers cross the network`,children:e.config?.transport||`remote`}),n&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:n})]},`${e.driver}/${e.address}`)}),d===`delete`&&(0,Z.jsxs)(`label`,{className:`mt-3 flex cursor-pointer items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:y,onChange:e=>b(e.target.checked),className:`mt-0.5 h-3.5 w-3.5 accent-destructive`}),(0,Z.jsxs)(`span`,{children:[`Keep the index entry when its `,(0,Z.jsx)(`strong`,{children:`last`}),` copy is deleted.`,(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:`Otherwise the document is removed from the index once no locations remain.`})]})]}),N&&(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-md border px-3 py-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs font-medium`,children:[`Destination on `,M.map(e=>e.config?.label||e.address).join(`, `)]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-folder`,className:`text-[11px] text-muted-foreground`,children:`Folder (relative to the backend root)`}),(0,Z.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,Z.jsx)(q,{id:`backend-transfer-folder`,value:x,onChange:e=>S(e.target.value),placeholder:`/`,disabled:o,className:`h-9 font-mono text-xs`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`icon`,className:`h-9 w-9 shrink-0`,onClick:()=>u(!0),disabled:o,"aria-label":`Browse backend folders`,title:`Browse…`,children:(0,Z.jsx)(Mn,{className:`h-4 w-4`})})]})]}),t===1?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-filename`,className:`text-[11px] text-muted-foreground`,children:`File name`}),(0,Z.jsx)(q,{id:`backend-transfer-filename`,value:C,onChange:e=>w(e.target.value),placeholder:r||`keeps the document's own name`,disabled:o,className:`h-9 font-mono text-xs`})]}):(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Each document keeps its own file name and extension.`}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-conflict`,className:`text-[11px] text-muted-foreground`,children:`If a different file already has that name`}),(0,Z.jsx)(`select`,{id:`backend-transfer-conflict`,className:Pp,value:T,onChange:e=>E(e.target.value),disabled:o,children:Np.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),d===`move`&&k.length>0&&(0,Z.jsx)(`p`,{className:`px-1 pt-2 text-[11px] text-muted-foreground`,children:`The source copy is released only once the destination write is durable.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-t px-4 py-3`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[_.size,` backend`,_.size===1?``:`s`,` selected`]}),(0,Z.jsx)(J,{size:`sm`,variant:d===`delete`?`destructive`:`default`,onClick:F,disabled:_.size===0||o,children:o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ud,{className:`mr-1.5 h-3.5 w-3.5`}),`Working…`]}):(0,Z.jsxs)(Z.Fragment,{children:[d===`delete`?(0,Z.jsx)(lt,{className:`mr-1 h-3.5 w-3.5`}):d===`move`?(0,Z.jsx)(qn,{className:`mr-1 h-3.5 w-3.5`}):(0,Z.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),re]})})]}),d===`delete`&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 border-t bg-destructive/5 px-4 py-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,Z.jsx)(`span`,{children:`Deletes the file data from the selected backends. Copies on other backends are untouched.`})]}),l&&(0,Z.jsx)(pp,{onClose:()=>u(!1),children:(0,Z.jsx)(dp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`backends`],fixedWorkspaceName:e,title:`Pick a destination folder…`,confirmLabel:`Use folder`,onConfirm:P,onClose:()=>u(!1)})})]})}function Lp({onClose:e,onConfirm:t,fixedWorkspaceName:n,saving:r=!1,sizeClassName:i}){let[a,o]=(0,X.useState)(n?`browse`:`workspace`),[s,c]=(0,X.useState)([]),[l,u]=(0,X.useState)(!n),[d,f]=(0,X.useState)(n??null),[p,m]=(0,X.useState)(`context`),[h,g]=(0,X.useState)(new Set),[_,v]=(0,X.useState)(n);return n!==_&&(v(n),n||u(!0)),(0,X.useEffect)(()=>{n||Pr().then(c).catch(()=>c([])).finally(()=>u(!1))},[n]),(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,i||`h-viewport-card max-h-full w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Ot,{className:`h-4 w-4`}),a===`workspace`?`Add existing documents…`:`Pick documents…`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:e,disabled:r,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Z.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-200`,style:{transform:a===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Z.jsx)(lp,{workspaces:s,loading:l,onPick:e=>{f(e),g(new Set),o(`browse`)}})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:[!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4 rotate-180`})}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{m(e),g(new Set)},className:K(`flex items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,p===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[tp[e],np[e]]},e))]}),d&&(0,Z.jsx)(up,{workspaceName:d,treeTab:p,onTreeTabChange:m,selectedDocIds:h,onToggleDoc:e=>{g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onNavigate:()=>g(new Set)})]})]})}),a===`browse`&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[h.size,` document`,h.size===1?``:`s`,` selected`]}),(0,Z.jsx)(J,{size:`sm`,onClick:async()=>{!d||h.size===0||r||await t(Array.from(h),{workspaceName:d,treeName:p===`directory`?`directory`:Na,treeType:p})},disabled:h.size===0||r,children:r?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ud,{className:`mr-1.5 h-3.5 w-3.5`}),`Adding…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ot,{className:`mr-1 h-3.5 w-3.5`}),`Add`]})})]})]})}var Rp=(0,X.createContext)(null),zp={entry:null,open:()=>{},close:()=>{}};function Bp(){return(0,X.useContext)(Rp)??zp}var Vp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{className:`relative w-full overflow-auto`,children:(0,Z.jsx)(`table`,{ref:n,className:K(`w-full caption-bottom text-sm`,e),...t})}));Vp.displayName=`Table`;var Hp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`thead`,{ref:n,className:K(`[&_tr]:border-b`,e),...t}));Hp.displayName=`TableHeader`;var Up=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tbody`,{ref:n,className:K(`[&_tr:last-child]:border-0`,e),...t}));Up.displayName=`TableBody`;var Wp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tfoot`,{ref:n,className:K(`border-t bg-muted/50 font-medium [&>tr]:last:border-b-0`,e),...t}));Wp.displayName=`TableFooter`;var Gp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tr`,{ref:n,className:K(`border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted`,e),...t}));Gp.displayName=`TableRow`;var Kp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`th`,{ref:n,className:K(`h-12 px-2 md:px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0`,e),...t}));Kp.displayName=`TableHead`;var qp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`td`,{ref:n,className:K(`p-2 md:p-4 align-middle [&:has([role=checkbox])]:pr-0`,e),...t}));qp.displayName=`TableCell`;var Jp=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`caption`,{ref:n,className:K(`mt-4 text-sm text-muted-foreground`,e),...t}));Jp.displayName=`TableCaption`;var Yp=({label:e,sortKey:t,sort:n,onSort:r,className:i})=>{let a=n.key===t;return(0,Z.jsx)(Kp,{"aria-sort":a?n.dir===`asc`?`ascending`:`descending`:`none`,className:K(`cursor-pointer select-none hover:text-foreground transition-colors`,i),onClick:()=>r(t),children:(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,a?n.dir===`asc`?(0,Z.jsx)(Sn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Dn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Pe,{className:`h-3.5 w-3.5 opacity-40`})]})})};Yp.displayName=`SortableTableHead`;function Xp(e,t,n={key:null,dir:`asc`}){let[r,i]=X.useState(n);return{sorted:X.useMemo(()=>{let n=r.key?t[r.key]:null;if(!n)return e;let i=r.dir===`asc`?1:-1;return[...e].sort((e,t)=>{let r=n(e)??``,a=n(t)??``;return typeof r==`number`&&typeof a==`number`?(r-a)*i:String(r).localeCompare(String(a),void 0,{numeric:!0})*i})},[e,r,t]),sort:r,toggleSort:X.useCallback(e=>{i(t=>t.key===e?{key:e,dir:t.dir===`asc`?`desc`:`asc`}:{key:e,dir:`asc`})},[])}}var Zp=`workspace:relations:refresh`;function Qp(){window.dispatchEvent(new CustomEvent(Zp))}var $p=(0,X.createContext)(null),em=`canvas:documentOpenMode`;function tm(){try{return localStorage.getItem(em)===`modal`?`modal`:`side`}catch{return`side`}}var nm=tm(),rm=new Set;function im(){return nm}function am(e){try{localStorage.setItem(em,e)}catch{}nm=e;for(let e of rm)e()}function om(e){rm.add(e);let t=t=>{(t.key===em||t.key===null)&&(nm=tm(),e())};return window.addEventListener(`storage`,t),()=>{rm.delete(e),window.removeEventListener(`storage`,t)}}function sm(){return(0,X.useSyncExternalStore)(om,im,()=>`side`)}function cm({tabs:e,active:t,onChange:n,className:r=``,iconOnly:i=!1}){return(0,Z.jsx)(`div`,{className:`flex gap-1 border-b overflow-x-auto ${r}`,children:e.map(e=>{let r=e.icon;return(0,Z.jsxs)(`button`,{onClick:()=>n(e.id),title:e.label,className:`${i&&r?`px-3`:`px-4`} py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap inline-flex items-center gap-1.5 ${t===e.id?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[r&&(0,Z.jsx)(r,{className:`h-3.5 w-3.5`}),(!i||!r)&&e.label]},e.id)})})}var lm=e=>`${Qr.workspaces}/${encodeURIComponent(e)}/messages`,um=e=>Y.get(`${lm(e)}/accounts`),dm=(e,t)=>Y.get(`${lm(e)}/reply-target/${t}`),fm=(e,t)=>Y.post(`${lm(e)}/send`,t),pm=(e,t)=>Y.get(`${lm(e)}/whatsapp/${encodeURIComponent(t)}/connection`),mm=(e,t)=>Y.get(`${lm(e)}/outbox/${encodeURIComponent(t)}`),hm=(e,t)=>Y.delete(`${lm(e)}/whatsapp/${encodeURIComponent(t)}/connection`);function gm(e,t,n=!1){let r=2166136261;try{for(let e of localStorage.getItem(`authToken`)||``)r=Math.imul(r^e.charCodeAt(0),16777619)}catch{}return`canvas:message-draft:${r>>>0}:${e}:${t||`new`}${n?`:fwd`:``}`}var _m={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function vm({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,onClose:i}){let a=!!t&&n===`forward`,o=gm(e,t,a),s=()=>({requestId:crypto.randomUUID(),text:``,replyToDocumentId:t,...a?{forward:!0}:t?{replyAll:n===`replyAll`,quote:!0}:{}}),[c,l]=(0,X.useState)(()=>{try{let e=localStorage.getItem(o);if(e){let r=JSON.parse(e),i=r.draft||r;return a||!t?i:{...i,replyAll:n===`replyAll`}}}catch{}return s()}),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(navigator.onLine);(0,X.useEffect)(()=>{let e=()=>h(navigator.onLine);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]);let[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(()=>{try{return JSON.parse(localStorage.getItem(o)||`{}`).attempted===!0}catch{return!1}}),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(null);(0,X.useEffect)(()=>{let n=!0;return Promise.all([um(e),t?dm(e,t):Promise.resolve(null)]).then(([e,r])=>{n&&(d(r),p(e.filter(e=>e.canSend&&(!r||e.driver===r.driver&&e.address===r.address))),t&&!r&&x(`This message has no supported reply account.`),r&&l(e=>({...e,driver:r.driver,address:r.address})))}).catch(e=>{n&&x(e.message)}),()=>{n=!1}},[e,t]),(0,X.useEffect)(()=>{try{S?.status===`accepted`?localStorage.removeItem(o):localStorage.setItem(o,JSON.stringify({draft:c,attempted:v}))}catch{}},[o,c,v,S]);let w=f.find(e=>e.driver===c.driver&&e.address===c.address),T=w?.driver===`imap`,E=!!c.text.trim(),D=e=>l(t=>({...t,...e})),O=async()=>{_(!0),x(``),y(!0);let t=T?E?c:{...c,html:void 0}:{...c,html:void 0,quote:void 0,forward:void 0};try{let n=v?await mm(e,c.requestId).catch(n=>{if(n.statusCode===404)return fm(e,t);throw n}):await fm(e,t);if(C(n),n.status===`accepted`){try{localStorage.removeItem(o)}catch{}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}}))}}catch(e){let t=e;x(t.message),!v&&t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==409&&y(!1)}finally{_(!1)}},k=c.replyAll?u?.allRecipients:u?.recipients,A=g||v,j=t?a?_m.forward:_m[c.replyAll?`replyAll`:`reply`]:`New message`,M=t&&r?`${a?`Fwd`:`Re`}: ${r.replace(a?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Z.jsxs)(`section`,{className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${j} to message`:`New message`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Z.jsx)(`strong`,{className:`text-sm`,children:j}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:i,children:`Close`})]}),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,Z.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:w?`${w.driver}:${w.address}`:``,disabled:A||!!t,onChange:e=>{let t=f.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&D({driver:t.driver,address:t.address,to:[],cc:[],bcc:[],subject:void 0,target:void 0,replyAll:!1})},children:[(0,Z.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),f.map(e=>(0,Z.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),!f.length&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Enable sending in the account’s workspace settings. Your draft stays on this device.`}),T?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!a?`(leave blank to reply to the sender)`:``,(0,Z.jsx)(q,{"aria-label":`To`,disabled:A,value:c.to?.join(`, `)||``,onChange:e=>D({to:[e.target.value]})})]}),t&&!a&&!c.to?.some(e=>e.trim())&&k&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,k.to.join(`, `),k.cc.length?` · Cc: ${k.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Z.jsx)(q,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:A,value:c[e]?.join(`, `)||``,onChange:t=>D({[e]:[t.target.value]})})]},e)),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Z.jsx)(q,{"aria-label":`Subject`,disabled:A,value:c.subject||``,placeholder:M,onChange:e=>D({subject:e.target.value||void 0})})]}),t&&!a&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:A,checked:c.replyAll||!1,onChange:e=>D({replyAll:e.target.checked})}),`Reply all`]}),(0,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:A,checked:c.quote||!1,onChange:e=>D({quote:e.target.checked})}),`Quote original message`]})]}),a&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,Z.jsx)(So,{format:`html`,editable:!A,value:c.html||``,placeholder:a?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>D({html:e,text:t.slice(0,32e3)})})]}):(0,Z.jsxs)(Z.Fragment,{children:[!t&&(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,Z.jsx)(q,{"aria-label":`Conversation`,disabled:A,value:c.target||``,onChange:e=>D({target:e.target.value})})]}),(0,Z.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:A,value:c.text,onChange:e=>D({text:e.target.value}),placeholder:`Write a message…`})]}),b&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:b}),S&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[S.status===`accepted`?`Accepted by the provider.`:S.message,` `,S.warnings?.join(` `),` `,S.rejected?.length?`Not accepted for: ${S.rejected.join(`, `)}`:``]}),S?.status!==`accepted`&&(0,Z.jsx)(J,{size:`sm`,disabled:g||!v&&(!w||!E&&!(T&&a)||a&&!c.to?.some(e=>e.trim()))||!m,onClick:()=>void O(),children:g?`Sending…`:v?`Check send status`:`Send`}),(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,disabled:g,onClick:()=>{window.confirm(v?`This message may already have been sent. Discard this draft only after checking the conversation.`:`Discard this draft?`)&&(l({...s(),driver:c.driver,address:c.address}),y(!1),C(null),x(``))},children:`Discard draft`}),v&&S?.status!==`accepted`&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Do not start another send until you have checked the conversation. The same request will not be delivered twice by Canvas.`})]})}var ym=1,bm=8,xm=320,Sm=28,Cm=2.5,wm={scale:1,x:0,y:0};function Tm({src:e,alt:t,className:n=``,onZoomChange:r}){let i=(0,X.useRef)(null),a=(0,X.useRef)(null),[o,s]=(0,X.useState)(wm),c=(0,X.useRef)(new Map),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(!1),f=(0,X.useRef)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(e);h!==e&&(g(e),s(wm)),(0,X.useEffect)(()=>{r?.(o.scale>1.001)},[o.scale,r]);let _=(0,X.useCallback)(e=>{let t=i.current,n=a.current;if(!t||!n)return e;let r=Math.min(bm,Math.max(ym,e.scale)),o=Math.max(0,(n.offsetWidth*r-t.clientWidth)/2),s=Math.max(0,(n.offsetHeight*r-t.clientHeight)/2);return{scale:r,x:Math.min(o,Math.max(-o,e.x)),y:Math.min(s,Math.max(-s,e.y))}},[]),v=(0,X.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let a=r.getBoundingClientRect(),o=t-a.left-a.width/2,c=n-a.top-a.height/2;s(t=>{let n=e/t.scale;return _({scale:e,x:o-(o-t.x)*n,y:c-(c-t.y)*n})})},[_]),y=(0,X.useCallback)(()=>{let e=i.current,t=a.current;if(!e||!t||!t.offsetWidth||!t.offsetHeight)return Cm;let n=Math.max(e.clientWidth/t.offsetWidth,e.clientHeight/t.offsetHeight),r=Math.max(t.naturalWidth/t.offsetWidth,t.naturalHeight/t.offsetHeight)||bm;return Math.min(bm,Math.max(Cm,Math.min(Math.max(n,Cm),r)))},[]),b=(0,X.useCallback)((e,t)=>{o.scale>1.001?s(wm):v(y(),e,t)},[o.scale,v,y]),x=e=>{if(c.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),d.current=!1,c.current.size===2){let[e,t]=[...c.current.values()];l.current={dist:Math.hypot(e.x-t.x,e.y-t.y),scale:o.scale,cx:(e.x+t.x)/2,cy:(e.y+t.y)/2}}e.currentTarget.setPointerCapture(e.pointerId)},S=e=>{let t=c.current.get(e.pointerId);if(!t)return;if(c.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),c.current.size>=2&&l.current){let[e,t]=[...c.current.values()],n=Math.hypot(e.x-t.x,e.y-t.y);l.current.dist>0&&(d.current=!0,m(!0),v(l.current.scale*(n/l.current.dist),l.current.cx,l.current.cy));return}if(o.scale<=1.001)return;let n=e.clientX-t.x,r=e.clientY-t.y;(Math.abs(n)>1||Math.abs(r)>1)&&(d.current=!0,m(!0)),s(e=>_({...e,x:e.x+n,y:e.y+r}))},C=e=>{if(c.current.delete(e.pointerId),c.current.size<2&&(l.current=null),c.current.size===0&&m(!1),d.current){u.current=null;return}let t=e.timeStamp,n=u.current;if(n&&t-n.t<xm&&Math.hypot(e.clientX-n.x,e.clientY-n.y)<Sm){u.current=null,f.current=t,b(e.clientX,e.clientY);return}u.current={t,x:e.clientX,y:e.clientY}},w=e=>{e.preventDefault();let t=o.scale*(e.deltaY<0?1.15:1/1.15);t<=ym?s(wm):v(Math.min(bm,t),e.clientX,e.clientY)},T=o.scale>1.001;return(0,Z.jsx)(`div`,{ref:i,className:`relative flex h-full w-full items-center justify-center overflow-hidden`,style:{touchAction:`none`,cursor:T?`grab`:`zoom-in`},onPointerDown:x,onPointerMove:S,onPointerUp:C,onPointerCancel:e=>{c.current.delete(e.pointerId),l.current=null,u.current=null,d.current=!0,c.current.size===0&&m(!1)},onWheel:w,onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),!(f.current!==null&&e.timeStamp-f.current<xm)&&b(e.clientX,e.clientY)},children:(0,Z.jsx)(`img`,{ref:a,src:e,alt:t,draggable:!1,className:n,style:{transform:`translate3d(${o.x}px, ${o.y}px, 0) scale(${o.scale})`,transformOrigin:`center center`,transition:p?`none`:`transform 160ms ease-out`,willChange:`transform`}})})}var Em=`(max-width: 767px)`,Dm=new Map;function Om(e){let t=Dm.get(e);if(!t){let n=()=>typeof window<`u`&&typeof window.matchMedia==`function`;t={subscribe:t=>{if(!n())return()=>{};let r=window.matchMedia(e);return r.addEventListener(`change`,t),()=>r.removeEventListener(`change`,t)},getSnapshot:()=>n()?window.matchMedia(e).matches:!1},Dm.set(e,t)}return t}function km(){let e=Om(Em);return(0,X.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>!1)}function Am(){return jm(`(max-width: 1023px)`)}function jm(e){let t=Om(e);return(0,X.useSyncExternalStore)(t.subscribe,t.getSnapshot,()=>!1)}function Mm(){return!/android|iphone|ipad|mobile/i.test(navigator.userAgent)&&navigator.pdfViewerEnabled!==!1}var Nm=40,Pm=1600;function Fm({blob:e,filename:t}){let n=(0,X.useRef)(null),[r,i]=(0,X.useState)({error:null,pages:0,truncated:!1});return(0,X.useEffect)(()=>{let r=n.current;if(!r)return;let a=!1,o=null;return(async()=>{let n=await m(()=>import(`./pdf-Ciz5_WNq.js`),__vite__mapDeps([0,1])),s=(await m(async()=>{let{default:e}=await import(`./pdf.worker.min-C8Ts8bNu.js`);return{default:e}},[])).default;n.GlobalWorkerOptions.workerSrc=s;let c=await e.arrayBuffer();if(a)return;let l=n.getDocument({data:c});o=()=>{l.destroy()};let u=await l.promise;if(a)return;let d=Math.min(u.numPages,Nm),f=r.clientWidth||600,p=window.devicePixelRatio||1;for(let e=1;e<=d;e++){if(a)return;let n=await u.getPage(e),o=n.getViewport({scale:1}),s=Math.min(f*p,Pm*p)/o.width,c=n.getViewport({scale:s}),l=document.createElement(`canvas`);if(l.width=c.width,l.height=c.height,l.style.width=`100%`,l.style.height=`auto`,l.className=`rounded border bg-white`,l.setAttribute(`aria-label`,`${t}, page ${e}`),await n.render({canvas:l,viewport:c}).promise,n.cleanup(),a)return;r.appendChild(l),i({error:null,pages:e,truncated:u.numPages>Nm})}})().catch(e=>{a||i(t=>({...t,error:e instanceof Error?e.message:String(e)}))}),()=>{a=!0,o?.(),r.replaceChildren()}},[e,t]),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[r.error&&(0,Z.jsxs)(`p`,{className:`text-sm text-destructive`,children:[`Could not render PDF: `,r.error]}),!r.error&&r.pages===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering PDF…`}),(0,Z.jsx)(`div`,{ref:n,className:`space-y-2`}),r.truncated&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,Nm,` pages. Download the file for the full document.`]})]})}function Im({blob:e,blobUrl:t,filename:n,className:r=``}){let i=(0,X.useMemo)(()=>e&&e.type!==`application/pdf`?URL.createObjectURL(e.slice(0,e.size,`application/pdf`)):null,[e]);return(0,X.useEffect)(()=>()=>{i&&URL.revokeObjectURL(i)},[i]),Mm()||!e?(0,Z.jsx)(`div`,{className:`min-h-[300px] ${r}`,children:(0,Z.jsx)(`iframe`,{src:i??t,className:`h-full min-h-[300px] w-full rounded border`,title:n})}):(0,Z.jsx)(`div`,{className:`max-h-viewport-pane overflow-y-auto ${r}`,children:(0,Z.jsx)(Fm,{blob:e,filename:n})})}function Lm(e,t,n=256,{enabled:r=!0,blobFallback:i=!0,version:a=null}={}){let{isPublic:o,fetchBlob:s,fetchThumbnail:c}=vo(e),l=`${o?`pub`:`ws`}:${e}:${t}:${n}:${r}:${a??``}`,[u,d]=(0,X.useState)({blobUrl:null,error:null,loading:r}),[f,p]=(0,X.useState)(l);return l!==f&&(p(l),d({blobUrl:null,error:null,loading:r})),(0,X.useEffect)(()=>{if(!r)return;let e=!1,o=null;return c(t,n,a).catch(e=>{if(!i)throw e;return s(t)}).then(({blob:t})=>{e||(o=URL.createObjectURL(t),d({blobUrl:o,error:null,loading:!1}))}).catch(t=>{e||d({blobUrl:null,error:String(t instanceof Error?t.message:t),loading:!1})}),()=>{e=!0,o&&URL.revokeObjectURL(o)}},[l]),u}function Rm({workspaceId:e,document:t}){let{download:n}=vo(e),[r,i]=(0,X.useState)(!1),a=mo(t)||`document-${t.id}`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{i(!0);try{await n(t.id,a)}finally{i(!1)}},disabled:r,className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,Z.jsx)(er,{className:`h-3.5 w-3.5`}),r?`Preparing…`:`Download`]})}var zm=1600;function Bm({error:e,loading:t,children:n}){return e?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:e}):t?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading preview...`}):(0,Z.jsx)(Z.Fragment,{children:n})}function Vm({workspaceId:e,document:t,className:n=``}){let r=(0,X.useContext)($p),i=km(),a=jm(`(pointer: coarse)`),{blobUrl:o,error:s,loading:c}=Lm(e,t.id,zm,{version:t.checksumArray?.[0]??null}),{fetchBlob:l}=vo(e),u=mo(t)||`document-${t.id}`,[d,f]=(0,X.useState)(!1);return(0,Z.jsx)(Bm,{error:s,loading:c,children:o&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[i||a?(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(Tm,{src:o,alt:u,className:`max-h-full max-w-full object-contain`})}):(0,Z.jsx)(`img`,{src:o,alt:u,draggable:!1,onDoubleClick:r?e=>{e.preventDefault(),e.stopPropagation(),r()}:void 0,title:r?`Double-click to maximize or restore`:void 0,className:`min-h-0 w-full flex-1 object-contain ${r?`cursor-zoom-in`:``}`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{f(!0);try{let{blob:e}=await l(t.id),n=URL.createObjectURL(e),r=window.document.createElement(`a`);r.href=n,r.download=u,window.document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),3e4)}finally{f(!1)}},disabled:d,className:`inline-flex shrink-0 self-start items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,Z.jsx)(er,{className:`h-3.5 w-3.5`}),d?`Preparing…`:`Download original`]})]})})}function Hm({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=go(e,t.id);return(0,Z.jsx)(Bm,{error:i,loading:a,children:r&&(0,Z.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Z.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`,className:`w-full`}),(0,Z.jsx)(Rm,{workspaceId:e,document:t})]})})}function Um({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=go(e,t.id),[o,s]=(0,X.useState)(!1);return(0,Z.jsx)(Bm,{error:i,loading:a,children:r&&(0,Z.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Z.jsx)(`video`,{src:r,controls:!0,playsInline:!0,preload:`metadata`,onError:()=>s(!0),className:`max-h-viewport-pane w-full rounded border`}),o&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This video can’t be played inline in your browser. Download it to view.`}),(0,Z.jsx)(Rm,{workspaceId:e,document:t})]})})}function Wm({workspaceId:e,document:t,className:n=``}){let{blobUrl:r,blob:i,error:a,loading:o}=Oo(e,t.id,{typeHint:`application/pdf`}),s=mo(t)||`document-${t.id}`;return(0,Z.jsx)(Bm,{error:a,loading:o,children:r&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[(0,Z.jsx)(Im,{blob:i,blobUrl:r,filename:s,className:`min-h-0 flex-1`}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(Rm,{workspaceId:e,document:t})})]})})}var Gm=(0,X.lazy)(()=>m(()=>import(`./markdown-html-bKd2bDZi.js`),__vite__mapDeps([2,3,4,5,6,7])));function Km({content:e,className:t=``,preview:n=!1}){return(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`whitespace-pre-wrap break-words ${t}`,children:e}),children:(0,Z.jsx)(Gm,{content:e,className:t,preview:n})})}function qm({workspaceId:e,document:t,className:n=``}){let{text:r,error:i,loading:a}=Oo(e,t.id,{mode:`text`});return i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):a||r==null?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Z.jsx)(`pre`,{className:`bg-muted p-3 rounded text-xs overflow-auto max-h-viewport-pane whitespace-pre-wrap ${n}`,children:r})}function Jm({workspaceId:e,document:t,className:n=``}){let r=t.schema===no,{text:i,error:a,loading:o}=Oo(e,t.id,{mode:`text`,enabled:!r});return r?(0,Z.jsxs)(`div`,{className:`space-y-3 ${n}`,children:[t.data?.title?(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:String(t.data.title)}):null,(0,Z.jsx)(`div`,{className:`rounded-md border border-input bg-transparent`,children:(0,Z.jsx)(Km,{content:String(t.data?.content??``),className:`markdown-doc px-4 py-3`})})]}):a?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:a}):o||i==null?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Z.jsx)(`div`,{className:`rounded-md border border-input bg-transparent overflow-auto max-h-viewport-pane ${n}`,children:(0,Z.jsx)(Km,{content:i,className:`markdown-doc px-4 py-3`})})}function Ym({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),r=ro(n);return r?(0,Z.jsx)(`div`,{className:`aspect-video w-full ${t}`,children:(0,Z.jsx)(`iframe`,{src:`https://www.youtube-nocookie.com/embed/${encodeURIComponent(r)}`,title:String(e.data?.title??e.data?.label??`YouTube video`),className:`h-full w-full rounded border`,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0})}):null}function Xm({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),[r,i]=(0,X.useState)({blobUrl:null,blob:null,failed:!1,loading:!0}),[a,o]=(0,X.useState)(n);n!==a&&(o(n),i({blobUrl:null,blob:null,failed:!1,loading:!0})),(0,X.useEffect)(()=>{let e=!1,t=null,r=async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.blob();return new Blob([t],{type:`application/pdf`})},a=()=>{let e=localStorage.getItem(`authToken`);return fetch(`${ti}/proxy/pdf?url=${encodeURIComponent(n)}`,{headers:e?{Authorization:`Bearer ${e}`}:{}})};return fetch(n).then(r).catch(()=>a().then(r)).then(n=>{e||(t=URL.createObjectURL(n),i({blobUrl:t,blob:n,failed:!1,loading:!1}))}).catch(()=>{e||i({blobUrl:null,blob:null,failed:!0,loading:!1})}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[n]);let{blobUrl:s,blob:c,failed:l,loading:u}=r,d=(()=>{try{let e=decodeURIComponent(new URL(n).pathname.split(`/`).filter(Boolean).pop()??``)||`document`;return/\.pdf$/i.test(e)?e:`${e}.pdf`}catch{return`document.pdf`}})();return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${t}`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3`,children:[(0,Z.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Z.jsx)(gn,{className:`h-3 w-3`}),` `,n]}),c&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{if(!c)return;let e=URL.createObjectURL(c),t=window.document.createElement(`a`);t.href=e,t.download=d,window.document.body.appendChild(t),t.click(),t.remove(),setTimeout(()=>URL.revokeObjectURL(e),3e4)},className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:[(0,Z.jsx)(er,{className:`h-3.5 w-3.5`}),` Download`]})]}),u&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading PDF…`}),l&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Inline preview unavailable (direct fetch and server proxy both failed). Use the link above.`}),s&&(0,Z.jsx)(Im,{blob:c,blobUrl:s,filename:d,className:`min-h-[300px] flex-1`})]})}function Zm(e){if(!e)return!1;try{let t=new URL(e);return!!(/\.pdf$/i.test(t.pathname)||t.hostname.endsWith(`arxiv.org`)&&t.pathname.startsWith(`/pdf/`))}catch{return!1}}function Qm(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function $m({document:e,className:t=``}){let n=e.data||{},r=String(n.url??n.uri??``),i=String(n.title??n.label??``)||Qm(r),a=typeof n.favIconUrl==`string`?n.favIconUrl:``,o=n.pinned===!0,s=typeof n.timestamp==`string`?n.timestamp:null,[c,l]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:`space-y-3 ${t}`,children:[(0,Z.jsxs)(`a`,{href:r,target:`_blank`,rel:`noopener noreferrer`,className:`group flex items-start gap-3 rounded-lg border bg-card p-3 transition-colors hover:bg-accent/40`,children:[(0,Z.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded bg-muted`,children:a&&!c?(0,Z.jsx)(`img`,{src:a,alt:``,className:`h-5 w-5`,onError:()=>l(!0)}):(0,Z.jsx)(oe,{className:`h-4 w-4 text-muted-foreground`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:i}),o&&(0,Z.jsx)(ne,{className:`h-3 w-3 shrink-0 fill-warning text-warning`})]}),(0,Z.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-muted-foreground`,children:Qm(r)}),(0,Z.jsx)(`div`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground/70`,children:r})]}),(0,Z.jsx)(gn,{className:`mt-1 h-4 w-4 shrink-0 text-muted-foreground reveal-on-hover`})]}),s&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Saved `,new Date(s).toLocaleString()]})]})}var eh={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4};function th(e){let t=e.coords,n={lat:t.latitude,lon:t.longitude,source:`device`};return t.altitude!=null&&Number.isFinite(t.altitude)&&(n.alt=t.altitude),Number.isFinite(t.accuracy)&&(n.accuracy=Math.round(t.accuracy)),n}function nh(){return new Promise((e,t)=>navigator.geolocation.getCurrentPosition(e,t,eh))}function rh(e){let t=e?.code;return t===1?`Location permission denied`:t===2?`Location unavailable; no fix right now`:t===3?`Timed out waiting for a location fix`:`Could not read your location`}function ih(){let e=typeof navigator<`u`&&`geolocation`in navigator&&typeof window<`u`&&window.isSecureContext,[t,n]=(0,X.useState)(e?`prompt`:`unsupported`),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),h=(0,X.useRef)(!1),g=(0,X.useRef)(null),_=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(!e||!navigator.permissions?.query)return;let t=!1,r=null;return navigator.permissions.query({name:`geolocation`}).then(e=>{t||(r=e,n(e.state),e.onchange=()=>n(e.state))}).catch(()=>{}),()=>{t=!0,r&&(r.onchange=null)}},[e]);let v=(0,X.useCallback)(e=>{if(c(null),!e){_.current=null,f(null),m(null),h.current||i(!1);return}let t={lat:e.lat,lon:e.lon,source:`manual`};_.current=t,f(t),m(e.label??null),i(!0)},[]);return{supported:e,permission:t,enabled:r,busy:a,error:s,fix:l,setEnabled:(0,X.useCallback)(t=>{if(c(null),!t){h.current=!1,_.current=null,f(null),m(null),i(!1);return}_.current||e&&(h.current=!0,i(!0),o(!0),nh().then(e=>{let t=th(e);g.current=t,u(t),n(`granted`)}).catch(e=>{c(rh(e)),e?.code===1&&(n(`denied`),h.current=!1,i(!1))}).finally(()=>o(!1)))},[e]),manual:d,manualLabel:p,setManual:v,capture:(0,X.useCallback)(async()=>{if(_.current)return _.current;if(!h.current||!e)return null;try{return th(await nh())}catch{return g.current}},[e])}}var ah=`2.1`,oh=[`pending`,`in-progress`,`completed`,`cancelled`],sh={pending:`Pending`,"in-progress":`In progress`,completed:`Completed`,cancelled:`Cancelled`};function ch(e){return String(e).padStart(2,`0`)}function lh(e){return`${e.getFullYear()}-${ch(e.getMonth()+1)}-${ch(e.getDate())}T${ch(e.getHours())}:${ch(e.getMinutes())}`}function uh(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:lh(t)}function dh(e){if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function fh(){let e=new Date;return e.setHours(23,59,0,0),lh(e)}function ph(e){let t=dh(e.due);return{title:e.title.trim(),...e.description.trim()?{description:e.description.trim()}:{},status:e.status,completed:e.status===`completed`,...t?{dueDate:t}:{},...e.priority===``?{}:{priority:Number(e.priority)}}}function mh(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(`pending`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(fh()),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(!1),g=ih(),_=e.trim().length>0&&!m;async function v(t){h(!0);try{let r=await g.capture(),a=f.trim(),s={schema:uo,schemaVersion:ah,data:ph({title:e,description:n,status:i,priority:o,due:c}),...a?{comment:a}:{},metadata:{features:_p(u),...r?{geo:r}:{}}};return await ts(t,[s])}finally{h(!1)}}return{title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,tags:u,setTags:d,comment:f,setComment:p,saving:m,canSave:_,save:v,geotag:g}}function hh(e){return e.data||{}}var gh={pending:`bg-muted text-muted-foreground`,"in-progress":`bg-info/15 text-info dark:text-info`,completed:`bg-success/15 text-success dark:text-success`,cancelled:`bg-muted text-muted-foreground line-through`};function _h(e){if(!e.dueDate||e.status===`completed`||e.status===`cancelled`)return!1;let t=new Date(e.dueDate).getTime();return Number.isFinite(t)&&t<Date.now()}function vh(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}async function yh(e,t,n){let r=n===`completed`,i={...t.data||{},status:n,completed:r};r?i.completedAt=new Date().toISOString():delete i.completedAt,await Ui(e,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:i}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}function bh({document:e,workspaceId:t,className:n=``}){let r=hh(e),i=Eo()!=null,[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=ea(e),l=r.status===`completed`,u=r.status??`pending`,d=_h(r);return(0,Z.jsx)(`div`,{className:`space-y-3 ${n}`,children:(0,Z.jsxs)(`div`,{className:`relative flex items-start gap-3 rounded-lg border bg-card p-3 transition-opacity ${s?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(i||a)){o(!0);try{await yh(t,e,l?`pending`:`completed`)}catch{}finally{o(!1)}}},disabled:i||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${i?`cursor-default opacity-70`:``}`,children:a?(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}):l&&(0,Z.jsx)($e,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`font-medium leading-tight ${l?`text-muted-foreground line-through`:``}`,children:r.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-2 py-0.5 ${gh[u]}`,children:sh[u]}),r.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(pe,{className:`h-3 w-3`}),vh(r.dueDate),d?` · overdue`:``]}),typeof r.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,children:[(0,Z.jsx)(bn,{className:`h-3 w-3`}),`P`,r.priority]})]}),r.description&&(0,Z.jsx)(Km,{content:String(r.description),className:`mt-2 text-sm text-muted-foreground`}),s&&(0,Z.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),c]})]})]})})}function xh(e){return e?typeof e==`string`?e:e.name&&e.address?`${e.name} <${e.address}>`:e.address||e.name||``:``}function Sh(e){return e?(Array.isArray(e)?e:[e]).map(e=>xh(e)).filter(Boolean).join(`, `):``}function Ch(e){if(!Number.isFinite(e))return``;let t=Number(e);return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function wh(e,t,n){let r=0;Ss.addHook(`afterSanitizeAttributes`,e=>{if(e.tagName===`IMG`){let i=e.getAttribute(`src`)||``,a=i.toLowerCase();if(a.startsWith(`cid:`)){let n=i.slice(4).replace(/^<|>$/g,``),r=t.get(n)||t.get(`<${n}>`);r?e.setAttribute(`src`,r):e.removeAttribute(`src`)}else(a.startsWith(`http:`)||a.startsWith(`https:`)||a.startsWith(`//`))&&(r++,n?e.setAttribute(`src`,i.replace(/^http:/i,`https:`).replace(/^\/\//,`https://`)):e.removeAttribute(`src`))}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`))});try{let t=Ss.sanitize(e,{FORBID_TAGS:[`script`,`iframe`,`object`,`embed`,`form`,`base`,`link`,`meta`],FORBID_ATTR:[`srcset`]}),i=`<!doctype html><html><head>
|
|
7
7
|
<meta charset="utf-8">
|
|
8
8
|
<meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; img-src data:${n?` https:`:``}; style-src 'unsafe-inline'`}">
|
|
9
9
|
<style>body{margin:12px;font:14px/1.5 system-ui,sans-serif;color:#1a1a1a;background:#fff;word-break:break-word}img{max-width:100%}</style>
|
|
10
|
-
</head><body>${t}</body></html>`;return{url:URL.createObjectURL(new Blob([i],{type:`text/html;charset=utf-8`})),remoteCount:r}}finally{Ss.removeHook(`afterSanitizeAttributes`)}}function Th(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function Eh({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=vo(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],s=typeof a.bodyHtml==`string`&&a.bodyHtml.trim()?a.bodyHtml:null,c=typeof a.body==`string`?a.body:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!s),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(0),[_,v]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!s||d)return;let e=!1,n=[],i=o.filter(e=>e.contentId&&e.url);return Promise.all(i.slice(0,20).map(async e=>{try{let{blob:n}=await r(t.id,{url:e.url}),i=await Th(n);return[String(e.contentId).replace(/^<|>$/g,``),i]}catch{return null}})).then(t=>{if(e)return;let r=new Map(t.filter(Boolean)),{url:i,remoteCount:a}=wh(s,r,p);n.push(i),u(i),g(a)}).catch(t=>{e||v(String(t instanceof Error?t.message:t))}),()=>{e=!0,n.forEach(e=>URL.revokeObjectURL(e)),u(null)}},[e,t.id,s,d,p]);let b=typeof a.date==`string`?new Date(a.date).toLocaleString():null,x=o.filter(e=>!e.isInline||!e.contentId),S=async e=>{if(e.url)try{await i(t.id,e.filename||`attachment`,{url:e.url})}catch(e){v(e instanceof Error?e.message:String(e))}};return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 ${n}`,children:[(0,Z.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-3 text-sm`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,Z.jsx)(`div`,{className:`text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,xh(a.from)]}),Sh(a.to)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Sh(a.to)]}),Sh(a.cc)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Sh(a.cc)]}),b&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:b})]}),s&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap justify-end gap-2`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>f(!d),children:[d?(0,Z.jsx)(j,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(wn,{className:`mr-1.5 h-3.5 w-3.5`}),d?`HTML`:`Plain text`]}),!d&&h>0&&(0,Z.jsxs)(J,{size:`sm`,variant:p?`secondary`:`outline`,onClick:()=>m(!p),title:`Remote images can reveal your IP/read status to the sender`,children:[p?(0,Z.jsx)(V,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(y,{className:`mr-1.5 h-3.5 w-3.5`}),p?`Hide remote images`:`Show remote images (${h})`]})]})]})}),_&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:_}),!d&&s?l?(0,Z.jsx)(`iframe`,{src:l,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,Z.jsx)(`pre`,{className:`min-h-[12rem] flex-1 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-sm`,children:c||`(empty body)`}),x.length>0&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,x.length,`)`]}),x.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(wn,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:Ch(e.size)})]}),e.url&&(0,Z.jsxs)(`button`,{onClick:()=>S(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Z.jsx)(er,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}var Dh={email:Cn,phone:be,sms:Me,chat:Me,slack:Me,matrix:Me,web:oe,url:oe},Oh={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},kh=e=>Array.isArray(e)?e:[];function Ah(e,t){return t?e===`email`?`mailto:${t}`:e===`phone`||e===`sms`?`tel:${t.replace(/[^\d+]/g,``)}`:/^https?:\/\//i.test(t)?t:null:null}function jh({title:e,count:t,children:n}){return t===0?null:(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`space-y-1`,children:n})]})}function Mh({icon:e,primary:t,children:n,title:r}){return(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 rounded-md border bg-card px-2.5 py-1.5 text-sm`,title:r,children:[(0,Z.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,Z.jsx)(Ln,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function Nh({document:e,className:t}){let n=e.data??{},r=kh(n.identifiers),i=kh(n.channels),a=kh(n.organizations),o=kh(n.links),s=kh(n.tags),c=String(n.displayName||``).trim(),l=io(e.schema,oo),u=String(n.primaryEmail||``).trim(),d=n.name&&typeof n.name==`object`?n.name:{},f=[d.prefix,d.given,d.middle,d.family,d.suffix].map(e=>String(e||``).trim()).filter(Boolean).join(` `),p=i.some(e=>e.kind===`email`&&e.value===u);return(0,Z.jsxs)(`div`,{className:K(`space-y-4`,t),children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:Oh[l]||l}),f&&f!==c&&(0,Z.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,Z.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,Z.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,Z.jsx)(jh,{title:`Primary email`,count:1,children:(0,Z.jsx)(Mh,{icon:Cn,primary:!0,children:(0,Z.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,Z.jsx)(jh,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=Ah(n,r),a=Dh[n]||Me;return(0,Z.jsxs)(Mh,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,Z.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,Z.jsx)(jh,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,Z.jsxs)(Mh,{icon:In,primary:e.primary,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,Z.jsx)(jh,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,Z.jsxs)(Mh,{icon:st,children:[e.name,e.role&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,Z.jsx)(jh,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,Z.jsxs)(Mh,{icon:Xt,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function Ph({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function Fh(e){let t=e.schema;if(t===`data/schema/note`)return Jm;if(t===`data/schema/drawing`)return Vm;if(t===`data/schema/task`)return bh;if(t===`data/schema/message/email`)return Eh;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return Nh;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return ro(t)?Ym:Zm(t)?Xm:$m}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(so(n,mo(e))){case`image`:return Vm;case`audio`:return Hm;case`video`:return Um;case`pdf`:return Wm;case`markdown`:return Jm;case`text`:return qm;default:return Ph}}function Ih({workspaceId:e,document:t,className:n}){let r=Fh(t);return r?(0,Z.jsx)(r,{workspaceId:e,document:t,className:n}):(0,Z.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var Lh=15,Rh=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function zh(e){return String(e).padStart(2,`0`)}function Bh(e){let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(e||``);return t?{date:`${t[1]}-${t[2]}-${t[3]}`,time:`${t[4]}:${t[5]}`}:null}function Vh(e){return`${e.getFullYear()}-${zh(e.getMonth()+1)}-${zh(e.getDate())}`}function Hh(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function Uh(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/Lh)*Lh),`${zh(e.getHours())}:${zh(e.getMinutes())}`}function Wh(){let e=[];for(let t=0;t<1440;t+=Lh)e.push(`${zh(Math.floor(t/60))}:${zh(t%60)}`);return e}var Gh=Wh();function Kh(e){let t=new Date(e.getFullYear(),e.getMonth(),1),n=(t.getDay()+6)%7,r=new Date(t);return r.setDate(t.getDate()-n),Array.from({length:42},(e,t)=>{let n=new Date(r);return n.setDate(r.getDate()+t),n})}function qh(e){let[t,n]=e.split(`:`).map(Number);return new Date(2e3,0,1,t,n).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function Jh(e){let t=Bh(e);if(!t)return``;let[n,r,i]=t.date.split(`-`).map(Number),[a,o]=t.time.split(`:`).map(Number);return new Date(n,r-1,i,a,o).toLocaleString(void 0,{weekday:`short`,day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}function Yh({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,X.useState)(!1),u=(0,X.useRef)(null),d=Bh(e),f=d?Jh(e):``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:K(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,Z.jsx)(pe,{className:K(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Z.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(G,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Z.jsx)(Xh,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Xh({anchorRef:e,value:t,onChange:n,onClose:r}){let i=Bh(t),a=i?.date??Vh(new Date),o=i?.time??null,[s,c]=(0,X.useState)(()=>{let e=Hh(a);return new Date(e.getFullYear(),e.getMonth(),1)}),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(null);(0,X.useLayoutEffect)(()=>{let t=l.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));f({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,X.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let p=(0,X.useMemo)(()=>!o||Gh.includes(o)?Gh:[...Gh,o].sort(),[o]);(0,X.useEffect)(()=>{let e=u.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let m=(e,t)=>n(`${e}T${t}`),h=e=>{let t=o??Uh();m(Vh(e),t),e.getMonth()!==s.getMonth()&&c(new Date(e.getFullYear(),e.getMonth(),1))},g=e=>{m(a,e),r()},_=e=>{let t=new Date;t.setDate(t.getDate()+e);let n=o??Uh();m(Vh(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},v=Vh(new Date),y=Kh(s);return(0,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Z.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},children:[(0,Z.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(se,{className:`h-4 w-4`})}),(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:Rh.map(e=>(0,Z.jsx)(`span`,{children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:y.map(e=>{let t=Vh(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>h(e),"aria-pressed":r,className:K(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===v&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,Z.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,Z.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Z.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&m(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,Z.jsx)(`div`,{ref:u,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:p.map(e=>{let t=e===o;return(0,Z.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>g(e),"aria-pressed":t,className:K(`block w-full rounded px-2 py-1 text-left text-xs tabular-nums transition-colors`,t?`bg-primary text-primary-foreground`:`hover:bg-muted`),children:qh(e)},e)})})]})]})]}),document.body)}var Zh={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Qh=`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,$h=`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 eg({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-title`,children:`Title`}),(0,Z.jsx)(q,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-desc`,children:`Description`}),(0,Z.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:$h})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-due`,children:`Due`}),(0,Z.jsx)(Yh,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Z.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Qh,children:[(0,Z.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Z.jsx)(`option`,{value:e,children:Zh[e]},e))]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-status`,children:`Status`}),(0,Z.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Qh,children:oh.map(e=>(0,Z.jsx)(`option`,{value:e,children:sh[e]},e))})]})]})}var tg=`3.0`,ng=[`person`,`organization`,`service`,`bot`],rg={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},ig=[`email`,`phone`,`sms`,`chat`,`web`],ag=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function og(e){let t=e.primaryEmail.trim().toLowerCase(),n=e.channels.map(e=>({...e,kind:e.kind.trim(),value:e.value.trim(),label:e.label?.trim()||void 0})).filter(e=>e.kind&&e.value);if(t&&!n.some(e=>e.kind===`email`&&e.value===t)){for(let e of n)e.kind===`email`&&(e.primary=!1);n.push({kind:`email`,value:t,label:void 0,primary:!0})}let r=e.given.trim(),i=e.family.trim();return{displayName:e.displayName.trim(),...t?{primaryEmail:t}:{},...r||i?{name:{...r?{given:r}:{},...i?{family:i}:{}}}:{},channels:n,identifiers:e.identifiers.map(e=>({...e,type:e.type.trim(),identifier:e.identifier.trim(),provider:e.provider?.trim()||void 0})).filter(e=>e.type&&e.identifier),organizations:e.organizations.map(({identityId:e,...t})=>({...t,name:t.name.trim(),role:t.role?.trim()||void 0,...e?{metadata:{identityId:e}}:{}})).filter(e=>e.name)}}function sg(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=io(String(e?.schema||``),oo);return{displayName:String(t.displayName||``),type:ng.includes(i)?i:`person`,primaryEmail:String(t.primaryEmail||``),given:String(n.given||``),family:String(n.family||``),channels:r(t.channels),identifiers:r(t.identifiers),organizations:r(t.organizations).map(e=>({name:String(e.name||``),role:e.role?String(e.role):void 0,identityId:Number(e.metadata?.identityId)||void 0}))}}async function cg(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await Xi(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function lg(e){let[t,n]=(0,X.useState)(e?.displayName??``),[r,i]=(0,X.useState)(e?.type??`person`),[a,o]=(0,X.useState)(e?.primaryEmail??``),[s,c]=(0,X.useState)(e?.given??``),[l,u]=(0,X.useState)(e?.family??``),[d,f]=(0,X.useState)(e?.channels??[]),[p,m]=(0,X.useState)(e?.identifiers??[]),[h,g]=(0,X.useState)(e?.organizations??[]),[_,v]=(0,X.useState)([]),[y,b]=(0,X.useState)(``),[x,S]=(0,X.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${oo}/${C.type}`,schemaVersion:tg,data:og(C),...t?{comment:t}:{},metadata:{features:_p(_)}},r=await ts(e,[n]);return await cg(e,r[0],h),r}finally{S(!1)}}return{displayName:t,setDisplayName:n,type:r,setType:i,primaryEmail:a,setPrimaryEmail:o,given:s,setGiven:c,family:l,setFamily:u,channels:d,setChannels:f,identifiers:p,setIdentifiers:m,organizations:h,setOrganizations:g,tags:_,setTags:v,comment:y,setComment:b,values:C,saving:x,canSave:T,emailValid:w,save:E}}var ug=`h-9 shrink-0 rounded-md border border-input bg-transparent px-2 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function dg({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(Eu,{children:e}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(H,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},i))})]})}function fg(e,t){let n=e[t].kind,r=e[t].primary;return e.map((e,i)=>e.kind===n?{...e,primary:!r&&i===t}:e)}function pg(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Va(e,`organization`);t||n(r.map(e=>({id:e.id,name:bo(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function mg({idPrefix:e,workspaceName:t,displayName:n,setDisplayName:r,type:i,setType:a,primaryEmail:o,setPrimaryEmail:s,given:c,setGiven:l,family:u,setFamily:d,channels:f,setChannels:p,identifiers:m,setIdentifiers:h,organizations:g,setOrganizations:_,emailValid:v=!0}){let y=pg(t);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Z.jsx)(q,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-type`,children:`Type`}),(0,Z.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:K(ug,`w-full`),children:ng.map(e=>(0,Z.jsx)(`option`,{value:e,children:rg[e]},e))})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Z.jsx)(q,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-given`,children:`Given name`}),(0,Z.jsx)(q,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-family`,children:`Family name`}),(0,Z.jsx)(q,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Z.jsx)(dg,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:K(ug,`w-24`),children:[ig.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!ig.includes(e.kind)&&(0,Z.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Z.jsx)(q,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(fg(f,f.indexOf(e))),className:K(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,Z.jsx)(Ln,{className:K(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Z.jsx)(dg,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:K(ug,`w-24`),children:[ag.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!ag.includes(e.type)&&(0,Z.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Z.jsx)(q,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,Z.jsx)(dg,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[y.length>0?(0,Z.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:K(ug,`min-w-0 flex-1`),children:[(0,Z.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Z.jsx)(q,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(q,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function hg(e){return e===`data/schema/note`||e===`data/schema/link`||e===`data/schema/tab`||e===`data/schema/task`||e===`data/schema/drawing`||e===`data/schema/identity`||e.startsWith(`data/schema/identity/`)}function gg(e){return hg(e.schema)||xo(e)}function _g(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function vg(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await Ta(e,t,{resolve:!1}),a=new Set(i.outgoing.filter(e=>e.p===`member-of`).map(e=>e.to));for(let n of r)a.has(n)||await Xi(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await Xr(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function yg({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=to(),a=hg(e.schema),o=e.schema===no,s=xo(e),c=Do(e)??`markdown`,l=s&&ho(e),u=e.schema===uo,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=_g(e.schema),[m,h]=(0,X.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,X.useState)(String(e.data?.[p]??``)),[v,y]=(0,X.useState)(String(e.data?.content??``)),[b,x]=(0,X.useState)(String(e.data?.description??``)),[S,C]=(0,X.useState)(e.data?.status??`pending`),[w,T]=(0,X.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,X.useState)(e.data?.dueDate?uh(String(e.data.dueDate)):fh()),O=lg(sg(e)),[k,A]=(0,X.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[M,N]=(0,X.useState)(j),P=JSON.stringify(M??null)!==JSON.stringify(j??null),F=e.features??e.metadata?.features,[I,ee]=(0,X.useState)(vp(F).length?vp(F):e.data?.tags??[]),te=Oo(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:wo,version:e.checksumArray?.[0]??null}),[ne,re]=(0,X.useState)(null),ie=`${e.id}:${e.checksumArray?.[0]??``}`;s&&te.text!=null&&ne!==ie&&(re(ie),y(te.text));let[L,R]=(0,X.useState)([]),[ae,oe]=(0,X.useState)(!1),{replicating:se,mirror:ce}=ea(e);(0,X.useEffect)(()=>{let e=!1;return jr(t).then(t=>{e||R(t)}).catch(()=>{}),()=>{e=!0}},[t]);let z=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),le=!ae&&(s?!l&&te.text!=null&&!te.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?g.trim().length>0:o?v.trim().length>0:z:!0),ue=async()=>{oe(!0);try{if(s){await ko(t,e,v,{comment:k.trim(),...P?{metadata:{geo:M}}:{}}),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n();return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:k.trim()};if(d){let{type:t,...n}=e.data??{};i.schema=`${oo}/${O.values.type}`,i.data={...n,...og(O.values)},i.metadata={features:_p(I)}}else if(u)i.data={...e.data,...ph({title:g,description:b,status:S,priority:w,due:E})},i.metadata={features:_p(I)};else if(a){let t=I.map(e=>e.trim()).filter(Boolean),n;o?n={...g.trim()?{title:g.trim()}:{},content:v}:(n={...e.data},f&&(n[f]=m.trim()),g.trim()?n[p]=g.trim():delete n[p],n.tags=t),i.data=n,i.metadata={features:_p(I)}}P&&(i.metadata={...i.metadata??{},geo:M}),await Ui(t,i),d&&await vg(t,e.id,O.values.organizations),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{oe(!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`edit-url`,children:`URL`}),(0,Z.jsx)(q,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!z&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Z.jsx)(mg,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Z.jsx)(eg,{idPrefix:`edit-todo`,title:g,setTitle:_,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`edit-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-title`,value:g,onChange:e=>_(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Body`}),l?(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&te.error?(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:te.error}):s&&te.text==null?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Z.jsx)(To,{kind:o?`markdown`:c,value:v,onChange:y,placeholder:o?`Write your note…`:void 0})]}),a&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:I,onChange:ee,suggestions:L})]}),(0,Z.jsx)(Ap,{value:M,onChange:N}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`edit-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`edit-comment`,value:k,onChange:e=>A(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,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 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:n,disabled:ae,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:ue,disabled:!le,children:ae?se?`Replicating to ${ce.label}…`:`Saving…`:`Save changes`})]})]})}var bg=(0,X.createContext)(null),xg={open:()=>{},close:()=>{}};function Sg(){return(0,X.useContext)(bg)??xg}var Cg=`main`,wg=(0,X.createContext)(null);function Tg(){return(0,X.useContext)(wg)}function Eg({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=Sg(),o=Bp(),s=Tg(),c=n===`out`?e.to:e.from,l=e.document??null,u=!e.meta||e.meta.src===`doc`;return(0,Z.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,Z.jsx)(qn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Z.jsx)(Bt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Z.jsx)(ep,{document:l,size:3.5}):null,l?(0,Z.jsx)(`button`,{type:`button`,onClick:()=>s?o.open(l,t):a(l,t),className:`min-w-0 flex-1 truncate text-left hover:underline`,title:`Open document ${c}`,children:bo(l).title}):(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Z.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!u&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),u&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function Dg({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=to(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useCallback)(async()=>{try{let n=await Ta(t,e.id);a(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[t,e.id]),h=`${t}:${e.id}`,[g,_]=(0,X.useState)(h);h!==g&&(_(h),a(null),s(null)),(0,X.useEffect)(()=>{async function e(){await m()}return e(),window.addEventListener(Zp,e),()=>window.removeEventListener(Zp,e)},[m]);let v=async(i,a)=>{let o=a===`out`?i.to:i.from;if(o==null)return;let s=`${a}:${i.p}:${o}`;p(s);try{await Xr(t,e.id,i.p,o,a),n(`Relation removed`),Qp()}catch(e){r(e instanceof Error?e.message:`Failed to remove relation`)}finally{p(null)}},y=[{dir:`out`,title:`Points at`,hint:`this document as the subject`,entries:i?.outgoing??[]},{dir:`in`,title:`Pointed at by`,hint:`this document as the object`,entries:i?.incoming??[]}];return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Z.jsx)(H,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?y.every(e=>e.entries.length===0)?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Z.jsx)(`div`,{className:`space-y-4`,children:y.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,Z.jsx)(Eg,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void v(n,e)},i)})]},n))]},e))}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),c&&(0,Z.jsx)(pp,{onClose:()=>{u||l(!1)},children:(0,Z.jsx)(dp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,tabs:[`relations`],fixedWorkspaceName:t,documentCount:1,saving:u,relationPredicates:i?.predicates,relationExcludeIds:new Set([e.id]),onClose:()=>l(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:i,direction:a,targetIds:o})=>{d(!0);try{await Xi(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),Qp()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var Og=(0,X.lazy)(()=>m(()=>import(`./SketchEditor-BbXQRr1e.js`),__vite__mapDeps([8,3,4,1,9,10,11,12,13,14,15,16,17,18,19,20]))),kg=(0,X.lazy)(()=>m(()=>import(`./TextDocumentEditor-BU0qu4aP.js`),__vite__mapDeps([21,3,4,9,11,10,12,13,22,1,19]))),Ag={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},jg={reply:F,replyAll:M,forward:ie};function Mg({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Eo()!=null,{showErrorToast:a}=to(),[o,s]=(0,X.useState)(null),c=e.schema===`data/schema/message/email`,l=!i&&(c||[`slack`,`whatsapp`].includes(String(e.data?.platform))),u=c?[`reply`,`replyAll`,`forward`]:[`reply`],d=e=>s(t=>t===e?null:e),f=!i,[p,m]=(0,X.useState)(n&&gg(e)),h=e.schema===lo,[g,_]=(0,X.useState)(!1),v=e.schema===`data/schema/note`||xo(e),[y,b]=(0,X.useState)(!1),x=`${e.id}:${n}`,[S,C]=(0,X.useState)(x);return x!==S&&(C(x),m(n&&gg(e))),p&&f?(0,Z.jsx)(yg,{document:e,workspaceId:t,onClose:()=>{m(!1),r?.()}}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[f&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[l&&u.map(e=>{let t=jg[e];return(0,Z.jsxs)(J,{size:`sm`,variant:o===e?`secondary`:`outline`,onClick:()=>d(e),children:[(0,Z.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),Ag[e]]},e)}),e.schema===`data/schema/file`&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Zr(t,e.id,mo(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Z.jsx)(er,{className:`mr-1 h-3 w-3`}),` Download`]}),h&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Z.jsx)(rt,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),v&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Z.jsx)(T,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(!0),children:[(0,Z.jsx)(Fe,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),g&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(Og,{doc:e,workspaceName:t,onSaved:()=>{_(!1),r?.()},onClose:()=>_(!1),onDetails:()=>{_(!1),m(!0)}})}),y&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Z.jsx)(kg,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),m(!0)}})}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:[(0,Z.jsx)(Ih,{workspaceId:t,document:e}),o&&l&&(0,Z.jsx)(vm,{workspaceId:t,replyToDocumentId:Number(e.id),mode:o,originalSubject:c&&typeof e.data?.subject==`string`?e.data.subject:void 0,onClose:()=>s(null)},`${e.id}:${o}`)]}),e.comment?.trim()&&(0,Z.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Z.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var Ng=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,Pg=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function Fg({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Z.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,Pg(n.exposureTime)),n&&i(`ISO`,Number.isFinite(n.iso)?n.iso:null),n&&i(`Focal length`,Number.isFinite(n.focalLength)?`${n.focalLength} mm`:null),n&&i(`Captured`,Ng(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Z.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function Ig({document:e}){let t=e.metadata;return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:Ng(e.createdAt)})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:Ng(e.updatedAt)})]})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Z.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Z.jsx)(Fg,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=Bg(e.url);return(0,Z.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Z.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),r&&(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Z.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function Lg({document:e}){let{showSuccessToast:t,showErrorToast:n}=to(),r=JSON.stringify(e,null,2);return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Z.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function Rg({document:e,workspaceId:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,X.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,X.useEffect)(()=>{let n=!1;return qr(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Z.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Z.jsx)(Dg,{document:e,workspaceId:t})]}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function zg(e){return e===`stored`?wt:e===`workspace-file`?hr:e===`imap`?Cn:e===`readonly`?oe:fn}function Bg(e){let t=e.match(/^([a-z][a-z0-9+.-]*):\/\/([^/]*)\/?(.*)$/i);return t?{backend:`${t[1]}://${t[2]}`,key:t[3]}:{backend:e,key:``}}function Vg({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=to(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(!1),_=`${t}:${e.id}`,[v,y]=(0,X.useState)(_);_!==v&&(y(_),o(null),c(null),f(null));let b=()=>{Br(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,X.useEffect)(()=>{let n=!1;return Br(t,e.id).then(e=>{n||o(e)}).catch(e=>{n||c(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[_]);let x=async(a,o)=>{u(a),f(null);try{let i=await Mr(t,[e.id],{urls:[a],...o===void 0?{}:{keepDocument:o}}),s=i.successful[0];if(!s)throw Error(i.failed[0]?.reason||`Destroy failed`);s.docDeleted?r(`Removed from backend; document removed from index`):s.deleted.includes(a)?r(`Removed from backend`):r(`Reference dropped (backend is read-only)`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n?.(),b()}catch(e){i(e instanceof Error?e.message:String(e))}finally{u(null)}},S=async(a,o,s)=>{g(!0);try{let i=await Pi(t,[e.id],{to:a,mode:o,keepDocument:s.keepDocument,folder:s.folder,filename:s.filename,onConflict:s.onConflict}),c=i.successful[0];if(!c)throw Error(i.failed[0]?.reason||`Transfer failed`);let l=c.transfers?.flatMap(e=>e.state===`unchanged`?[]:[e.backend])??[],u=a.join(`, `);o===`delete`?r(`Deleted from ${u}`):l.length===0?r(`Nothing to do — already on ${u}`):r(`${o===`move`?`Moved to`:`Copied to`} ${l.join(`, `)}${c.transfers?.some(e=>e.state===`pending`)?` (pending sync)`:``}`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),m(null),n?.(),b()}catch(e){i(e instanceof Error?e.message:String(e))}finally{g(!1)}},C=e=>{if((a?.length??0)<=1){f(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&x(e.url)};if(s)return(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let w=a.length===0,T=mo(e);return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(wt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Z.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),w?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,Z.jsx)(qn,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=zg(n.kind),{backend:a,key:o}=Bg(n.url),s=l===n.url;return(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,Z.jsx)(`button`,{onClick:()=>Zr(t,e.id,T||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,Z.jsx)(er,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{onClick:()=>C(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),d===n.url&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Z.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(J,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!1),children:`Also remove index entry`}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>f(null),children:`Cancel`})]})]})]},n.url)}),p&&(0,yf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(Ip,{workspaceId:t,documentCount:1,initialMode:p,defaultFilename:T,saving:h,onConfirm:S,onClose:()=>{h||m(null)}})}),window.document.body)]})}function Hg(e){let t=e.metadata?.geo,n=t?.lat,r=t?.lon;if(n==null||r==null||n===``||r===``)return null;let i=Number(n),a=Number(r);return!Number.isFinite(i)||!Number.isFinite(a)||i===0&&a===0?null:{lat:i,lon:a}}function Ug(e,t,n){let r=!1;for(let i=0,a=n.length-1;i<n.length;a=i++){let o=n[i].lat,s=n[i].lon,c=n[a].lat,l=n[a].lon;o>e!=c>e&&t<(l-s)*(e-o)/(c-o)+s&&(r=!r)}return r}function Wg(e,t,n){if(n.kind===`rect`){let r=n.bbox;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLon&&t<=r.maxLon}return n.points.length>=3&&Ug(e,t,n.points)}function Gg(e,t,n=!1){let r=Hg(e);return r?Wg(r.lat,r.lon,t):n}var Kg=(0,X.lazy)(()=>m(()=>import(`./LocationTab-ARqmeXmv.js`),__vite__mapDeps([23,3,4,24,25]))),qg=[{id:`view`,label:`View`,icon:Vt},{id:`location`,label:`Location`,icon:yt},{id:`metadata`,label:`Metadata`,icon:A},{id:`json`,label:`JSON`,icon:je},{id:`synapses`,label:`Synapses`,icon:_n},{id:`backends`,label:`Backends`,icon:wt}];function Jg({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1}){let s=Eo()!=null,c=Hg(e),l=qg.filter(e=>(e.id!==`location`||c!==null)&&(!s||![`synapses`,`backends`].includes(e.id))),[u,d]=(0,X.useState)(n),f=`${e.id}:${n}`,[p,m]=(0,X.useState)(f);f!==p&&(m(f),d(n));let h=l.some(e=>e.id===u)?u:`view`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[(0,Z.jsx)(cm,{tabs:l,active:h,onChange:d,className:`shrink-0 px-2`,iconOnly:o}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-4`,children:[h===`view`&&(0,Z.jsx)(Mg,{document:e,workspaceId:t,initialEdit:r&&!s,onChanged:i}),h===`location`&&c&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Z.jsx)(Kg,{lat:c.lat,lon:c.lon})}),h===`metadata`&&(0,Z.jsx)(Ig,{document:e,workspaceId:t}),h===`json`&&(0,Z.jsx)(Lg,{document:e,workspaceId:t}),h===`synapses`&&!s&&(0,Z.jsx)(Rg,{document:e,workspaceId:t}),h===`backends`&&!s&&(0,Z.jsx)(Vg,{document:e,workspaceId:t,onChanged:i})]})]})}function Yg(e,t){let[n,r]=(0,X.useState)(null),i=t?.id??null,[a,o]=(0,X.useState)(i);i!==a&&(o(i),r(null));let s=(0,X.useRef)(i);(0,X.useEffect)(()=>{s.current=i},[i]);let c=(0,X.useCallback)(()=>{!e||i==null||Sr(e,i).then(e=>{s.current===i&&e&&r(e)}).catch(()=>{})},[e,i]);return{document:n??t,refresh:c}}function Xg(e){let t=sm(),n=(0,X.useContext)(Rp),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,X.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Z.jsx)(Zg,{...e})}function Zg({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,X.useState)(!1),c=Io(),{document:l,refresh:u}=Yg(r,e);if(Sf(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,yf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:K(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,Z.jsxs)(`div`,{className:K(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-lg md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-lg`),onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:bo(l).title}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=yo(l);return e?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,Z.jsx)(gn,{className:`h-4 w-4`})}):null})(),(0,Z.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)($p.Provider,{value:()=>s(e=>!e),children:(0,Z.jsx)(Jg,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Qg={sortBy:`crud:created`,order:`desc`},$g={"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function e_(e){return $g[e]??e}function t_(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{let t=!1;return Wa(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,X.useMemo)(()=>[...new Set([`crud:created`,`crud:updated`,...t])].map(e=>({value:e,label:e_(e)})),[t])}function n_({workspaceId:e,value:t,onChange:n}){let r=t_(e);return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Z.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by timeline`,children:[!r.some(e=>e.value===t.sortBy)&&(0,Z.jsx)(`option`,{value:t.sortBy,children:e_(t.sortBy)}),r.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending (oldest first)`:`Descending (newest first)`,className:`flex h-7 w-7 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent hover:text-foreground touch-target`,children:t.order===`asc`?(0,Z.jsx)(Rn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(hn,{className:`h-3.5 w-3.5`})})]})}var r_={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},i_=e=>e*1e6;function a_(){try{let e=new Intl.Locale(navigator.language),t=(typeof e.getWeekInfo==`function`?e.getWeekInfo():e.weekInfo)?.firstDay;if(typeof t==`number`&&t>=1&&t<=7)return t}catch{}return 1}function o_(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function s_(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=o_(e);return r.setDate(r.getDate()-n),r}var c_=864e5;function l_(e){let t=a_(),n=o_(e),r=s_(e,t);return{today:n.getTime(),yesterday:n.getTime()-c_,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*c_,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function u_(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:i_(r_.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:i_(r_.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:i_(r_.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:i_(r_.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:i_(r_.lastWeek)};let n=new Date(e),r=n.getFullYear()*12+n.getMonth();if(r===t.month)return{key:`this-month`,label:`Earlier this month`,rank:i_(r_.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:i_(r_.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:i_(r_.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:i_(r_.year)+i}}function d_(e,t,n=`desc`,r=new Date){let i=l_(r),a=new Map;for(let n of e){let e=u_(t(n),i),r=a.get(e.key);r?r.items.push(n):a.set(e.key,{...e,items:[n]})}let o=[...a.values()].sort((e,t)=>n===`asc`?e.rank-t.rank:t.rank-e.rank),s=o.filter(e=>e.key===`unknown`);return s.length?[...o.filter(e=>e.key!==`unknown`),...s]:o}function f_({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,X.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map(e=>({schema:e.schema,schemaVersion:e.schemaVersion,data:e.data,metadata:e.metadata})),l=JSON.stringify(c,null,2),u=async()=>{try{await navigator.clipboard.writeText(l),a(`copied`),setTimeout(()=>a(`idle`),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e),a(`error`),setTimeout(()=>a(`idle`),2e3)}};return(0,yf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,Z.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,Z.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsx)(`div`,{className:`space-y-4`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,Z.jsxs)(J,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,Z.jsx)(Ve,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,Z.jsx)(`textarea`,{className:`w-full h-96 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&u()}},onFocus:e=>e.target.select()})]})}),(0,Z.jsx)(`div`,{className:`mt-8 pt-4 border-t flex justify-end`,children:(0,Z.jsx)(J,{onClick:o,children:`Close`})})]})})}),window.document.body)}function p_({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e.schema||!e.data){c(`Each document must have "schema" and "data" fields`);return}o(!0),await n(a)?(i(``),t()):c(`Failed to import documents`)}catch{c(`Invalid JSON format`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,yf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data containing documents to import`})]}),(0,Z.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,Z.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),className:`w-full h-64 p-3 border rounded-lg font-mono text-sm`,placeholder:`[{"schema": "data/schema/tab", "schemaVersion": "2.0", "data": {...}, "metadata": {...}}]`,disabled:a,autoFocus:!0})]}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,Z.jsx)(J,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,Z.jsx)(J,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function m_({document:e,open:t,onClose:n,onViewDetails:r,onEdit:i,onLink:a,onOpenToSide:o,onRemove:s,onDelete:c}){if(Sf(n,t),!t)return null;let l=bo(e),u=e=>()=>{n(),e()},d=`flex w-full items-center gap-3 rounded-xl border bg-card px-4 py-4 text-base font-medium transition-transform active:scale-[.98]`;return(0,yf.createPortal)((0,Z.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-background animate-in slide-in-from-bottom-10 fade-in duration-200`,onClick:n,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(ep,{document:e,chip:!0}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-base font-semibold`,children:l.title}),(0,Z.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,e.id,` · `,e.schema]})]}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,Z.jsx)(G,{className:`h-5 w-5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 px-4 pt-2`,style:{paddingBottom:`calc(var(--safe-bottom) + 1.25rem)`},onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`button`,{onClick:u(r),className:d,children:[(0,Z.jsx)(Vt,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` View details`]}),i&&(0,Z.jsxs)(`button`,{onClick:u(i),className:d,children:[(0,Z.jsx)(Fe,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Edit`]}),a&&(0,Z.jsxs)(`button`,{onClick:u(a),className:d,children:[(0,Z.jsx)(Gt,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Link to…`]}),o&&(0,Z.jsxs)(`button`,{onClick:u(o),className:d,children:[(0,Z.jsx)(ce,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Open to the side`]}),s&&(0,Z.jsxs)(`button`,{onClick:u(s),className:d,children:[(0,Z.jsx)(G,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Remove from context`]}),c&&(0,Z.jsxs)(`button`,{onClick:u(c),className:`${d} border-destructive/30 text-destructive`,children:[(0,Z.jsx)(lt,{className:`h-5 w-5 shrink-0`}),` Delete permanently`]}),(0,Z.jsx)(`button`,{onClick:n,className:`${d} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function h_({document:e}){let{replicating:t,label:n}=ea(e);return t?(0,Z.jsxs)(`span`,{role:`status`,className:`inline-flex shrink-0 items-center gap-1 rounded-full border bg-muted/60 px-2 py-0.5 text-[11px] font-normal text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),n]}):null}function g_({document:e,isSelected:t,workspaceId:n,onSelect:r,onRemoveDocument:i,onDeleteDocument:a,onLinkDocument:o,onOpenToSide:s,onRightClick:c,onDragStart:l}){let u=_f(),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),_=Eo()!=null,v=gg(e),{replicating:y}=ea(e),b=e.schema===`data/schema/tab`,x=b?e.data.url:null,S=bo(e),C=v_(e),w=C||b_(e),{blobUrl:T}=Lm(n??``,e.id,128,{enabled:w,blobFallback:C,version:e.checksumArray?.[0]??null}),E=t=>{l?.(t,e.id)},D=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),O=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),k=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(b&&x?window.open(x,`_blank`,`noopener,noreferrer`):(m(!1),f(!0)))},A=e=>{e.shiftKey&&e.preventDefault()},j=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),c?.(n,e.id)},M=e=>{e.stopPropagation(),m(!1),f(!0)},N=e=>{e.stopPropagation(),m(!0),f(!0)},P=t=>{t.stopPropagation(),i?.(e.id)},F=t=>{t.stopPropagation(),a?.(e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Gp,{className:`cursor-pointer transition-opacity ${y?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:k,onMouseDown:A,...u,onContextMenu:j,draggable:!0,onDragStart:E,children:[(0,Z.jsx)(qp,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:!!t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}})}),(0,Z.jsx)(qp,{className:`w-12`,children:T?(0,Z.jsx)(`img`,{src:T,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,Z.jsx)(ep,{document:e,chip:!0})}),(0,Z.jsx)(qp,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:S.title,children:S.title}),S.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(h_,{document:e})]}),S.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:S.subtitle,children:S.subtitle})]})}),(0,Z.jsx)(qp,{className:`hidden md:table-cell`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:S.schemaLabel})}),(0,Z.jsx)(qp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,Z.jsx)(qp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:O&&(0,Z.jsx)(`span`,{className:`font-mono`,title:`${O.algo} checksum`,children:O.hash})}),(0,Z.jsx)(qp,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:D(e.createdAt)}),(0,Z.jsxs)(qp,{children:[(0,Z.jsxs)(`div`,{className:`hidden items-center gap-1 md:flex`,children:[(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:M,title:`View document details`,children:(0,Z.jsx)(Vt,{className:`h-4 w-4`})}),v&&!_&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:N,title:`Edit document`,children:(0,Z.jsx)(Fe,{className:`h-4 w-4`})}),o&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:t=>{t.stopPropagation(),o(e.id)},title:`Link document to other paths`,children:(0,Z.jsx)(Gt,{className:`h-4 w-4`})}),s&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:t=>{t.stopPropagation(),s(e)},title:`Open to the side`,children:(0,Z.jsx)(ce,{className:`h-4 w-4`})}),i&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:P,title:`Remove document from context`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:F,title:`Delete document permanently`,className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,className:`md:hidden`,onClick:e=>{e.stopPropagation(),g(!0)},title:`Actions`,"aria-label":`Document actions`,children:(0,Z.jsx)(gt,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(m_,{document:e,open:h,onClose:()=>g(!1),onViewDetails:()=>{m(!1),f(!0)},onEdit:v&&!_?()=>{m(!0),f(!0)}:void 0,onLink:o?()=>o(e.id):void 0,onOpenToSide:s?()=>s(e):void 0,onRemove:i?()=>i(e.id):void 0,onDelete:a?()=>a(e.id):void 0}),(0,Z.jsx)(Xg,{document:e,isOpen:d,onClose:()=>f(!1),workspaceId:n,initialEdit:p})]})}function __({document:e,isSelected:t,workspaceId:n,onSelect:r,onRemoveDocument:i,onDeleteDocument:a,onLinkDocument:o,onOpenToSide:s,onRightClick:c,onDragStart:l}){let u=_f(),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),_=Eo()!=null,v=e.schema===`data/schema/tab`,y=gg(e),{replicating:b}=ea(e),x=v?e.data.url:null,S=bo(e),C=v_(e),w=C||b_(e),{blobUrl:T,loading:E}=Lm(n??``,e.id,128,{enabled:w,blobFallback:C,version:e.checksumArray?.[0]??null}),D=t=>{l?.(t,e.id)},O=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),k=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),A=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(v&&x?window.open(x,`_blank`,`noopener,noreferrer`):(m(!1),f(!0)))},j=e=>{e.shiftKey&&e.preventDefault()},M=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),c?.(n,e.id)},N=e=>{e.stopPropagation(),m(!1),f(!0)},P=e=>{e.stopPropagation(),m(!0),f(!0)},F=t=>{t.stopPropagation(),i?.(e.id)},I=t=>{t.stopPropagation(),a?.(e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`border rounded-lg p-4 transition cursor-pointer ${b?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${v&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:A,onMouseDown:j,...u,onContextMenu:M,draggable:!0,onDragStart:D,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[w&&(0,Z.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:T?(0,Z.jsx)(`img`,{src:T,alt:S.title,loading:`lazy`,className:`h-full w-full object-cover`}):E?(0,Z.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(ep,{document:e})})}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,Z.jsx)(ep,{document:e,chip:!0}),(0,Z.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:S.title,children:S.title}),S.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(`span`,{className:`px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:S.schemaLabel}),(0,Z.jsx)(h_,{document:e})]}),S.subtitle&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:S.subtitle,children:S.subtitle}),S.preview&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:S.preview}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),k&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(Ne,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{className:`font-mono`,title:`${k.algo} checksum`,children:k.hash})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(_e,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{title:`Created: ${O(e.createdAt)}`,children:O(e.createdAt)})]})]})]}),(0,Z.jsxs)(`div`,{className:`hidden items-center gap-2 md:flex`,children:[(0,Z.jsx)(`button`,{onClick:N,className:`p-1 hover:bg-muted rounded-sm`,title:`View document details`,children:(0,Z.jsx)(Vt,{className:`h-4 w-4`})}),y&&!_&&(0,Z.jsx)(`button`,{onClick:P,className:`p-1 hover:bg-muted rounded-sm`,title:`Edit document`,children:(0,Z.jsx)(Fe,{className:`h-4 w-4`})}),o&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(e.id)},className:`p-1 hover:bg-muted rounded-sm`,title:`Link document to other paths`,children:(0,Z.jsx)(Gt,{className:`h-4 w-4`})}),s&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),s(e)},className:`p-1 hover:bg-muted rounded-sm`,title:`Open to the side`,children:(0,Z.jsx)(ce,{className:`h-4 w-4`})}),i&&(0,Z.jsx)(`button`,{onClick:F,className:`p-1 hover:bg-muted rounded-sm`,title:`Remove document from context (keep in database)`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(`button`,{onClick:I,className:`p-1 hover:bg-destructive hover:text-destructive-foreground rounded-sm text-destructive`,title:`Delete document permanently from database`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{onClick:e=>{e.stopPropagation(),g(!0)},className:`p-2 hover:bg-muted rounded-sm md:hidden`,title:`Actions`,"aria-label":`Document actions`,children:(0,Z.jsx)(gt,{className:`h-4 w-4`})})]})}),(0,Z.jsx)(m_,{document:e,open:h,onClose:()=>g(!1),onViewDetails:()=>{m(!1),f(!0)},onEdit:y&&!_?()=>{m(!0),f(!0)}:void 0,onLink:o?()=>o(e.id):void 0,onOpenToSide:s?()=>s(e):void 0,onRemove:i?()=>i(e.id):void 0,onDelete:a?()=>a(e.id):void 0}),(0,Z.jsx)(Xg,{document:e,isOpen:d,onClose:()=>f(!1),workspaceId:n,initialEdit:p})]})}function v_(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function y_(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function b_(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function x_({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=go(e,t),[a,o]=(0,X.useState)(!1);return i||a?(0,Z.jsx)(Z.Fragment,{children:n}):r?(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,Z.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,Z.jsx)(Oe,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function S_({document:e,workspaceId:t,markdown:n}){let r=(0,X.useRef)(null),[i,a]=(0,X.useState)(()=>typeof IntersectionObserver>`u`);(0,X.useEffect)(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(a(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let{text:o,loading:s,error:c}=Oo(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,Z.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,Z.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,Z.jsx)(Km,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,Z.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,Z.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,Z.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,Z.jsx)(ep,{document:e,size:10,chip:!0}),i&&s&&(0,Z.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function C_({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onDragStart:o}){let s=_f(),[c,l]=(0,X.useState)(!1),u=e.schema===`data/schema/tab`,d=u?e.data.url:null,f=v_(e),p=y_(e),m=f||b_(e),h=bo(e),g=so(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||mo(e)),_=e.schema===`data/schema/file`&&(g===`markdown`||g===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,v=!m&&e.schema!==`data/schema/file`&&!!(h.preview||h.subtitle),{replicating:y}=ea(e),{blobUrl:b,loading:x}=Lm(n??``,e.id,768,{enabled:m,blobFallback:f,version:e.checksumArray?.[0]??null}),S=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&r(e.id,!i||!t,i),i||(u&&d?window.open(d,`_blank`,`noopener,noreferrer`):l(!0))},C=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-lg border transition cursor-pointer hover:shadow-elevation-2 ${y?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:S,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...s,onContextMenu:C,draggable:!0,onDragStart:t=>o?.(t,e.id),title:h.title,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`absolute left-2 top-2 z-10 h-4 w-4 cursor-pointer accent-primary ${t?``:`reveal-on-hover`}`,checked:t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}}),(0,Z.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${m&&b||v||_&&n||p&&n?``:`aspect-square`}`,children:[m&&x&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),m&&b?(0,Z.jsx)(`img`,{src:b,alt:h.title,loading:`lazy`,className:`block h-auto w-full`}):p&&n?(0,Z.jsx)(x_,{workspaceId:n,documentId:e.id,fallback:(0,Z.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,Z.jsx)(ep,{document:e,size:10,chip:!0})})}):_&&n?(0,Z.jsx)(S_,{document:e,workspaceId:n,markdown:g===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):v?(0,Z.jsxs)(`div`,{className:`flex min-h-28 w-full flex-col gap-1.5 overflow-hidden bg-card p-3 pt-7 text-left`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(ep,{document:e}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:h.schemaLabel})]}),(0,Z.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:h.title}),h.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:h.subtitle}),(0,Z.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:h.preview})]}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(ep,{document:e,size:10,chip:!0})}),i&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`absolute right-2 top-2 rounded-sm bg-scrim p-1 text-scrim-foreground reveal-on-hover`,title:`Open to the side`,children:(0,Z.jsx)(ce,{className:`h-3.5 w-3.5`})})]}),!v&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:h.title,children:h.title}),h.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,Z.jsx)(Xg,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function w_(e,t,n,r){let[i,a]=(0,X.useState)(!1),o=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:i,onDragOver:e=>{!t||!o(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,i||a(!0))},onDragLeave:()=>a(!1),onDrop:async i=>{if(a(!1),!t||!o(i))return;i.preventDefault(),i.stopPropagation();let s=null;try{s=JSON.parse(i.dataTransfer.getData(`application/json`))}catch{s=null}if(!(s?.type!==`document`||!Array.isArray(s.documentIds)||s.documentIds.length===0))try{await t(e.path,s.documentIds,{move:!1,sourcePath:s.sourcePath??n,sourceTreeName:s.sourceTreeName??r})}catch{}}}}function T_({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,Z.jsx)(O,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,Z.jsx)(ge,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var E_=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function D_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=w_(e,n,r,i);return(0,Z.jsxs)(`button`,{type:`button`,title:E_(e),onClick:()=>t?.(e.path),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,className:`folder-surface group flex min-w-0 max-w-full items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm transition-colors hover:bg-accent ${a.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,Z.jsx)(T_,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,Z.jsx)(O,{className:`hidden h-4 w-4 group-hover:block`}):(0,Z.jsx)(Ae,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function O_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=w_(e,n,r,i),o=e.color?{color:e.color}:void 0;return(0,Z.jsxs)(`button`,{type:`button`,title:E_(e),onClick:()=>t?.(e.path),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-lg border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${a.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,Z.jsx)(O,{className:`h-10 w-10`,strokeWidth:1.5}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ge,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:o}),(0,Z.jsx)(Ae,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:o})]})}),(0,Z.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function k_({folders:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-4 grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(O_,{folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i},e.path))})}function A_({folders:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(D_,{folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i},e.path))})}function j_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=w_(e,n,r,i);return(0,Z.jsxs)(Gp,{className:`cursor-pointer ${a.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:e=>e.stopPropagation(),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,title:E_(e),children:[(0,Z.jsx)(qp,{className:`w-10`}),(0,Z.jsx)(qp,{className:`w-12`,children:(0,Z.jsx)(T_,{folder:e})}),(0,Z.jsx)(qp,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,Z.jsx)(qp,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,Z.jsx)(qp,{className:`hidden lg:table-cell`}),(0,Z.jsx)(qp,{className:`hidden lg:table-cell`}),(0,Z.jsx)(qp,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,Z.jsx)(qp,{className:`w-12 md:w-auto`})]})}function M_({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,Z.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-1 mb-2 flex items-center gap-2 bg-background/95 px-1 py-1.5 backdrop-blur-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 cursor-pointer accent-primary ${r||i?``:`reveal-on-hover`}`,checked:r,ref:e=>{e&&(e.indeterminate=i&&!r)},onChange:e=>o(e.target.checked),title:`Select everything in "${e}"`,onClick:e=>e.stopPropagation()}),(0,Z.jsxs)(`button`,{type:`button`,onClick:a,"aria-expanded":!n,className:`flex min-w-0 items-center gap-1.5 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,Z.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function N_({documents:e,isLoading:t,contextPath:n,treeName:r,workspaceId:i,totalCount:a,onRemoveDocument:o,onDeleteDocument:s,onDestroyDocument:c,onRemoveDocuments:l,onDeleteDocuments:u,onDestroyDocuments:d,onCopyDocuments:f,onCutDocuments:p,onPasteDocuments:m,onImportDocuments:h,onSelectionChange:g,pastedDocumentIds:_,viewMode:v=`card`,allowViewToggle:y=!1,activeContextUrl:x,currentContextUrl:S,currentPage:C=1,pageSize:T=50,onPageChange:E,onPageSizeChange:D,onPurgeDocuments:O,disablePurgeDocuments:A=!1,backendSearchQueries:j=[],onBackendSearch:M,onRemoveBackendQuery:N,serverSort:P,onServerSortChange:F,scope:I=`path`,onScopeChange:ee,canSaveChanges:te=!1,isSavingChanges:ne=!1,onSaveChanges:ie,linkTree:L,folders:R,onOpenFolder:ae}){let[ce,z]=(0,X.useState)(()=>{if(!y)return v;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return v}),le=y?ce:v,ue=(0,X.useCallback)(e=>{z(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[de,fe]=(0,X.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),pe=(0,X.useCallback)(()=>{fe(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[me,he]=(0,X.useState)(new Set),ge=(0,X.useCallback)(e=>{he(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[_e,ye]=(0,X.useState)(new Set),[B,be]=(0,X.useState)(null),[V,xe]=(0,X.useState)(null),Se=Io(),Ce=!!(Se&&i),U=(0,X.useCallback)(t=>{if(!Se||!i)return;let n=t.map(t=>e.find(e=>e.id===t)).filter(e=>!!e);n.length!==0&&Se.openAddRelated({workspaceName:i,documents:n})},[Se,i,e]),[W,we]=(0,X.useState)(!1),[Te,Ee]=(0,X.useState)(null),[De,Oe]=(0,X.useState)(!1),[ke,Ae]=(0,X.useState)(!1),[je,Me]=(0,X.useState)(null),[Ne,Pe]=(0,X.useState)(null),Ie=Eo()==null&&!!i,[Le,Re]=(0,X.useState)(null),ze=!!(L&&m),Be=!!i,{showSuccessToast:He,showErrorToast:Ue}=to(),We=Bp(),Ke=i?e=>We.open(e,i):void 0,qe=I===`workspace`,Je=qe?void 0:o,Xe=qe?void 0:l,[Ze,Qe]=(0,X.useState)(null),[$e,et]=(0,X.useState)(!1),[tt,nt]=(0,X.useState)(!1),[rt,it]=(0,X.useState)(!1),[at,ot]=(0,X.useState)(``),[st,ct]=(0,X.useState)(!1),ut=j.length>0,dt=(0,X.useRef)(null),ft=(0,X.useCallback)(()=>{ot(``),dt.current&&(dt.current.value=``)},[]);(0,X.useEffect)(()=>{if(!y||window.matchMedia(`(max-width: 767px)`).matches)return;let e=dt.current;if(!e)return;let t=setTimeout(()=>e.focus(),60);return()=>clearTimeout(t)},[y]);let[pt,mt]=(0,X.useState)(n);n!==pt&&(mt(n),ye(new Set)),(0,X.useEffect)(()=>{let e=()=>{ze&&_e.size>0&&xe(Array.from(_e))};return window.addEventListener(`workspace:documents:link-selection`,e),()=>window.removeEventListener(`workspace:documents:link-selection`,e)},[ze,_e]),(0,X.useEffect)(()=>{g?.(Array.from(_e))},[_e,g]);let gt=(0,X.useCallback)(()=>{if(!M)return;let e=at.trim();e&&(M(e),ft())},[M,at,ft]),_t=(0,X.useCallback)(()=>{ft(),N&&j.length>0&&N(-1)},[N,j.length,ft]),vt=(0,X.useCallback)((e,t)=>{let i;_e.has(t)&&_e.size>1?i=Array.from(_e):(i=[t],ye(new Set([t])));let a={type:`document`,documentIds:i,sourcePath:n,sourceTreeName:r};e.dataTransfer.setData(`application/json`,JSON.stringify(a)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[_e,n,r]),yt=(0,X.useCallback)(async e=>{if(!m)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let r=null;try{r=JSON.parse(t)}catch{return}r?.type!==`document`||!Array.isArray(r.documentIds)||r.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),ct(!1),await m(n,r.documentIds,{move:e.shiftKey,sourcePath:r.sourcePath,sourceTreeName:r.sourceTreeName}),ye(new Set))},[n,m]),xt=(0,X.useCallback)(e=>{m&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,ct(!0))},[m]),St=(0,X.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||ct(!1)},[]),Ct=(0,X.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2},{name:`schema`,weight:.1}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),wt=(0,X.useMemo)(()=>e.length===0?null:new Po(e,Ct),[e,Ct]),Tt=(0,X.useDeferredValue)(at),Et=(0,X.useMemo)(()=>!Tt.trim()||!wt?e:wt.search(Tt).map(e=>e.item),[e,Tt,wt]),Dt=(0,X.useMemo)(()=>!R||R.length===0||Tt.trim()?[]:R,[R,Tt]),At=Dt.length>0,Mt={folders:Dt,onOpen:ae,onPasteDocuments:m,contextPath:n,treeName:r},{sorted:Nt,sort:Pt,toggleSort:Ft}=Xp(Et,(0,X.useMemo)(()=>({title:e=>bo(e).title?.toLowerCase()??``,schema:e=>bo(e).schemaLabel??``,type:e=>(e.metadata?.contentType||e.schema||``).toLowerCase(),id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),It=(0,X.useCallback)(e=>{let t=P?.sortBy===`crud:updated`?e.updatedAt:e.createdAt,n=Date.parse(t??``);return Number.isNaN(n)?null:n},[P?.sortBy]),Lt=(0,X.useMemo)(()=>d_(Et,It,P?.order===`asc`?`asc`:`desc`),[Et,It,P?.order]),zt=de&&Lt.length>1,Bt=(0,X.useCallback)((e,t)=>{ye(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),Ht=(0,X.useMemo)(()=>(le===`table`?Nt:zt?Lt.filter(e=>!me.has(e.key)).flatMap(e=>e.items):Et).map(e=>e.id),[le,Nt,zt,Lt,me,Et]),Ut=(0,X.useRef)(null),Wt=JSON.stringify([i,n,r,C]),Kt=(0,X.useCallback)((e,t,n,r=!1)=>{let i=Ut.current,a=i?.scope===Wt&&Ht.includes(i.id)?i.id:null;(!r||a===null)&&(Ut.current={scope:Wt,id:e}),ye(i=>{if(r)return vf(Ht,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[Wt,Ht]),qt=(0,X.useCallback)((e,t)=>{if(e.target.closest?.(`[role="dialog"]`))return;e.preventDefault(),e.stopPropagation();let n;_e.has(t)?n=Array.from(_e):(n=[t],ye(new Set([t]))),be({x:e.clientX,y:e.clientY,documentIds:n})},[_e]),Jt=(0,X.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){we(!0);try{for(let n of t)await Xi(i,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;He(`Created ${n} relation${n===1?``:`s`}`),Qp(),xe(null)}catch(e){Ue(e instanceof Error?e.message:`Failed to create relations`)}finally{we(!1)}}},[i,He,Ue]),Yt=(0,X.useCallback)(async(e,t,n)=>{if(m){for(let r of e)await m(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});ye(new Set)}},[m]),Zt=(0,X.useCallback)(async(e,t,n)=>{if(!(!i||!Te)){Oe(!0);try{let r=await Pi(i,Te.ids,{to:e,mode:t,keepDocument:n.keepDocument,folder:n.folder,filename:n.filename,onConflict:n.onConflict}),a=r.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,o=r.successful.length-a,s=r.failed.length,c=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,l=e.join(`, `),u=[a?`${a} already there`:null,s?`${s} skipped`:null].filter(Boolean).join(` · `);o>0?He(`${c} ${l}: ${o} document${o===1?``:`s`}${u?` · ${u}`:``}`):a>0?He(`Nothing to do — already on ${l}`):s>0&&Ue(r.failed[0]?.reason||`Transfer failed`),s>0&&console.warn(`Backend transfer skipped documents:`,r.failed),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),Ee(null),ye(new Set)}catch(e){Ue(e instanceof Error?e.message:String(e))}finally{Oe(!1)}}},[i,Te,He,Ue]),Qt=(0,X.useCallback)(async(t,n)=>{switch(t){case`edit`:if(n.length===1){let t=e.find(e=>e.id===n[0]);if(t){Re({document:t,edit:!0}),be(null);return}}break;case`copy`:f?.(n);break;case`cut`:p?.(n);break;case`link-to`:xe(n),be(null);return;case`add-related`:U(n),be(null);return;case`remove`:n.length===1?o?.(n[0]):l?.(n);break;case`delete`:n.length===1?s?.(n[0]):u?.(n);break;case`destroy`:n.length===1?c?.(n[0]):d?.(n);break;case`view-details`:if(n.length===1){let t=e.find(e=>e.id===n[0]);if(t){Re({document:t}),be(null);return}}break;case`open-url`:if(n.length===1){let t=e.find(e=>e.id===n[0]);t&&t.schema===`data/schema/tab`&&t.data.url&&window.open(t.data.url,`_blank`,`noopener,noreferrer`)}break;case`copy-id`:if(n.length===1)try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(n[0].toString());else{let e=document.createElement(`textarea`);e.value=n[0].toString(),document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e)}}catch(e){console.error(`Failed to copy ID to clipboard:`,e);let t=document.createElement(`textarea`);t.value=n[0].toString(),document.body.appendChild(t),t.select(),document.execCommand(`copy`),document.body.removeChild(t)}}be(null),ye(new Set)},[f,p,o,l,s,u,c,d,e,U]),$t=(0,X.useCallback)(e=>{e.target.closest?.(`[role="dialog"]`)||!(_&&_.length>0&&m)&&!h||(e.preventDefault(),e.stopPropagation(),Qe({x:e.clientX,y:e.clientY}))},[_,m,h]),en=(0,X.useCallback)(async()=>{if(!(!m||!_||_.length===0))try{await m(n,_)}catch(e){console.error(`Failed to paste documents:`,e)}finally{Qe(null)}},[m,_,n]),tn=(0,X.useCallback)(()=>{_e.size===Et.length?ye(new Set):ye(new Set(Et.map(e=>e.id)))},[_e.size,Et]),rn=(0,X.useCallback)(async e=>{if(!h)return!1;try{return await h(e,n)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[h,n]),an=e=>zt?Lt.map(t=>{let n=me.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!_e.has(t),0);return(0,Z.jsxs)(`section`,{className:`group mb-4`,children:[(0,Z.jsx)(M_,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>ge(t.key),onSelectAll:e=>Bt(r,e)}),!n&&e(t.items)]},t.key)}):e(Et);return t?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})}):(0,Z.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0 p-4 rounded-lg transition-colors ${st?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:xt,onDragLeave:St,onDrop:yt,children:[(0,Z.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,Z.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:at?`${Et.length} of ${e.length}`:`${a.toLocaleString()} document${a===1?``:`s`}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{className:`min-w-0 truncate`,children:[`Context: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n}),x&&S&&x!==S&&(0,Z.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,Z.jsxs)(`p`,{className:`shrink-0`,children:[_e.size>0&&(0,Z.jsxs)(`span`,{className:`text-info`,children:[_e.size,` selected`]}),_e.size>0&&(at||a>T)&&(0,Z.jsx)(`span`,{className:`mx-1`,children:`·`}),at?`on this page`:a>T?`Showing ${Math.min((C-1)*T+1,a)}–${Math.min(C*T,a)}`:null]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[ee&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>ee(`path`),className:`px-2.5 py-2 transition-colors ${I===`path`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List documents in the selected path`,children:`This path`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>ee(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${I===`workspace`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List every document in the workspace (staging excluded)`,children:[(0,Z.jsx)(oe,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),y&&(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,Rt,`Table view`],[`tile`,dr,`Tile view`],[`card`,ht,`Card view`]].map(([e,t,n])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>ue(e),title:n,"aria-pressed":le===e,className:`rounded-sm p-1.5 transition-colors ${le===e?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(t,{className:`h-4 w-4`})},e))}),y&&le!==`table`&&(0,Z.jsx)(`button`,{type:`button`,onClick:pe,title:de?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":de,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors ${de?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(Nn,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,Z.jsx)(pr,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,Z.jsx)(`input`,{ref:dt,type:`text`,placeholder:M?ut?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,defaultValue:``,onChange:e=>ot(e.target.value),onFocus:e=>{let t=e.currentTarget;window.matchMedia(`(max-width: 767px)`).matches&&setTimeout(()=>t.scrollIntoView({block:`center`,behavior:`smooth`}),250)},onKeyDown:e=>{e.key===`Enter`&&M&&(e.preventDefault(),gt())},className:`w-full pl-10 pr-9 py-2 border border-input rounded-md bg-background text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent`}),(at||ut)&&(0,Z.jsx)(`button`,{onClick:_t,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]}),M&&at.trim()&&!j.includes(at.trim())&&(0,Z.jsxs)(J,{size:`sm`,variant:`default`,onClick:gt,className:`shrink-0`,title:ut?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,Z.jsx)(pr,{className:`h-3.5 w-3.5 mr-1`}),ut?`Refine`:`Search server`]}),te&&ie&&(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:ie,disabled:ne,className:`shrink-0`,title:`Save current query and filters`,children:[(0,Z.jsx)(k,{className:`h-3.5 w-3.5 mr-1`}),ne?`Saving...`:`Save filters`]})]}),ut&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),j.map((e,t)=>(0,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),N&&(0,Z.jsx)(`button`,{onClick:()=>N(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),N&&j.length>1&&(0,Z.jsx)(`button`,{onClick:()=>N(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),E&&a>0&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mt-3 pt-3 border-t max-sm:flex-nowrap max-sm:gap-1`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Show:`}),(0,Z.jsxs)(`select`,{value:T,onChange:e=>D?.(Number(e.target.value)),className:`h-control-sm rounded-(--input-radius) border-(length:--input-border-width) border-input bg-background px-2 text-sm focus-ring`,children:[(0,Z.jsx)(`option`,{value:25,children:`25`}),(0,Z.jsx)(`option`,{value:50,children:`50`}),(0,Z.jsx)(`option`,{value:100,children:`100`}),(0,Z.jsx)(`option`,{value:200,children:`200`})]}),(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`per page`})]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 max-sm:gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((C-1)*T+1,a),` - `,Math.min(C*T,a),` of `,a]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(1),disabled:C===1,className:`p-1 touch-target`,children:(0,Z.jsx)(w,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(C-1),disabled:C===1,className:`p-1 touch-target`,children:(0,Z.jsx)(se,{className:`h-4 w-4`})}),(0,Z.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),C,(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,Z.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(a/T)]}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(C+1),disabled:C>=Math.ceil(a/T),className:`p-1 touch-target`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(Math.ceil(a/T)),disabled:C>=Math.ceil(a/T),className:`p-1 touch-target`,children:(0,Z.jsx)(gr,{className:`h-4 w-4`})})]})]})]}),e.length>0&&(0,Z.jsxs)(`div`,{className:`mt-3 pt-3 border-t`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>et(e=>!e),"aria-expanded":$e,className:`flex w-full items-center justify-between gap-2 rounded-md border px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-accent/50 sm:hidden`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(kt,{className:`h-3.5 w-3.5`}),`Actions`,_e.size>0?` (${_e.size} selected)`:``]}),(0,Z.jsx)(Ge,{className:`h-3.5 w-3.5 transition-transform ${$e?`rotate-180`:``}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap ${$e?`max-sm:mt-2`:`max-sm:hidden`}`,children:[F&&P&&i&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(n_,{workspaceId:i,value:P,onChange:F})]}),le!==`table`&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:tn,className:`flex items-center gap-2`,disabled:Et.length===0,children:_e.size===Et.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Tn,{className:`h-4 w-4`}),`Deselect Page`,at&&` (${Et.length})`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(nn,{className:`h-4 w-4`}),`Select Page`,at&&` (${Et.length})`]})}),O&&a>0&&_e.size===0&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:O,disabled:A||!!at,className:`flex items-center gap-2 text-destructive hover:text-destructive-foreground hover:bg-destructive`,title:A||at?`Purge is disabled while local search is active`:`Delete all documents matching the current server-side filters across all pages`,children:[(0,Z.jsx)(lt,{className:`h-4 w-4`}),`Purge All (`,a,`)`]}),_e.size>0&&(0,Z.jsxs)(Z.Fragment,{children:[Ie&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Pe(Array.from(_e)),children:[(0,Z.jsx)(Fe,{className:`mr-2 h-4 w-4`}),`Bulk Edit… (`,_e.size,`)`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{let e=Array.from(_e);f?.(e)},className:`flex items-center gap-2`,title:`Copy selected documents`,children:[(0,Z.jsx)(Ve,{className:`h-4 w-4`}),`Copy (`,_e.size,`)`]}),ze&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>xe(Array.from(_e)),className:`flex items-center gap-2`,title:`Link selected documents to another path`,children:[(0,Z.jsx)(Gt,{className:`h-4 w-4`}),`Link to… (`,_e.size,`)`]}),Ie&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Me(Array.from(_e)),children:[(0,Z.jsx)(Ve,{className:`mr-1 h-4 w-4`}),`Copy to workspace…`]}),Ce&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>U(Array.from(_e)),className:`flex items-center gap-2`,title:`Create a new document related to the selected ones`,children:[(0,Z.jsx)(H,{className:`h-4 w-4`}),`Add related… (`,_e.size,`)`]}),Be&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Ee({ids:Array.from(_e),mode:`copy`}),className:`flex items-center gap-2`,title:`Copy, move, or delete the file data on storage backends`,children:[(0,Z.jsx)(hr,{className:`h-4 w-4`}),`Backends… (`,_e.size,`)`]}),p&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{p(Array.from(_e))},className:`flex items-center gap-2`,title:`Cut selected documents`,children:[(0,Z.jsx)(lr,{className:`h-4 w-4`}),`Cut (`,_e.size,`)`]}),(o||l)&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,disabled:qe,onClick:()=>{let e=Array.from(_e);e.length===1?Je?.(e[0]):Xe?.(e),ye(new Set)},className:`flex items-center gap-2`,title:qe?`Switch to “This path” to remove documents from a folder`:`Remove selected documents from this folder (kept in index)`,children:[(0,Z.jsx)(G,{className:`h-4 w-4`}),`Remove (unlink) from folder (`,_e.size,`)`]}),(s||u)&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{let e=Array.from(_e);e.length===1?s?.(e[0]):u?.(e),ye(new Set)},className:`flex items-center gap-2 text-destructive hover:text-destructive-foreground hover:bg-destructive`,title:`Delete from index (data stays on backends)`,children:[(0,Z.jsx)(lt,{className:`h-4 w-4`}),`Delete from index (`,_e.size,`)`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>nt(!0),className:`flex items-center gap-2`,title:`Export selected documents`,children:[(0,Z.jsx)(er,{className:`h-4 w-4`}),`Export (`,_e.size,`)`]})]}),_&&_.length>0&&m&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(n,_),className:`flex items-center gap-2`,title:`Paste documents to current context`,children:[(0,Z.jsx)(b,{className:`h-4 w-4`}),`Paste (`,_.length,`)`]}),_e.size===0&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>nt(!0),className:`flex items-center gap-2`,title:`Export all documents`,children:[(0,Z.jsx)(er,{className:`h-4 w-4`}),`Export All`]}),h&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>it(!0),className:`flex items-center gap-2`,title:`Import documents`,children:[(0,Z.jsx)(re,{className:`h-4 w-4`}),`Import`]}),m&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Ae(!0),className:`flex items-center gap-2`,title:`Browse and add existing documents to this folder`,children:[(0,Z.jsx)(Ot,{className:`h-4 w-4`}),`Add existing…`]})]})]})]}),Et.length===0&&!At?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,onContextMenu:$t,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(bt,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:at?`No documents match your search`:`No documents found in this context`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:at?(0,Z.jsxs)(Z.Fragment,{children:[`Search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,at,`"`]})]}):(0,Z.jsxs)(Z.Fragment,{children:[`Path: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n})]})}),at&&(0,Z.jsx)(`button`,{onClick:ft,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!at&&_&&_.length>0&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click to paste `,_.length,` document(s)`]})]})}):le===`tile`?(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:$t,children:[(0,Z.jsx)(k_,{...Mt}),Et.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),an(e=>(0,Z.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,Z.jsx)(C_,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Kt,onRemoveDocument:Je,onDeleteDocument:s,onLinkDocument:ze?e=>xe([e]):void 0,onOpenToSide:Ke,onRightClick:qt,onDragStart:vt},e.id))}))]}):le===`table`?(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:$t,children:(0,Z.jsxs)(Vp,{children:[(0,Z.jsx)(Hp,{children:(0,Z.jsxs)(Gp,{children:[(0,Z.jsx)(Kp,{className:`w-10`,children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:Et.length>0&&_e.size===Et.length,ref:e=>{e&&(e.indeterminate=_e.size>0&&_e.size<Et.length)},onChange:tn,title:`Select all on this page`})}),(0,Z.jsx)(Yp,{label:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:Pt,onSort:Ft,className:`w-12`}),(0,Z.jsx)(Yp,{label:`Title`,sortKey:`title`,sort:Pt,onSort:Ft,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,Z.jsx)(Yp,{label:`Schema`,sortKey:`schema`,sort:Pt,onSort:Ft,className:`hidden md:table-cell`}),(0,Z.jsx)(Yp,{label:`ID`,sortKey:`id`,sort:Pt,onSort:Ft,className:`hidden lg:table-cell`}),(0,Z.jsx)(Kp,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,Z.jsx)(Yp,{label:`Created`,sortKey:`created`,sort:Pt,onSort:Ft,className:`hidden sm:table-cell`}),(0,Z.jsx)(Kp,{className:`w-12 md:w-auto`,children:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,Z.jsxs)(Up,{children:[Dt.map(e=>(0,Z.jsx)(j_,{folder:e,onOpen:ae,onPasteDocuments:m,contextPath:n,treeName:r},e.path)),Nt.map(e=>(0,Z.jsx)(g_,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Kt,onRemoveDocument:Je,onDeleteDocument:s,onLinkDocument:ze?e=>xe([e]):void 0,onOpenToSide:Ke,onRightClick:qt,onDragStart:vt},e.id))]})]})}):(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:$t,children:[(0,Z.jsx)(A_,{...Mt}),Et.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),an(e=>(0,Z.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,Z.jsx)(`div`,{onContextMenu:t=>{t.stopPropagation(),qt(t,e.id)},children:(0,Z.jsx)(__,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Kt,onRemoveDocument:Je,onDeleteDocument:s,onLinkDocument:ze?e=>xe([e]):void 0,onOpenToSide:Ke,onRightClick:qt,onDragStart:vt})},e.id))}))]}),B&&(0,Z.jsxs)(Cf,{x:B.x,y:B.y,onClose:()=>be(null),className:`bg-background border rounded-lg shadow-elevation-3 py-1 min-w-[120px]`,children:[(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`copy`,B.documentIds),children:[(0,Z.jsx)(Ve,{className:`h-3 w-3`}),`Copy `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),Ie&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Me(B.documentIds),be(null)},children:[(0,Z.jsx)(Ve,{className:`h-3 w-3`}),`Copy to workspace…`]}),p&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`cut`,B.documentIds),children:[(0,Z.jsx)(lr,{className:`h-3 w-3`}),`Cut `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),ze&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`link-to`,B.documentIds),children:[(0,Z.jsx)(Gt,{className:`h-3 w-3`}),`Link to… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),Ie&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Pe(B.documentIds),be(null)},children:[(0,Z.jsx)(Fe,{className:`h-3 w-3`}),`Bulk Edit… (`,B.documentIds.length,`)`]}),Ce&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`add-related`,B.documentIds),children:[(0,Z.jsx)(H,{className:`h-3 w-3`}),`Add related document… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),B.documentIds.length===1&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`view-details`,B.documentIds),children:[(0,Z.jsx)(Vt,{className:`h-3 w-3`}),`View Details`]}),(()=>{let t=e.find(e=>e.id===B.documentIds[0]);return t?.schema===`data/schema/note`||t?.schema===`data/schema/link`?(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`edit`,B.documentIds),children:[(0,Z.jsx)(Fe,{className:`h-3 w-3`}),`Edit`]}):null})(),(()=>{let t=e.find(e=>e.id===B.documentIds[0]);return t?.schema===`data/schema/tab`&&t?.data.url?(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`open-url`,B.documentIds),children:[(0,Z.jsx)(gn,{className:`h-3 w-3`}),`Open URL`]}):null})(),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`copy-id`,B.documentIds),children:[(0,Z.jsx)(Xt,{className:`h-3 w-3`}),`Copy ID`]})]}),(Je||Xe)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Unlinks from this folder; the document stays in the index`,onClick:()=>Qt(`remove`,B.documentIds),children:[(0,Z.jsx)(ve,{className:`h-3 w-3`}),`Remove (unlink) from folder `,B.documentIds.length>1?`(${B.documentIds.length})`:``]})]}),(s||u)&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2 text-destructive`,title:`Removes the document from the index entirely; file data stays on its backend(s)`,onClick:()=>Qt(`delete`,B.documentIds),children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from index `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),Be&&B.documentIds.some(t=>(e.find(e=>e.id===t)?.locations?.length??0)>0)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsx)(`div`,{className:`px-3 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Backends`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Copy the file data to another storage backend (keeps the existing copies)`,onClick:()=>{Ee({ids:B.documentIds,mode:`copy`}),be(null)},children:[(0,Z.jsx)(hr,{className:`h-3 w-3`}),`Copy to backend… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Move the file data to another storage backend (source released once the copy is durable)`,onClick:()=>{Ee({ids:B.documentIds,mode:`move`}),be(null)},children:[(0,Z.jsx)(jt,{className:`h-3 w-3`}),`Move to backend… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-destructive hover:text-destructive-foreground text-sm flex items-center gap-2 text-destructive font-medium`,title:`Delete the file data from selected backends (copies elsewhere are kept)`,onClick:()=>{Ee({ids:B.documentIds,mode:`delete`}),be(null)},children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from backend… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]})]}),!Be&&(c||d)&&B.documentIds.some(t=>(e.find(e=>e.id===t)?.locations?.length??0)>0)&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-destructive hover:text-destructive-foreground text-sm flex items-center gap-2 text-destructive font-medium`,title:`Deletes the document and its file data from the storage backend(s)`,onClick:()=>Qt(`destroy`,B.documentIds),children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from backend(s) `,B.documentIds.length>1?`(${B.documentIds.length})`:``]})]}),Ze&&(0,Z.jsxs)(Cf,{x:Ze.x,y:Ze.y,onClose:()=>Qe(null),className:`bg-background border rounded-lg shadow-elevation-3 py-1 min-w-[120px]`,children:[_&&_.length>0&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:en,children:[(0,Z.jsx)(b,{className:`h-3 w-3`}),`Paste Documents (`,_.length,`)`]}),h&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Qe(null),it(!0)},children:[(0,Z.jsx)(re,{className:`h-3 w-3`}),`Import Documents`]})]}),(0,Z.jsx)(f_,{isOpen:tt,onClose:()=>nt(!1),documents:e,selectedDocuments:_e}),(0,Z.jsx)(p_,{isOpen:rt,onClose:()=>it(!1),onImport:rn}),je&&i&&(0,Z.jsx)(hp,{workspaceId:i,ids:je,onClose:()=>Me(null)}),V&&L&&(0,Z.jsx)(pp,{onClose:()=>xe(null),children:(0,Z.jsx)(dp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,documentCount:V.length,fixedWorkspaceName:i,tabs:[`context`,`directory`,`relations`],saving:W,relationExcludeIds:new Set(V),onConfirm:(e,t)=>Yt(e,V,t),onConfirmRelation:e=>Jt(e,V),onClose:()=>xe(null)})}),Te&&i&&(0,yf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(Ip,{workspaceId:i,documentCount:Te.ids.length,initialMode:Te.mode,defaultFilename:Te.ids.length===1?mo(e.find(e=>e.id===Te.ids[0])??{}):``,saving:De,onConfirm:Zt,onClose:()=>{De||Ee(null)}})}),window.document.body),ke&&m&&(0,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>Ae(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(Lp,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:i,onConfirm:async e=>{await m(n,e),Ae(!1)},onClose:()=>Ae(!1)})})]}),window.document.body),Ne&&i&&(0,Z.jsx)(jp,{workspaceId:i,documentIds:Ne,onClose:()=>Pe(null)}),(0,Z.jsx)(Xg,{document:Le?.document??null,isOpen:!!Le,onClose:()=>Re(null),workspaceId:i,initialEdit:Le?.edit})]})}function P_(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,X.useState)(e.canvasQueries??[]),a=(0,X.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,X.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,X.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,X.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,X.useCallback)(()=>o([]),[o])}}function F_({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,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(1),[u,d]=(0,X.useState)(!0),f=t.canvasSort??Qg,{queries:p,runSearch:m,removeQuery:h}=P_(t,()=>l(1));(0,X.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,X.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(n_,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsx)(N_,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}pf({type:`documents-table`,name:`Documents`,icon:Rt,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:F_});function I_({config:e,setConfig:t,canvas:n}){let[r,i]=(0,X.useState)(()=>new Date),a=e.format!==`24`;return(0,X.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,Z.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,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,Z.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`})]})}pf({type:`clock`,name:`Clock`,icon:cn,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:I_});var L_=450,R_=10;function z_(e,t){let{open:n}=Sg(),r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.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()},L_))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>R_&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function B_({doc:e,workspaceId:t}){let n=bo(e),{activationProps:r}=z_(e,t);return(0,Z.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,Z.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function V_({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null);return(0,X.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,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,Z.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,Z.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,Z.jsx)(B_,{doc:e,workspaceId:t.workspaceId},e.id))})}pf({type:`recent-documents`,name:`Recent documents`,icon:Bn,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:V_});function H_({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,Z.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`})}pf({type:`note`,name:`Note`,icon:xn,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:H_});var U_=`data/schema/file`,W_=`data/schema/drawing`;function G_(e){return(e.schema===U_||e.schema===W_)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function K_(e){return e.schema===U_&&String(e.metadata?.contentType||``).startsWith(`video/`)}var q_=`data/mime/image`;function J_(e,t,n=!1){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(1),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=P_(e,()=>c(1)),y=e.canvasSort??Qg;(0,X.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:[q_,`data/mime/video`]}:{allOf:[q_]}});if(r)return;i((a.payload||[]).filter(e=>G_(e)||n&&K_(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,X.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,X.useCallback)(()=>{m(``),v()},[v]),S=(0,X.useCallback)(e=>{_(e)},[_]),C=(0,X.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,X.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}}function Y_({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=Lm(e,t.id,512,{blobFallback:!K_(t),version:t.checksumArray?.[0]??null}),c=mo(t)||`image-${t.id}`,l=Co(t),u=l!==``&&i!==`off`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-lg border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!K_(t)&&(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,Z.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-200 group-hover:scale-105`}),K_(t)&&(0,Z.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,Z.jsx)(Oe,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,Z.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,Z.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,Z.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,Z.jsx)(v,{className:`h-3 w-3`})})]})}function X_({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Oo(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!K_(a)}),l=mo(a)||`image-${a.id}`,u=Co(a),[d,f]=(0,X.useState)(!1);return Sf(r),(0,X.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,yf.createPortal)((0,Z.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,Z.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,Z.jsx)(G,{className:`h-5 w-5`})}),n>0&&!d&&(0,Z.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,Z.jsx)(se,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,Z.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,Z.jsx)(Ye,{className:`h-6 w-6 touch-target`})}),(0,Z.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,Z.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),K_(a)&&(0,Z.jsx)(Q_,{workspaceId:e,doc:a},a.id),o&&(0,Z.jsx)(Tm,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,Z.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,Z.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&&!K_(a)&&(0,Z.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function Z_({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,Z.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,Z.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}),_&&(0,Z.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,Z.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,Z.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,Z.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,Z.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,Z.jsx)(v,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(n_,{workspaceId:e,value:u,onChange:d}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,Z.jsx)(ud,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,Z.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,Z.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,Z.jsx)(se,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,Z.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,Z.jsx)(Ye,{className:`h-3.5 w-3.5`})})]})]})]})}function Q_({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=go(e,t.id);return(0,Z.jsxs)(Z.Fragment,{children:[r&&(0,Z.jsx)(`span`,{children:`Loading video…`}),i&&(0,Z.jsx)(`span`,{role:`alert`,children:i}),n&&(0,Z.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function $_({config:e,setConfig:t,canvas:n}){let r=J_(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=Eo()==null&&(n.interactive??!n.readOnly),[a,o]=(0,X.useState)(new Set),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.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,X.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Z_,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,Z.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,Z.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,Z.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,Z.jsx)(Y_,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,Z.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,Z.jsx)(Cf,{x:d.x,y:d.y,onClose:()=>f(null),className:`rounded-lg border bg-popover p-1 shadow-elevation-3`,children:(0,Z.jsxs)(`button`,{className:`px-3 py-2 text-sm hover:bg-muted`,onClick:()=>{u(d.ids),f(null)},children:[`Bulk Edit… (`,d.ids.length,`)`]})}),l&&(0,Z.jsx)(jp,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,Z.jsx)(X_,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}pf({type:`gallery`,name:`Gallery`,icon:sn,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:$_});var ev=150;function tv(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function nv(e){let t=e.metadata??{},n=e.data??{};return{w:tv(t.width)||tv(t.imageWidth)||tv(n.width)||tv(n.imageWidth),h:tv(t.height)||tv(t.imageHeight)||tv(n.height)||tv(n.imageHeight)}}function rv(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=nv(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 iv({config:e,setConfig:t,canvas:n}){let r=J_(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,X.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Z_,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,Z.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,Z.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${ev}px, 1fr))`,gridAutoRows:`${ev}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=rv(e,t);return(0,Z.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,Z.jsx)(Y_,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,Z.jsx)(X_,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}pf({type:`mosaic`,name:`Mosaic`,icon:$n,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:iv});var av=`data/schema/task`;function ov({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=hh(e),[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=ea(e),l=i.status===`completed`,u=i.status??`pending`,d=_h(i),{activationProps:f,stopRowActivation:p}=z_(e,t),m=async()=>{if(!(n||a)){o(!0);try{await yh(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,Z.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,Z.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,Z.jsx)(Mt,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,Z.jsx)($e,{className:`h-3 w-3`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${gh[u]}`,children:sh[u]}),i.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(pe,{className:`h-3 w-3`}),vh(i.dueDate)]}),typeof i.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,Z.jsx)(bn,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function sv({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,X.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,X.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[av],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===uo))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,X.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,X.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>hh(e).status!==`completed`):i,v=i.filter(e=>{let t=hh(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,Z.jsx)(ov,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}pf({type:`todos`,name:`Todos`,icon:On,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:sv});function cv(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var lv=`context`;function uv(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:lv,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:lv,path:e?`/${e}`:`/`}}return{treeName:lv,path:`/`}}function dv(e,t,n){let r=n&&n!==lv?`/trees/${encodeURIComponent(n)}`:``,i=cv(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function fv({canvas:e}){return Eo()!=null||!rd()?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,Z.jsx)(pv,{workspaceId:e.workspaceId},e.workspaceId)}function pv({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(`Workspace`),[a,o]=(0,X.useState)(!0),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([wi(e),qa(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),l(null)}catch{if(t||a!==r)return;n([]),l(`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 c=Xu.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),c?.(),window.clearInterval(u)}},[e,u]),(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,Z.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>d(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,Z.jsx)(Te,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,Z.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=Hf(t.color),i=(0,Z.jsxs)(Z.Fragment,{children:[n?(0,Z.jsx)(at,{className:`h-5 w-5 shrink-0 text-warning`}):(0,Z.jsx)(c,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,Z.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,Z.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-lg border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,Z.jsx)(`li`,{children:n?(0,Z.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,Z.jsx)(mu,{to:dv(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,Z.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.`})})]})}pf({type:`workspace-pins`,name:`Workspace pins`,icon:ne,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:fv});function mv({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,X.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,Z.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-lg border bg-background overflow-hidden`,children:[(0,Z.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,Z.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(hv,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:de}),(0,Z.jsx)(hv,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:jn})]}),(0,Z.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,Z.jsx)(it,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(Fn,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,Z.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,Z.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,yf.createPortal)(d,u??document.body):d}function hv({on:e,onClick:t,label:n,icon:r}){return(0,Z.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,Z.jsx)(r,{className:`w-3.5 h-3.5`})})}var gv=(0,df.WidthProvider)(df.default),_v=12,vv=80,yv=40,bv=[12,12],xv=[8,8],Sv={w:!1,h:!1};function Cv(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function wv(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function Tv(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 Ev(e,t,n=0){let r=n>0?n:Cv(e);return e.map(e=>{let n=t[e.i]??Sv;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?_v:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var Dv=4;function Ov(e,t,n=bv[1]){return Math.max(1,Math.ceil((e-n-Dv)/(t+n)))}var kv=45,Av=640;function jv(e,t,n=0,r){let i=[...Ev(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:_v,y:a,h:n};return a+=n,i})}var Mv=e=>e&&e.trim()?[e]:[];function Nv(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(Tv):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=_v,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function Pv({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,X.useMemo)(()=>Nv(a),[a]),[p,m]=(0,X.useState)(f.layout),[h,g]=(0,X.useState)(f.widgets),[_,v]=(0,X.useState)(f.fills),y=(0,X.useRef)(f.fills),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(0),N=(0,X.useRef)(0),P=(0,X.useCallback)(e=>{y.current=e,v(e)},[]),[F,I]=(0,X.useState)(()=>i?.sort??Qg),ee=(0,X.useRef)(!1),[te,ne]=(0,X.useState)(()=>Mv(i?.query)),re=(0,X.useRef)(!1),ie=(0,X.useRef)(null),L=(0,X.useRef)(f),R=(0,X.useCallback)(e=>{let t=mf(h[e]?.type??``)?.mobileHeight;if(!(!t||j<=0))return Math.max(1,Math.round(j*t))},[h,j]),ae=(0,X.useMemo)(()=>O?jv(p,_,j,R):Ev(p,_,j),[p,_,O,j,R]),oe=O?yv:vv,se=(0,X.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,X.useEffect)(()=>{let e=Nv(a);m(e.layout),g(e.widgets),P(e.fills),L.current=e,I(i?.sort??Qg),ee.current=!1,ne(Mv(i?.query)),re.current=!1,C(!1)},[n,r]),(0,X.useEffect)(()=>{if(!s)return;let e=Nv(a);m(e.layout),g(e.widgets),P(e.fills),L.current=e},[s,se,a,P]),(0,X.useEffect)(()=>{let e=ie.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<Av;A(n),N.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?xv:bv;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&M(Ov(t,n?yv:vv,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let ce=(0,X.useCallback)(e=>{I(e),ee.current=!0,C(!0)},[]),z=(0,X.useCallback)(e=>{ne(e),re.current=!0,C(!0)},[]),le=(0,X.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:F,setCanvasSort:d?ce:void 0,canvasQueries:te,setCanvasQueries:d?z:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await Si(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 Si(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,F,ce,te,z]),ue=(0,X.useCallback)((e,t,n)=>{L.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),de=(0,X.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:L.current.widgets,layout:L.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};L.current={...r,fills:y.current};let o=ee.current||re.current?{...i||{},...ee.current?{sort:F.sortBy?F:null}:{},...re.current?{query:te.join(` `).trim()||null}:{}}:void 0;await Di(e,n,t,{...a||{},ui:r},o),ee.current=!1,re.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,F,te]),fe=(0,X.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 ue(n,h),n})},[d,O,ue,h]),pe=(0,X.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??Sv,i=bv[1]+(n.y+n.h)*(vv+bv[1]),a={w:n.x+n.w>=_v,h:N.current>0&&i>=N.current-kv};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};P(o),ue(L.current.layout,h,o)},[d,P,ue,h]),me=(0,X.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??Sv,r={...y.current,[e]:{...n,[t]:!n[t]}};P(r),ue(p,h,r)},[d,P,ue,p,h]),he=(0,X.useCallback)(e=>{let t=mf(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:wv(ae),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>=_v,h:!1}};m(l),g(u),P(d),x(!1),ue(l,u,d)},[p,ae,h,P,ue]),ge=(0,X.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),P(r),ue(t,n,r)},[p,h,P,ue]),_e=(0,X.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return ue(p,r),r})},[p,ue]),ve=Object.keys(h);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Z.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,Z.jsx)(H,{className:`w-3.5 h-3.5`}),`Add`,(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,Z.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:hf().map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>he(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,Z.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:de,disabled:!S||w,className:K(`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,Z.jsx)(k,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[ve.length,` widget`,ve.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,Z.jsx)(`div`,{ref:ie,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:ve.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,Z.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,Z.jsx)(gv,{className:`layout`,layout:ae,cols:_v,rowHeight:oe,margin:O?xv:bv,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:fe,onResizeStop:pe,compactType:`vertical`,children:ve.map(e=>{let t=h[e],n=mf(t.type),r=_[e]??Sv,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,Z.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,Z.jsx)(mv,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>ge(e),fill:_[e]??Sv,onToggleFill:d?t=>me(e,t):void 0,children:(0,Z.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>_e(e,t),canvas:le})}):(0,Z.jsx)(mv,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>ge(e),children:(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var Fv=`data/schema/file`;function Iv(e){return String(e.locations?.[0]?.url||``).trim()}function Lv(e){let t=Iv(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function Rv(e){return e.schema===Fv&&String(e.metadata?.contentType||``).startsWith(`image/`)}function zv(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 Bv(e){if(e.schema!==Fv)return bo(e);let t=Lv(e),n=String(e.metadata?.contentType||``).trim(),r=zv(e.metadata?.size);return{...bo(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:Iv(e),schemaLabel:`file`}}function Vv(e){return/^https?:\/\/[^\s]+$/i.test(e)}function Hv(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return Vv(t)?t:null}return t.isExternal&&Vv(t.subtitle)?t.subtitle:Vv(t.title)?t.title:null}function Uv(e,t,n=!1){return _o(e,t,{download:n})}function Wv(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>Vv(e)?(0,Z.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 Gv(e){return e?new Date(e).toLocaleString():``}function Kv(){let{code:e=``}=tl(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),d=(0,X.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=Bv(t);return[t.schema,n.title,n.preview,n.subtitle,Lv(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,X.useCallback)(async()=>{if(e){i(!0);try{let t=await Y.get(`${ti}/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,X.useEffect)(()=>{p()},[p]),(0,X.useEffect)(()=>{if(!e)return;let t=$a(`${si}/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,X.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,X.useCallback)(()=>{u(``)},[]),g=(0,X.useCallback)(async()=>({payload:d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Z.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Z.jsxs)(Du,{className:`max-w-md bg-card`,children:[(0,Z.jsx)(Ou,{children:(0,Z.jsx)(ku,{children:`Canvas unavailable`})}),(0,Z.jsx)(ju,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Z.jsx)(qu,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,Z.jsx)(Ao.Provider,{value:e,children:(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Z.jsxs)(Du,{className:`bg-card shadow-elevation-3`,children:[(0,Z.jsx)(Ou,{className:`border-b p-3 sm:p-6`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Z.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,Z.jsx)($n,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Z.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,Z.jsx)(S,{className:`h-3 w-3 text-success`}):(0,Z.jsx)(qe,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Z.jsx)(ku,{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,Z.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,Z.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,Z.jsx)(S,{className:`h-3.5 w-3.5 text-success`}):(0,Z.jsx)(qe,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Z.jsxs)(ju,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Z.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,Z.jsxs)(`span`,{className:`truncate`,children:[`· `,Gv(t.stats.refreshedAt)]})]}),(0,Z.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Z.jsx)(qv,{label:`Path`,value:t.share.path,mono:!0}),(0,Z.jsx)(qv,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Z.jsx)(qv,{label:`Shown`,value:String(f.length)}),(0,Z.jsx)(qv,{label:`Refreshed`,value:Gv(t.stats.refreshedAt)})]}),v&&(0,Z.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,Z.jsx)(Pv,{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,Z.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Z.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,Z.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.jsx)(G,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Z.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,Z.jsx)(Te,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,Z.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,Z.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,Z.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=Bv(t),r=Hv(t,n),i=t.schema===Fv,a=i?Uv(e,t.id):null,o=a||r;return(0,Z.jsxs)(`article`,{className:`p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Z.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Z.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Z.jsxs)(`a`,{href:Uv(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,Z.jsx)(er,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Z.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:Gv(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Z.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:Wv(n.preview)}),Rv(t)&&(0,Z.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Z.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,Z.jsx)(qu,{className:`mt-6 text-center`})]})})})}function qv({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var Jv=(0,X.createContext)(void 0);function Yv(){let e=(0,X.useContext)(Jv),t=Io()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,X.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 Xv({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,X.useRef)(null),o=(0,X.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,X.useEffect)(()=>{o()},[e,o]),(0,Z.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 Zv({onLinkTo:e,onDelete:t}){return(0,Z.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,Z.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,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function Qv({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=to(),[a,o]=(0,X.useState)(!1);return(0,Z.jsx)(pp,{onClose:n,children:(0,Z.jsx)(dp,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await $r(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:fp,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 Xi(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Qp(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var $v=1200;function ey(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 ty(e,t){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=(0,X.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([is(n,[t]),as(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 Ki(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,X.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,X.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,X.useEffect)(()=>{u()},[u]),(0,X.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,X.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await Ha(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}var ny=`2.0`;function ry({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let[s,c]=(0,X.useState)(String(e.data?.title??``)),[l,u]=(0,X.useState)(String(e.data?.content??``)),[d,f]=(0,X.useState)(`idle`),p=(0,X.useRef)({title:String(e.data?.title??``),content:String(e.data?.content??``)}),m=(0,X.useRef)(null),h=(0,X.useRef)(0),g=(0,X.useCallback)(async(n,r)=>{if(!t||n===p.current.title&&r===p.current.content||!r.trim())return;let i=++h.current;f(`saving`);try{if(await Ui(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data||{},...n.trim()?{title:n.trim()}:{title:void 0},content:r},metadata:e.metadata}),i!==h.current)return;p.current={title:n,content:r},f(`saved`),setTimeout(()=>f(e=>e===`saved`?`idle`:e),1500)}catch{i===h.current&&f(`error`)}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),_=(0,X.useCallback)((e,t)=>{f(`dirty`),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(e,t),$v)},[g]),v=(0,X.useCallback)(()=>{m.current&&=(clearTimeout(m.current),null),g(s,l)},[g,s,l]);return(0,X.useEffect)(()=>()=>{m.current&&clearTimeout(m.current)},[]),(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[ey(e.createdAt),` · #`,e.id]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[d===`saving`&&(0,Z.jsx)(Mt,{className:`inline h-3 w-3 animate-spin`}),d===`saved`&&(0,Z.jsx)($e,{className:`inline h-3 w-3 text-success`}),d===`dirty`&&`·`,d===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Zv,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsx)(`input`,{value:s,onChange:e=>{c(e.target.value),_(e.target.value,l)},onBlur:v,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,Z.jsx)(Xv,{value:l,onChange:e=>{u(e),_(s,e)},onBlur:v,innerRef:t=>r(e.id,t)})]})}function iy({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:r,onChange:e=>i(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,Z.jsx)(Xv,{value:a,onChange:o,placeholder:`Write your note…`}),l&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!a.trim()||!e||s)){c(!0),u(null);try{await ts(e,[{schema:no,schemaVersion:ny,data:{...r.trim()?{title:r.trim()}:{},content:a},metadata:{features:[]}}]),t()}catch(e){u(e instanceof Error?e.message:`Failed to create note`),c(!1)}}},disabled:!a.trim()||s,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:s?`Saving…`:`Save note`})})]})}function ay({autoAdd:e=!1}){let t=Yv(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=ty(t,no),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(`desc`),[m,h]=(0,X.useState)(e),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(new Map),y=(0,X.useRef)(new Map),b=(0,X.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,X.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,X.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,X.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,X.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,X.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,X.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,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.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,Z.jsx)(hn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(H,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,Z.jsx)(iy,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)}),r&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,Z.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,Z.jsx)(ry,{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,Z.jsx)(Qv,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:ps(t)})}var oy=`2.1`,sy=new Set([`completed`,`cancelled`]);function cy({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,X.useState)(String(e.data?.title??``)),[u,d]=(0,X.useState)(String(e.data?.description??``)),[f,p]=(0,X.useState)(e.data?.status||`pending`),[m,h]=(0,X.useState)(uh(e.data?.dueDate)),[g,_]=(0,X.useState)(`idle`),{replicating:v,label:y}=ea(e),b=(0,X.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),x=(0,X.useRef)(null),S=(0,X.useRef)(0),C=(0,X.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++S.current;_(`saving`);try{let i=dh(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 Ui(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]),w=(0,X.useCallback)((e,t)=>{(e!==b.current.title||t!==b.current.description)&&(_(`dirty`),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>C({title:e,description:t,status:f,due:m}),$v))},[C,f,m]),T=(0,X.useCallback)(()=>{x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:m})},[C,c,u,f,m]);(0,X.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]);let E=(0,X.useCallback)(async()=>{let t=f,n=f===`completed`?`pending`:`completed`;p(n),await C({title:c,description:u,status:n,due:m})?s(e.id,n):p(t)},[f,C,c,u,m,e.id,s]),D=(0,X.useCallback)(e=>{h(e),x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:e})},[C,c,u,f]),O=sy.has(f);return(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0`,children:[ey(e.createdAt),` · #`,e.id,f!==`pending`&&(0,Z.jsxs)(`span`,{children:[` · `,sh[f]??f]})]}),(0,Z.jsx)(Yh,{value:m,onChange:D,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,Z.jsx)(Mt,{className:`inline h-3 w-3 animate-spin`}),v&&(0,Z.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,Z.jsx)($e,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Zv,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:E,className:`mt-0.5 shrink-0 text-muted-foreground transition-colors hover:text-foreground`,"aria-label":O?`Mark as pending`:`Mark as completed`,title:O?`Mark as pending`:`Mark as completed`,children:O?(0,Z.jsx)(te,{className:`h-4 w-4 text-success`}):(0,Z.jsx)(an,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),w(e.target.value,u)},onBlur:T,placeholder:`Untitled`,spellCheck:!1,className:K(`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold outline-none placeholder:text-muted-foreground/50`,O?`text-muted-foreground line-through`:`text-foreground`)}),(0,Z.jsx)(Xv,{value:u,onChange:e=>{d(e),w(c,e)},onBlur:T,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function ly({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(fh()),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]}),(0,Z.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,Z.jsx)(Xv,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(Yh,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await ts(e,[{schema:uo,schemaVersion:oy,data:ph({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 uy({autoAdd:e=!1}){let t=Yv(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=ty(t,uo),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(0),[p,m]=(0,X.useState)(`desc`),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(e),[y,b]=(0,X.useState)(null),x=(0,X.useRef)(new Map),S=(0,X.useRef)(new Map),C=(0,X.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,X.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,X.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,X.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,X.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!sy.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,X.useMemo)(()=>n.filter(e=>sy.has(String(e.data?.status??`pending`))).length,[n]),k=(0,X.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,X.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,X.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,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:K(`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,Z.jsx)(Vt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(kn,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(hn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(H,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,Z.jsx)(ly,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,Z.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,Z.jsx)(cy,{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,Z.jsx)(Qv,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:ps(t)})}var dy=(0,X.createContext)(null);function fy(){let e=(0,X.useContext)(dy);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function py(e=!0){let{registerViewer:t}=fy();(0,X.useEffect)(()=>{if(e)return t()},[e,t])}var my=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],hy=`canvas.lens.camera`,gy={min:1,max:4,step:.1,hardware:!1};function _y(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(hy)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:my.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function vy(e,t){let n=my.find(t=>t.id===e.resolution)??my[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function yy(e={}){let t=(0,X.useRef)(null),n=(0,X.useRef)(e.onEnded);(0,X.useEffect)(()=>{n.current=e.onEnded});let r=(0,X.useRef)(null),i=(0,X.useRef)(null),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(_y),p=(0,X.useRef)(d),[m,h]=(0,X.useState)([]),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(1),w=(0,X.useRef)(1),[T,E]=(0,X.useState)(!1),D=(0,X.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,X.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,X.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,X.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,X.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,X.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:vy(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:vy(e,!1),audio:!1});throw t}},[]),P=(0,X.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]),F=(0,X.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]),I=(0,X.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(hy,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]),ee=(0,X.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),te=(0,X.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),ne=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),re=(0,X.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]),ie=(0,X.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,X.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:P,startScreen:F,stop:j,captureFrame:ie,camera:(0,X.useMemo)(()=>g?{devices:m,prefs:d,setPrefs:I,size:b,zoomRange:v?.zoom?{min:v.zoom.min,max:v.zoom.max,step:v.zoom.step||.1,hardware:!0}:gy,zoom:S,setZoom:ee,torchSupported:!!v?.torch,torch:T,setTorch:te,focusSupported:ne,focusAt:re}:null,[g,m,d,I,b,v,S,ee,T,te,ne,re])}}async function by(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(`${Qr.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 xy=[{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}],Sy=1e3,Cy={sortBy:`crud:created`,order:`desc`},wy={features:{allOf:[],anyOf:[],noneOf:[]},timeline:{quickFilter:null,customRanges:[],indexCreated:!0,indexUpdated:!0,indexDeleted:!1,contentEvents:!1,selectedTimelines:[]},geo:{bbox:null,includeUnlocated:!1},lens:{gps:null,ids:null},sort:{...Cy}};function Ty(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function Ey(e,t=!1){if(!e.gps)return[];let{lat:n,lon:r,radiusM:i}=e.gps;return[`geo:near:${n},${r},${Math.max(1,Math.round(i))}m`,...t?[`geo:missing`]:[]]}function Dy(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function Oy(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Dy(e),c=s.length>0?s.map(e=>`${e.start}..${e.end}`):t?[t]:[];if(c.length===0)return[];let l=[];return n&&l.push(`crud:created`),r&&l.push(`crud:updated`),i&&l.push(`crud:deleted`),a&&l.push(`content`),l.push(...o),l.flatMap(e=>c.map(t=>`t:${e}:${t}`))}function ky(e,t,n=[]){return{features:e.features,filters:[...Oy(e.timeline),...Ty(e.geo),...Ey(e.lens,e.geo.includeUnlocated)],queryOptions:{ids:e.lens.ids,sortBy:e.sort.sortBy,order:e.sort.order,queries:n,geoSelection:t,includeUnlocated:e.geo.includeUnlocated??!1}}}var Ay=32,jy=12,My=`canvas.lens.fit`;function Ny({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=fy(),a=(0,X.useRef)(null),[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,X.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.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:K(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,Z.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 Py({children:e}){let t=Io(),n=(0,X.useRef)(t);(0,X.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,X.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=yy({onEnded:()=>a.current()}),[m,h]=(0,X.useState)(null),g=(0,X.useRef)(m);(0,X.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(Sy),[C,w]=(0,X.useState)(``),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)([]),[F,I]=(0,X.useState)(null),[ee,te]=(0,X.useState)(null),ne=ee&&ee.frame===F?ee:null,re=(0,X.useRef)(null),[ie,L]=(0,X.useState)(0),[R,ae]=(0,X.useState)(``),[oe,se]=(0,X.useState)(()=>{try{return localStorage.getItem(My)===`cover`?`cover`:`contain`}catch{return`contain`}}),ce=(0,X.useCallback)(e=>{se(e);try{localStorage.setItem(My,e)}catch{}},[]),z=(0,X.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:Sy,snapshot:!1}),le=(0,X.useRef)([]),ue=(0,X.useRef)(new Map),de=(0,X.useRef)(null),fe=(0,X.useRef)(null),pe=(0,X.useRef)(null),me=(0,X.useRef)(0),he=(0,X.useRef)(``),ge=(0,X.useRef)(!1),_e=(0,X.useRef)(async()=>{}),ve=(0,X.useRef)(()=>{});(0,X.useEffect)(()=>{z.current.text=T,z.current.maxDistance=C===``?NaN:Number(C),z.current.rateMs=x,z.current.paused=y},[T,C,x,y]);let ye=(0,X.useCallback)(()=>(L(e=>e+1),()=>L(e=>Math.max(0,e-1))),[]),B=(0,X.useCallback)(e=>{le.current=[...le.current.slice(-2),e];let t=le.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=de.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(de.current=i,n.current?.setLensIds(i))},[]),be=(0,X.useCallback)((e,t)=>{for(let n of e)ue.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);le.current=[...le.current.slice(-2),n];let r=le.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...ue.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>ue.current.get(e)).filter(e=>!!e);M(s.length),P(s)},[]),V=(0,X.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;pe.current?.abort();let a=new AbortController;pe.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await by(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?[...Oy(o.filters.timeline),...Ty(o.filters.geo),...Ey(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?jy:Ay,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||z.current!==t||!t.running?!1:(me.current=0,A(Math.round(performance.now()-r)),O(null),i?be(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):B(c.ids),!0)}catch(e){return a.signal.aborted||z.current!==t||!t.running?!1:(me.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[be,B]),xe=(0,X.useCallback)(async()=>{let e=z.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await V(t,e)}if(z.current.running){let e=Math.max(me.current?Math.min(3e4,1e3*2**Math.min(me.current-1,5)):0,z.current.rateMs-(performance.now()-t));fe.current=window.setTimeout(()=>void _e.current(),e)}},[p,V]);(0,X.useEffect)(()=>{_e.current=xe},[xe]);let H=(0,X.useCallback)(()=>{let e=z.current.consumer===`filter`;z.current.running=!1,me.current=0,z.current.consumer=null,fe.current&&window.clearTimeout(fe.current),pe.current?.abort(),f(),le.current=[],ue.current.clear(),de.current=null,h(null),v(null),b(!1),ae(``),P([]),I(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,X.useEffect)(()=>{a.current=H},[H]);let Se=(0,X.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||ge.current||(z.current.running&&H(),e===`photo`&&!r.image))return!1;ge.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return ge.current=!1,i?(le.current=[],ue.current.clear(),de.current=null,P([]),M(null),O(null),ae(r.workspaceRef),z.current={...z.current,running:!0,paused:!1,consumer:t,workspaceRef:r.workspaceRef,contextPath:r.contextPath??null,snapshot:e===`photo`},I(e===`photo`?r.image:null),h(e),v(t),b(!1),t===`filter`&&n.current?.setLensIds([]),e===`photo`?ve.current(r.image):xe(),!0):!1},[u,d,H,xe]),Ce=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,X.useEffect)(()=>{he.current!==Ce&&(he.current=Ce,z.current.consumer===`filter`&&(pe.current?.abort(),le.current=[],de.current=null,n.current?.setLensIds([])))},[Ce]);let U=(0,X.useCallback)(e=>{z.current.contextPath=e},[]),W=(0,X.useCallback)(e=>{z.current.paused=e,b(e)},[]),we=JSON.stringify([T,C,Ce]),Te=(0,X.useRef)(we);(0,X.useEffect)(()=>{Te.current=we});let Ee=(0,X.useCallback)(e=>{let t=z.current;!t.running||!t.workspaceRef||(re.current={frame:e,key:Te.current},le.current=[],ue.current.clear(),de.current=null,M(null),V(e,t))},[V]);(0,X.useEffect)(()=>{ve.current=Ee},[Ee]);let De=(0,X.useCallback)(()=>{let e=z.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,I(t),Ee(t))},[p,Ee]),Oe=(0,X.useCallback)(()=>{if(z.current.running&&g.current===`photo`){H();return}z.current.snapshot=!1,pe.current?.abort(),le.current=[],ue.current.clear(),I(null)},[H]),ke=(0,X.useCallback)(async(e,t,n)=>{let r=z.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,I(e),Ee(e),!0):Se(`photo`,t,{...n,image:e})},[Se,Ee]);(0,X.useEffect)(()=>{if(!F)return;let e=!0,t=new Image;return t.onload=()=>{e&&te({frame:F,width:t.naturalWidth,height:t.naturalHeight})},t.src=F,()=>{e=!1}},[F]),(0,X.useEffect)(()=>{if(!F)return;let e=re.current;if(e&&e.frame===F&&e.key===we)return;let t=window.setTimeout(()=>Ee(F),350);return()=>window.clearTimeout(t)},[F,we,Ee]),(0,X.useEffect)(()=>{!i||!z.current.running||r&&r===z.current.workspaceRef||H()},[i,r,H]);let Ae=(0,X.useCallback)(()=>{let e=n.current;if(e){if(z.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,X.useEffect)(()=>H,[H]);let je=(0,X.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:oe,setFit:ce,workspaceRef:R,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:Se,setContextPath:U,stop:H,setPaused:W,snapshot:F,takeSnapshot:De,clearSnapshot:Oe,snapshotSize:ne,searchPhoto:ke,reopen:Ae,hasViewer:ie>0,registerViewer:ye}),[m,y,_,s,c,oe,ce,R,x,C,T,l,D,k,j,N,Se,U,H,W,F,De,Oe,ne,ke,Ae,ie,ye]);return(0,Z.jsxs)(dy.Provider,{value:je,children:[e,(0,Z.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 Fy=`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`,Iy=`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`,Ly=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function Ry({className:e}){let{camera:t,fit:n,setFit:r}=fy();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,Z.jsxs)(`div`,{className:K(`flex flex-col gap-2`,e),children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,Z.jsxs)(`select`,{className:K(Fy,`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,Z.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,Z.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,Z.jsx)(`select`,{className:Fy,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:my.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:Iy,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,Z.jsx)(Zt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(pn,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:Iy,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,Z.jsx)(cr,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:K(Iy,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,Z.jsx)(Lt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,Z.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,Z.jsx)(z,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:Ly(l)})]})]})}function zy(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=fy();return e?n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:K(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,Z.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,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(G,{className:`h-3.5 w-3.5`}),` Close`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(He,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,Z.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,Z.jsx)(Wt,{className:`h-5 w-5`})}):null}async function By(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 Vy({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=fy(),o=(0,X.useRef)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await By(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(rn,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,Z.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,Z.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var Hy=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,Uy=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Wy({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=jo(t),{blobUrl:a}=Lm(e,t.id,256,{enabled:i}),o=bo(t);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-lg 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,Z.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,Z.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,Z.jsx)(ep,{document:t,size:10})}),(0,Z.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,Z.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function Gy(){let e=Yv(),t=Sg(),n=fy(),{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:[];py(p);let _=p?n.snapshotSize??n.camera?.size:null,v=!!_&&_.height>_.width,y=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:b}=n;return(0,X.useEffect)(()=>{p&&b(f)},[p,f,b]),e?.mode===`workspace`?(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:Hy,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:xy.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(Uy,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,Z.jsx)(`input`,{className:K(Uy,`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,Z.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,Z.jsx)(Ce,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y(`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,Z.jsx)(L,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y(`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,Z.jsx)(me,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(Vy,{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,Z.jsxs)(`div`,{className:K(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,v?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[p&&(0,Z.jsx)(Ny,{className:`h-full w-full`,interactive:!0}),p&&(0,Z.jsx)(zy,{}),!p&&(0,Z.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,Z.jsx)(g,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),p&&(0,Z.jsx)(Ry,{className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,Z.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,Z.jsxs)(Z.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,Z.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,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,Z.jsx)(Wy,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,Z.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.`})}function Ky({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=Lm(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-lg border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,Z.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,Z.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,Z.jsx)(rt,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,Z.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,Z.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:ey(e.updatedAt||e.createdAt)})]})]}),(0,Z.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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function qy({autoAdd:e}){let t=Yv(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=ty(t,lo),[c,l]=(0,X.useState)(e?`new`:null),{showErrorToast:u}=to();return t?(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,Z.jsx)(H,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,Z.jsx)(Ky,{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,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(Og,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var Jy=[{id:`notes`,label:`Notes`,icon:xn,modes:[`context`],description:`All notes in the current context, editable in place`,Component:ay},{id:`todo`,label:`Todos`,icon:On,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:uy},{id:`sketch`,label:`Sketch`,icon:rt,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:qy},{id:`lens`,label:`Lens`,icon:ze,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:Gy}];function Yy(e){return Jy.filter(t=>t.modes.includes(e))}function Xy({target:e,children:t}){return(0,Z.jsx)(Jv.Provider,{value:e,children:t})}function Zy({children:e}){let[t,n]=(0,X.useState)(null),r=(0,X.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,X.useCallback)(()=>n(null),[]),a=(0,X.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,Z.jsxs)(bg.Provider,{value:a,children:[e,(0,Z.jsx)(Xg,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var Qy=`universe`;function $y(){let{appletId:e}=tl(),[t,n]=bu(),r=Jy.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||Qy,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,X.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,X.useState)([]),[f,p]=(0,X.useState)([]);(0,X.useEffect)(()=>{Pr().then(d).catch(()=>d([])),Yo().then(p).catch(()=>p([]))},[]);let[m,h]=(0,X.useState)(o),[g,_]=(0,X.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,Z.jsxs)(`div`,{className:`flex h-viewport flex-col items-center justify-center gap-3 surface-desk`,children:[(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:Jy.map(e=>(0,Z.jsx)(mu,{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,Z.jsx)(Zy,{children:(0,Z.jsx)(Py,{children:(0,Z.jsxs)(`div`,{className:`flex h-viewport flex-col surface-desk p-shell gap-shell`,children:[(0,Z.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,Z.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,Z.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:K(`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,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,Z.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,Z.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,Z.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,Z.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,Z.jsx)(`div`,{className:`grow`}),(0,Z.jsx)(mu,{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,Z.jsx)(Se,{className:`h-3.5 w-3.5`})})]}),(0,Z.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,Z.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,Z.jsx)(Xy,{target:l,children:(0,Z.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})})})}var eb=`false`,tb=`false`,nb=eb===`true`,rb=tb===`true`;function ib(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,nb||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await m(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()},!rb){if(nb)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 ab=new Set,ob=!1,sb=ib({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){ob=!0,ab.forEach(e=>e())}});function cb(e){return ab.add(e),ob&&e(),()=>{ab.delete(e)}}function lb(){sb(!0)}function ub(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>cb(()=>t(!0)),[]),!e||n?null:(0,Z.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>lb(),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,Z.jsx)(Te,{className:`h-3 w-3`}),` Reload`]}),(0,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})})}function db(e){return e.isShared||e.type===`shared`?e.id:e.name}function fb({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=Zc();return(0,Z.jsxs)(`div`,{className:K(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,Z.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,Z.jsx)(Bt,{className:`h-5 w-5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h1`,{className:K(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,Z.jsx)(`p`,{className:K(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,Z.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,Z.jsx)(G,{className:`h-4 w-4`})}),n&&(0,Z.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 pb({className:e}){let t=Zc();return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:K(`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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})}function mb({onBack:e,title:t=`Back`,className:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:K(`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,Z.jsx)(Bt,{className:`h-4 w-4`})})}var hb=180;function gb({x:e,y:t,current:n,onChange:r,onClose:i}){Sf(i);let[a,o]=(0,X.useState)(``),[s,l]=(0,X.useState)([]),[u,d]=(0,X.useState)({q:``,list:[]}),[f,p]=(0,X.useState)(!0),m=(0,X.useRef)(null),h=(0,X.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,X.useEffect)(()=>{m.current?.focus()},[]),(0,X.useEffect)(()=>{let e=!0;return Tf().then(t=>{e&&(l(t),p(!1))}),()=>{e=!1}},[]),(0,X.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{Ef(e).then(t=>{d({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=u.q===_,y=_!==``&&!v,b=(0,X.useMemo)(()=>(_?v?u.list:[]:s).slice(0,hb),[_,v,u.list,s]),x=(0,X.useRef)(null),[S,C]=(0,X.useState)({x:e,y:t});return(0,X.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,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,Z.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[Df.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:K(`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,Z.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:K(`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,Z.jsx)(G,{className:`w-3 h-3`})}),(0,Z.jsx)(`label`,{title:`Custom color`,className:K(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!Df.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!Df.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,Z.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,Z.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`}),f||y?(0,Z.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,Z.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:K(`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,Z.jsx)(G,{className:`w-4 h-4`})}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(c,{icon:e,width:18,height:18,color:n.color})},e))]}),!f&&!y&&b.length===0&&(0,Z.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function _b(e,t,n){let r=(0,X.useRef)(n);(0,X.useEffect)(()=>{r.current=n}),(0,X.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 vb({title:e,onClose:t,children:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-lg border bg-card p-4 shadow-elevation-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,Z.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,Z.jsx)(G,{className:`h-4 w-4`})})]}),n]})}function yb({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,X.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=Hf(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsxs)(Du,{className:`relative ${S}`,style:C,children:[(0,Z.jsx)(Ou,{children:(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(ku,{className:`truncate`,children:e.label||e.name}),(0,Z.jsx)(Au,{children:p?`Shared from ${m}`:e.description||``})]}),(0,Z.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>n(db(e)),title:`Stop Workspace`,disabled:d||f,children:(0,Z.jsx)(nn,{className:`h-4 w-4`})}):(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>t(db(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,Z.jsx)(Oe,{className:`h-4 w-4`})}),l&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>r(db(e)),title:`Enter Workspace`,disabled:d||f,children:(0,Z.jsx)(fr,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:`Workspace settings`,"aria-label":`Workspace settings`,disabled:f,children:(0,Z.jsx)(Qt,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,Z.jsx)(xt,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,Z.jsxs)(Zi,{open:s,onOpenChange:c,children:[(0,Z.jsx)(Ua,{asChild:!0,children:(0,Z.jsx)(J,{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,Z.jsx)(lt,{className:`h-4 w-4`})})}),(0,Z.jsxs)(Ya,{children:[(0,Z.jsxs)(mi,{children:[(0,Z.jsx)(Ar,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,Z.jsx)(Li,{children:y?(0,Z.jsxs)(Z.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,Z.jsx)(`br`,{}),(0,Z.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,Z.jsxs)(Z.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,Z.jsxs)(Ka,{children:[(0,Z.jsx)(Ba,{children:`Cancel`}),(0,Z.jsx)(ji,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,Z.jsx)(ju,{children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.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,Z.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,Z.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,Z.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,Z.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 bb(){let[e,t]=bu(),n=e.get(`create`)===`1`,[r,i]=(0,X.useState)(n),[a,o]=(0,X.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,X.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var xb=`canvas:lastPath`,Sb=200;function Cb(){try{let e=localStorage.getItem(xb);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function wb(e){try{localStorage.setItem(xb,JSON.stringify(e))}catch{}}function Tb(e,t,n){if(!e)return;let r=Cb(),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>Sb)for(let e of a.slice(0,a.length-Sb))delete r[e];wb(r)}function Eb(e){let t=Cb()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function Db(e){let t=Eb(e);return t?dv(e,t.path,t.tree):`/workspaces/${e}`}var Ob=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:Ke,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:Le,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:C,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:D,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:me,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:Vn,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:_n,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:Ue,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:Xn,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/auth`,icon:rr,label:`Authentication`,description:`Configure sign-in backends: local passwords, LDAP and IMAP.`},{path:`/admin/embedding`,icon:Vn,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:Tt,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:Ct,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:Ae,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:dt,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:A,label:`About Canvas`,description:`View versions and information about this installation.`}]}],kb=[`/settings`,...Ob.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function Ab(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var jb=[{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.`}],Mb=`canvas:layout`;function Nb(){try{return localStorage.getItem(Mb)===`strip`?`strip`:`classic`}catch{return`classic`}}var Pb=Nb(),Fb=new Set;function Ib(){for(let e of Fb)e()}function Lb(){return Pb}function Rb(e){try{e===`strip`?localStorage.setItem(Mb,e):localStorage.removeItem(Mb)}catch{}Pb=e,Ib()}function zb(e){Fb.add(e);let t=t=>{(t.key===Mb||t.key===null)&&(Pb=Nb(),e())};return window.addEventListener(`storage`,t),()=>{Fb.delete(e),window.removeEventListener(`storage`,t)}}function Bb(){return(0,X.useSyncExternalStore)(zb,Lb,()=>`classic`)}var Vb=[{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.`}],Hb=`canvas:layout-nav`;function Ub(){try{let e=localStorage.getItem(Hb);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var Wb=Ub(),Gb=new Set;function Kb(){return Wb}function qb(e){try{e===`shift`?localStorage.removeItem(Hb):localStorage.setItem(Hb,e)}catch{}Wb=e;for(let e of Gb)e()}function Jb(e){Gb.add(e);let t=t=>{(t.key===Hb||t.key===null)&&(Wb=Ub(),e())};return window.addEventListener(`storage`,t),()=>{Gb.delete(e),window.removeEventListener(`storage`,t)}}function Yb(){return(0,X.useSyncExternalStore)(Jb,Kb,()=>`shift`)}function Xb(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}}var Zb=(0,X.createContext)(null);function Qb(){let e=(0,X.useContext)(Zb);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function $b(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`||kb.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function ex(e,t){let n=Jc(),r=Zc(),i=(0,X.useRef)(!1),a=(0,X.useRef)(e);return(0,X.useEffect)(()=>{a.current=e},[e]),(0,X.useEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=$b(n.pathname);if(e===null&&n.pathname!==`/`&&Lb()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=window.matchMedia(`(max-width: 767px)`).matches&&Lb()!==`strip`;t({type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,t]),{navigateToEntity:(0,X.useCallback)(e=>{i.current=!0,r(e)},[r])}}function tx(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=$a(Qr.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 nx=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function rx(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await Vi(e,`/${n}`,!0,a);let t=Pf(`/${n}`);t&&await Ca(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return fa(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function ix(){let[e,t]=(0,X.useState)(new Set),[n,r]=(0,X.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 ax({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,Z.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:nx.map(n=>{let r=Of[n.toLowerCase()];return(0,Z.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,Z.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,Z.jsx)(c,{icon:r.icon,width:16,height:16,color:r.color}),(0,Z.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var ox=[{value:`full`,icon:Mn,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:hr,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 sx({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,Z.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:ox.map(i=>{let a=e===i.value,o=i.icon;return(0,Z.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,Z.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,Z.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,Z.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function cx(){let[e,t]=(0,X.useState)(`full`),[n,r]=(0,X.useState)(!1);return(0,X.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 lx(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 ux(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function dx(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 fx(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.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 px(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(zf()),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(``),[_,v]=cx(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=bb(),D=ix(),[O,k]=(0,X.useState)(!1),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(!1),[P,F]=(0,X.useState)(null),{showToast:I}=po(),ee=Zc(),te=km(),{openM2Drawer:ne}=Qb(),re=tx();_b(re,`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))}),(0,X.useEffect)(()=>{(async()=>{try{r(!0);let e=await Pr();t(lx(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),I({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}})()},[re,I]);let ie=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await za({name:o,description:l||void 0,color:d,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),D.selected.size>0){try{await ui(e.name);let{ok:t,failed:n}=await rx(e.name,Array.from(D.selected),D.tree);n&&I({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),I({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}D.setSelected(new Set)}s(``),u(``),f(zf()),m(null),g(``),I({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),E(!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`}I({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},L=async e=>{if(e.preventDefault(),P)try{let e={label:P.label,description:P.description,color:P.color,icon:P.icon??null};await La(P.name,e),t(t=>t.map(t=>t.id===P.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),I({title:`Success`,description:`Workspace '${P.label}' details updated.`}),F(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;I({title:`Error`,description:t,variant:`destructive`})}},R=e=>{F(e)},ae=async e=>{try{await Qa(e.name),t(t=>t.filter(t=>t.id!==e.id)),I({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;I({title:`Error`,description:t,variant:`destructive`})}},oe=async e=>{try{let n=await ui(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),I({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`}I({title:`Error`,description:t,variant:`destructive`})}},se=async e=>{try{let n=await Cr(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),I({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`}I({title:`Error`,description:t,variant:`destructive`})}},ce=e=>{ee(Db(e))},{rowProps:z,handleProps:le,draggingIndex:ue,insertLineClass:de}=fx((n,r)=>{let i=ux(e,n,r);t(i),dx(i,(e,t)=>La(db(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&I({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(fb,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{variant:`outline`,onClick:()=>k(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>j(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>N(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!T&&(0,Z.jsxs)(J,{onClick:()=>E(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,Z.jsx)(H,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),T&&(0,Z.jsx)(vb,{title:`Create New Workspace`,onClose:()=>E(!1),children:(0,Z.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,Z.jsx)(q,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.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,Z.jsx)(c,{icon:p||`ph:stack-fill`,width:22,height:22,color:Hf(d)})}),(0,Z.jsx)(q,{id:`workspace-color`,type:`color`,value:d,onChange:e=>f(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>f(zf()),disabled:C,children:`Randomize`})]}),y&&(0,Z.jsx)(gb,{x:y.x,y:y.y,current:{icon:p??void 0,color:d},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&f(e.color)},onClose:()=>b(null)}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,Z.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,Z.jsx)(sx,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.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,Z.jsx)(ax,{selected:D.selected,onToggle:D.toggle,tree:D.tree,onTreeChange:D.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,Z.jsxs)(J,{type:`submit`,disabled:C||!o.trim(),children:[(0,Z.jsx)(H,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),O&&(0,Z.jsx)(hx,{}),M&&(0,Z.jsx)(gx,{onClose:()=>N(!1),onChanged:async()=>{try{t(lx(await Pr()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),A&&(0,Z.jsx)(mx,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),j(!1)},onClose:()=>j(!1)}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,Z.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=Hf(t.color);return(0,Z.jsxs)(`div`,{...z(n),className:`flex items-stretch rounded-lg ${de(n,e.length)||``} ${ue===n?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,...le(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,Z.jsx)(Je,{className:`h-4 w-4 ${Uf(i)}`})}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(yb,{workspace:r,onStart:oe,onStop:se,onEnter:ce,onEdit:R,onSettings:e=>{te?ne(`workspaces`,`settings`,db(e)):ee(`/workspaces/${db(e)}/settings/general`)},onDestroy:ae})})]},t.id)})})]}),P&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,P.label]}),(0,Z.jsxs)(`form`,{onSubmit:L,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-label`,value:P.label,onChange:e=>F(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`edit-description`,value:P.description||``,onChange:e=>F(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.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,Z.jsx)(c,{icon:P.icon||`ph:stack-fill`,width:22,height:22,color:Hf(P.color)})}),(0,Z.jsx)(q,{id:`edit-workspace-color`,type:`color`,value:P.color||`#FFFFFF`,onChange:e=>F(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>F(e=>e?{...e,color:zf()}:null),children:`Randomize Color`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:!P.label?.trim(),children:`Save Changes`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>F(null),children:`Cancel`})]})]}),x&&(0,Z.jsx)(gb,{x:x.x,y:x.y,current:{icon:P.icon??void 0,color:P.color??void 0},onChange:e=>{F(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 mx({onImported:e,onClose:t}){let{showToast:n}=po(),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``);return(0,Z.jsx)(vb,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,Z.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}c(!0),u(`Starting…`);try{let t=await Ma(i,a.trim(),e=>{u(ga[e.phase]||e.phase)});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{c(!1),u(``)}},className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:s}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:s}),(0,Z.jsx)(J,{type:`submit`,disabled:s||!r.trim()||!a.trim(),children:s?`Importing…`:`Import Workspace`})]}),s&&l&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:l}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,Z.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 hx(){let{showToast:e}=po(),[t,n]=(0,X.useState)(``),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,Z.jsx)(q,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,Z.jsx)(J,{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,Z.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 gx({onClose:e,onChanged:t}){let{showToast:n}=po(),r=Zc(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)([]),f=(0,X.useCallback)(async()=>{try{d(await ha())}catch{d([])}},[]);(0,X.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 ya(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 fi(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,Z.jsxs)(vb,{title:`Open a remote Workspace`,onClose:e,children:[(0,Z.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,Z.jsx)(J,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,Z.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,Z.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,Z.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,Z.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}function _x({workspaceName:e,children:t}){let n=e,[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a,s=async()=>{let s=++r;try{let c=await wi(e);!t&&s===r&&(a=c.id,i({identity:n,active:c.status===`active`}),o(``))}catch(e){!t&&s===r&&(i({identity:n,active:!1}),o(e instanceof Error?e.message:`Unable to check workspace status`))}},c=t=>{let o=t.detail?.refs;!o?.includes(e)&&!(a&&o?.includes(a))||(r++,i({identity:n,active:!1}))};s(),window.addEventListener(`workspaces:refresh`,s),window.addEventListener(`workspace:stopped`,c),window.addEventListener(`focus`,s);let l=window.setInterval(s,5e3);return()=>{t=!0,window.clearInterval(l),window.removeEventListener(`workspaces:refresh`,s),window.removeEventListener(`workspace:stopped`,c),window.removeEventListener(`focus`,s)}},[e,n,l]),r?.identity===n?r.active?t:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:`Workspace stopped`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to view its content.`}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(J,{disabled:s,onClick:async()=>{c(!0),o(``);try{await ui(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?`Starting…`:`Start workspace`}),(0,Z.jsx)(mu,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]}):(0,Z.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`})}function vx({workspaceId:e,workspaceName:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,X.useEffect)(()=>{let t=!1,n=!1,i=!1,a=async()=>{if(n){i=!0;return}n=!0;try{let n=await wa(e);t||r(n.filter(e=>e.resyncing))}catch{}finally{n=!1,i&&!t&&(i=!1,a())}},o=t=>{t.workspaceId===e&&a()};a();let s=setInterval(()=>{a()},3e3);return Xu.on(`backend.resync.changed`,o),()=>{t=!0,clearInterval(s),Xu.off(`backend.resync.changed`,o)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,Z.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,Z.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Mt,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,Z.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,Z.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,Z.jsx)(G,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,Z.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,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:i}),(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,Z.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,Z.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 yx(){let{openAddPicker:e}=xs();return(0,Z.jsx)(`button`,{type:`button`,onClick:e,title:`Add here`,"aria-label":`Add`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-full bg-foreground text-background hover:opacity-90 transition-opacity`,children:(0,Z.jsx)(H,{className:`w-4 h-4`})})}function bx({count:e}){return e<=0?null:(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>window.dispatchEvent(new CustomEvent(`workspace:documents:link-selection`)),title:`Link ${e} selected document(s) to…`,"aria-label":`Link selection`,className:`shrink-0 flex items-center justify-center gap-1 h-7 min-w-7 rounded-full bg-info px-1.5 text-info-foreground hover:bg-info transition-colors touch-target`,children:[(0,Z.jsx)(Gt,{className:`w-3.5 h-3.5`}),(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold leading-none`,children:e})]})}function xx({urlType:e,urlDisplay:t,onUrlClick:n,onUrlSubmit:r}){let i=t.match(/^(.*?:\/\/)(.*)$/),a=i?.[1]??``,o=i?.[2]??t,s=(0,X.useRef)(null);(0,X.useEffect)(()=>{s.current&&(s.current.value=o)},[o]);let c=(0,Z.jsxs)(`span`,{className:`font-mono text-xs px-1.5 py-0.5 rounded bg-muted border text-muted-foreground shrink-0`,children:[`[`,e.replace(`-`,`:`),`]`]}),l=n?(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:`Browse tree`,"aria-label":`Browse tree`,className:`shrink-0 flex items-center gap-1 rounded hover:opacity-80 transition-opacity`,children:[(0,Z.jsx)(Mn,{className:`w-3.5 h-3.5 text-muted-foreground`}),c]}):c;return r?(0,Z.jsxs)(`div`,{className:`flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full border border-transparent bg-muted/60 px-3 transition-colors hover:bg-muted focus-within:border-border focus-within:bg-background focus-within:shadow-elevation-1`,children:[l,(0,Z.jsxs)(`form`,{className:`flex flex-1 min-w-0 items-center`,onSubmit:e=>{e.preventDefault(),r(s.current?.value??o)},children:[a&&(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-sm text-muted-foreground select-none`,children:a}),(0,Z.jsx)(`input`,{ref:s,type:`text`,defaultValue:o,onKeyDown:e=>{e.key===`Escape`&&s.current&&(s.current.value=o)},spellCheck:!1,autoComplete:`off`,title:`Edit path; press Enter to go`,className:`w-full min-w-0 flex-1 truncate bg-transparent px-1 py-1 font-mono text-sm text-foreground focus:outline-none`})]})]}):(0,Z.jsxs)(`div`,{className:`flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full bg-muted/60 px-3`,children:[l,n?(0,Z.jsx)(`button`,{type:`button`,onClick:n,title:`Browse tree`,className:`flex-1 truncate rounded px-1 -mx-1 text-left text-sm text-foreground transition-colors hover:bg-accent active:bg-accent`,children:t}):(0,Z.jsx)(`span`,{className:`text-sm text-foreground truncate flex-1`,children:t})]})}function Sx({urlType:e,urlDisplay:t,contextPath:n,treeName:r,workspaceId:i,documents:a,isLoading:o,totalCount:s,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,canvasInfo:E,isCanvasPinned:D,onTogglePinCanvas:O,onSaveAsCanvas:A,onShareCanvas:j,onUnshareCanvas:M,onDeleteCanvas:N,isSharingCanvas:P,isDeletingCanvas:F,isCanvasShared:I,isCanvasLocked:ee,backendSearchQueries:te,onBackendSearch:re,onRemoveBackendQuery:ie,serverSort:L,onServerSortChange:R,scope:ae,onScopeChange:oe,canSaveChanges:se,isSavingChanges:ce,onSaveChanges:z,onUrlClick:le,onUrlSubmit:de,linkTree:fe,selectedCount:pe=0,children:me,contentBanner:ge,folders:_e,onOpenFolder:ve}){let ye=e===`canvas`;return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0 bg-background`,children:[ye&&E?(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[E.color&&(0,Z.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:E.color}}),(0,Z.jsx)($n,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:E.label||t.split(`://`)[1]||`Canvas`}),E.description&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:E.description})]}),se&&z&&(0,Z.jsxs)(`button`,{type:`button`,onClick:z,disabled:ce,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,Z.jsx)(k,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:ce?`Saving...`:`Save filters`})]}),O&&(0,Z.jsxs)(`button`,{type:`button`,onClick:O,"aria-pressed":!!D,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:D?`Unpin from home`:`Pin to home`,children:[D?(0,Z.jsx)(ue,{className:`w-3 h-3`}):(0,Z.jsx)(ne,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:D?`Unpin`:`Pin`})]}),j&&(0,Z.jsxs)(`button`,{type:`button`,onClick:j,disabled:P||F,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:I?`Copy public link`:`Share canvas`,children:[(0,Z.jsx)(_n,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:P?`Sharing...`:I?`Copy link`:`Share`})]}),I&&M&&(0,Z.jsxs)(`button`,{type:`button`,onClick:M,disabled:P||F,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,Z.jsx)(he,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),N&&(0,Z.jsxs)(`button`,{type:`button`,onClick:N,disabled:F||ee&&!I,title:ee&&!I?`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,Z.jsx)(lt,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:F?`Deleting…`:`Delete`})]}),(0,Z.jsx)(bx,{count:pe}),(0,Z.jsx)(yx,{})]}):(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2.5 border-b bg-muted/20 shrink-0`,children:[(0,Z.jsx)(xx,{urlType:e,urlDisplay:t,onUrlClick:le,onUrlSubmit:de}),A&&(0,Z.jsxs)(`button`,{type:`button`,onClick:A,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:`Save as canvas`,children:[(0,Z.jsx)(vn,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Save as canvas`})]}),(0,Z.jsx)(bx,{count:pe}),(0,Z.jsx)(yx,{})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[ge,me||(0,Z.jsx)(N_,{documents:a,isLoading:o,folders:_e,onOpenFolder:ve,contextPath:n,treeName:r,workspaceId:i,totalCount:s,viewMode:`table`,allowViewToggle:!0,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,backendSearchQueries:te,onBackendSearch:re,serverSort:L,onServerSortChange:R,onRemoveBackendQuery:ie,scope:ae,onScopeChange:oe,canSaveChanges:!ye&&se,isSavingChanges:ce,onSaveChanges:z,linkTree:fe})]})]})}var Cx=[{id:`todos`,label:`Todos`},{id:`notes`,label:`Notes`}],wx={id:`default`,name:`All`,kind:`documents`};function Tx(){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 Ex(e){let t=e?.views;if(!Array.isArray(t))return[wx];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`&&Cx.some(e=>e.id===t.app)});return n.length>0?n:[wx]}function Dx({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let c=o?(Bf(o)??0)>.5?`text-black`:`text-white`:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),y=()=>{g(null),v(null)},b=()=>{if(h&&_&&h!==_.id){let t=e.find(e=>e.id===h),n=e.filter(e=>e.id!==h),i=n.findIndex(e=>e.id===_.id);t&&i>=0&&(n.splice(_.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!l)return;let t=d.trim();t&&r(e.map(e=>e.id===l?{...e,name:t}:e)),u(null)},S=(t,n)=>{m(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?Cx.find(e=>e.id===n)?.label??`App`:`View ${e.length+1}`,o=t===`columns`?{id:i,name:a,kind:t,columns:Tx()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),u(i),f(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[wx],n===t?i[0]?.id??wx.id:void 0)};return(0,Z.jsxs)(`div`,{className:K(`flex min-w-0 items-end`,a),children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 items-end gap-0.5 overflow-x-auto pt-1`,children:e.map(r=>{let a=r.id===t;return l===r.id?(0,Z.jsx)(`input`,{autoFocus:!0,value:d,onChange:e=>f(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&u(null)},className:`relative z-[1] h-8 w-28 rounded-t-md border border-b-0 border-input bg-background px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`},r.id):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(r.id),onDoubleClick:()=>{i||(u(r.id),f(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`,g(r.id)},onDragOver:e=>{if(!h||h===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;v(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:K(`group flex h-8 shrink-0 items-center gap-1.5 rounded-t-md px-3 text-xs transition-colors`,a?K(`relative z-[1] border border-b-0 font-medium`,o?c:`border-border bg-background text-foreground`):`mb-[3px] border border-b-0 border-transparent bg-muted/40 text-muted-foreground hover:bg-accent/60 hover:text-foreground`,h===r.id&&`opacity-50`,_?.id===r.id&&(_.before?`border-l-2 border-l-primary`:`border-r-2 border-r-primary`)),style:a&&o?{backgroundColor:o,..._?.id===r.id?{}:{borderColor:o}}:void 0,children:[r.kind===`columns`?(0,Z.jsx)(P,{className:`h-3 w-3 shrink-0`}):r.kind===`app`?r.app===`todos`?(0,Z.jsx)(On,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(xn,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(ht,{className:`h-3 w-3 shrink-0`}),(0,Z.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,Z.jsx)(ce,{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,Z.jsx)(G,{className:K(`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&&(p?(0,Z.jsxs)(`span`,{className:`relative z-[1] mb-1.5 ml-1 flex shrink-0 items-center gap-1`,children:[!e.some(e=>e.id===wx.id)&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{m(!1),r([{...wx},...e],wx.id)},className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(ht,{className:`h-3 w-3`}),` All`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(ht,{className:`h-3 w-3`}),` List`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(P,{className:`h-3 w-3`}),` Board`]}),Cx.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[e.id===`todos`?(0,Z.jsx)(On,{className:`h-3 w-3`}):(0,Z.jsx)(xn,{className:`h-3 w-3`}),` `,e.label]},e.id)),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]}):(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!0),title:`Add view`,"aria-label":`Add view`,className:`relative z-[1] mb-1.5 ml-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,Z.jsx)(H,{className:`h-3.5 w-3.5`})}))]})}var Ox=`data/schema/note`;function kx(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null);(0,X.useEffect)(()=>{let o=!1;return Si(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,X.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,X.useCallback)(()=>s(e=>e+1),[])}}function Ax({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=kx(e,t,n,uo,`tasks`),[o,s]=(0,X.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,Z.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,Z.jsx)(ov,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function jx({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i}=kx(e,t,n,Ox);return(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto p-4`,children:(0,Z.jsx)(N_,{documents:r,isLoading:i,contextPath:n,treeName:t,workspaceId:e,totalCount:r.length,viewMode:`card`})})}function Mx({app:e,...t}){return e===`todos`?(0,Z.jsx)(Ax,{...t}):(0,Z.jsx)(jx,{...t})}var Nx=[{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 Px(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function Fx({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)({}),p=(0,X.useRef)(null),[m,h]=(0,X.useState)(!1),g=(0,X.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,X.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=Nx.filter(e=>!n.some(t=>t.id===e.id));return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.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=>Px(e,t.schemas)).filter(e=>{if(!a)return!0;let t=bo(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,Z.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-lg 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,Z.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,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,Z.jsx)(`span`,{className:`flex-1`}),!i&&(0,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`div`,{className:`px-3 pb-2`,children:(0,Z.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,Z.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=bo(e);return(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(ep,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,Z.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,Z.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,Z.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,Z.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,Z.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,Z.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,Z.jsx)(H,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,Z.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,Z.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,Z.jsx)(Ye,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,Z.jsx)(Xg,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var Ix=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function Lx(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function Rx(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>Rx(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:Lx(e)}];let r=Ix(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:Lx(e)}))}function zx(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 Bx(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 Vx(e,t,n=new Map){let r=Ix(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:Lx(n)}],ids:zx(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...Rx(r.context,`context`,n),...Rx(r.directory,`directory`,n)],a=Ix(r.changed);a&&i.push(...Rx(a.context,`context`,n),...Rx(a.directory,`directory`,n));let o=zx(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 Hx(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function Ux(e,t){return e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree?!1:Hx(e.path,t.path)}function Wx(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>Ux(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 Gx=(0,X.createContext)(null);function Kx(){let e=(0,X.useContext)(Gx);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function qx(e,t,n={}){return Xu.request(Iu,{workspace:e,specs:t,opts:n})}function Jx(e,t,n){return Xu.request(Lu,{sessionId:e,label:t,spec:n})}function Yx(e){return Xu.request(Ru,{sessionId:e})}function Xx(e,t={}){return Xu.request(zu,{sessionId:e,...t})}function Zx(e){return Xu.request(Bu,{sessionId:e})}function Qx(e){return Xu.on(Vu,e)}var $x=100;function eS({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),f=(0,X.useRef)([]),p=(0,X.useRef)(new Map),m=(0,X.useRef)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(null),_=(0,X.useRef)({}),v=(0,X.useRef)(null),y=(0,X.useMemo)(()=>JSON.stringify(t),[t]),b=(0,X.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,X.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,X.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=$x){let i=e.slice(r,r+$x),a=await Ki(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,X.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]),w=(0,X.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,X.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await qx(e,JSON.parse(y),JSON.parse(b));if(t){Zx(r.sessionId).catch(()=>{});return}n=r.sessionId,m.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await w(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=Xu.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&Zx(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,X.useEffect)(()=>{if(!c)return;let e=Qx(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):w(e.ids,e.count)}});return()=>{e?.()}},[c,C,w]);let T=(0,X.useCallback)(async()=>{let e=m.current;if(e)try{let t=await Yx(e);await w(t.ids,t.count)}catch{}},[w]),E=(0,X.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await Jx(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await w(r.ids,r.count)},[w]),D=(0,X.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 T();return}let r=await Xx(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,T]);(0,X.useEffect)(()=>{v.current=D},[D]);let O=(0,X.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await Xx(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 Jx(r,e,{ids:i.ids});return await w(a.ids,a.count),i.ids},[w]);return{documents:i,count:o,ready:c!==null,error:u,setCue:E,resync:T,rank:D,rankAndPin:O}}var tS=`canvas:query-debug`,nS=`canvas:query-debug-changed`;function rS(){try{return localStorage.getItem(tS)===`1`}catch{return!1}}function iS(e){try{e?localStorage.setItem(tS,`1`):localStorage.removeItem(tS)}catch{}window.dispatchEvent(new CustomEvent(nS,{detail:e}))}function aS(){let[e,t]=(0,X.useState)(rS);return(0,X.useEffect)(()=>{let e=()=>t(rS());return window.addEventListener(nS,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(nS,e),window.removeEventListener(`storage`,e)}},[]),e}function oS({data:e,className:t}){let[n,r]=(0,X.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,X.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,Z.jsxs)(`div`,{className:K(`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,Z.jsxs)(`div`,{className:K(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,Z.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,Z.jsx)(Ge,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5`}),`Query debug`,(0,Z.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,Z.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,Z.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,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.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,Z.jsxs)(Z.Fragment,{children:[` A jump at `,(0,Z.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,Z.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,Z.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,Z.jsx)(`tbody`,{children:i.map((e,t)=>(0,Z.jsxs)(`tr`,{className:K(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,Z.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,Z.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,Z.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,Z.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,Z.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 sS(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 cS=new Map;function lS(e,t,n){return`${e}\0${t}\0${n}`}function uS(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${lS(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function dS(e,t,n){let r=lS(e,t,n);for(let e of cS.keys())e.startsWith(r)&&cS.delete(e)}function fS(e,t){let n=`${e}\0`;for(let[e,r]of cS){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);Wx(t,{tree:i,kind:ba(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&cS.delete(e)}}function pS(e,t){if(!t?.treeName)return;let n=t.workspaceName??e,r=t.path?lS(n,t.treeName,t.path):`${n}\0${t.treeName}\0`;for(let e of cS.keys())e.startsWith(r)&&cS.delete(e)}function mS(){let{workspaceName:e}=tl();return e?(0,Z.jsx)(_x,{workspaceName:e,children:(0,Z.jsx)(hS,{})}):null}function hS(){let{workspaceName:e,treeName:t}=tl(),n=Jc(),r=Zc(),{showToast:i}=po(),a=new URLSearchParams(n.search),o=(()=>{let e=a.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(a.get(`search`)||``).trim();return t?[t]:[]})(),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(0),v=aS(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(v);x!==v&&(S(v),v||b(null));let[C,w]=(0,X.useState)(`path`),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(``),[N,P]=(0,X.useState)(!1),[F,I]=(0,X.useState)(!1),[ee,te]=(0,X.useState)(!1),[ne,re]=(0,X.useState)(null),[ie,L]=(0,X.useState)(1),[R,ae]=(0,X.useState)(50),[oe,se]=(0,X.useState)(o),[ce,z]=(0,X.useState)(null),{state:le,saveFilters:ue,toggleView:de,setSort:fe,setAccentColor:pe,setMapDocuments:me,hasActiveFilters:he}=xs(),ge=le.filters.features.allOf,_e=le.filters.features.anyOf,ve=le.filters.features.noneOf,ye=Oy(le.filters.timeline),B=Ty(le.filters.geo),be=Ey(le.filters.lens,le.filters.geo.includeUnlocated),V=le.filters.lens.ids,xe=[...ye,...B,...be],H=le.filters.sort??Cy,Se=JSON.stringify({a:ge,b:_e,c:ve,d:xe,i:V,s:H}),Ce=JSON.stringify({a:ge,b:_e,c:ve,d:xe,s:H}),U=uv(n.pathname).path,W=t??`context`,we=W===`backends`,[Te,Ee]=(0,X.useState)([]);(0,X.useEffect)(()=>{!we||!e||wa(e).then(Ee).catch(()=>Ee([]))},[we,e]);let De=we?Aa(U,Te):null,[Oe,ke]=(0,X.useState)(!1),Ae=`${W}\0${U}`,[je,Me]=(0,X.useState)(Ae);je!==Ae&&(Me(Ae),ke(!1));let G=a.get(`layer`)===`1`,Ne=a.get(`layerId`)||null,[Pe,Fe]=(0,X.useState)(null),[Ie,Le]=(0,X.useState)(null),[Re,ze]=(0,X.useState)(`left`),[Be,Ve]=(0,X.useState)([]),{openM2Drawer:He}=Qb(),Ue=km(),[We,Ge]=(0,X.useState)([]),Ke=(0,X.useMemo)(()=>{if(!Pe||U===`/`||G)return null;let e=U.split(`/`).filter(Boolean),t=Pe;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Pe,U,G]),qe=Ke?.type===`canvas`?`canvas`:null,Je=(0,X.useRef)(null);(0,X.useEffect)(()=>{!e||!Pe||G||Je.current===`${e}/${W}`&&(U!==`/`&&!Ke||Tb(e,W,U))},[e,Pe,G,U,Ke,W]);let Ye=(0,X.useMemo)(()=>G||C===`workspace`||oe.length>0||ba(W)!==`directory`?[]:sS(Pe,U),[Pe,U,W,G,C,oe]),Xe=G?null:U===`/`?Pe:Ke,Ze=`${W}\0${U}`,[$e,et]=(0,X.useState)(null),tt=$e?.key===Ze?$e.views:Ex(Xe?.metadata),nt=$e?.key===Ze?$e.activeId:tt[0]?.id??wx.id,rt=tt.find(e=>e.id===nt)??tt[0]??wx,it=e=>et({key:Ze,views:tt,activeId:e}),at=(t,n)=>{et({key:Ze,views:t,activeId:n??nt}),Ca(e,U,{metadata:{...Xe?.metadata??{},views:t}},W).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},ot=qe===`canvas`&&typeof Ke?.querySpec?.query==`string`?Ke.querySpec.query:``,st=qe===`canvas`?{label:Ke?.label,description:Ke?.description,color:Ke?.color}:null,{isPinned:ct,pin:lt,unpin:ut,pins:dt}=Kx(),ft=s?.name,pt=(0,X.useMemo)(()=>ft&&qe===`canvas`&&!G?{workspaceName:ft,treeName:W,path:U}:null,[ft,qe,G,W,U]),mt=pt?ct(pt):!1,ht=Ke?.id,gt=Ke?.label,_t=(0,X.useCallback)(async()=>{if(pt)try{let e=dt.find(e=>e.workspaceName===pt.workspaceName&&e.treeName===pt.treeName&&e.path===pt.path);e?await ut(e.id):await lt({...pt,layerId:ht,label:gt})}catch(e){console.error(`Failed to update home pins:`,e)}},[pt,dt,lt,ut,ht,gt]),vt=e?`${e}://${U===`/`?``:U.replace(/^\//,``)}`:``,yt=Hf(s?.color)||null;(0,X.useEffect)(()=>(pe(yt),()=>pe(null)),[yt,pe]);let bt=(0,X.useCallback)(async t=>{let n=V;if(t?.anyOf?.length&&_e.length&&(n=((await Si(e,U,W,{limit:0,anyOf:_e,ids:V,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await Si(e,U,W,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...ge,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:_e,noneOf:ve,filters:xe,ids:n,queries:[...oe,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,U,W,Se,oe]);(0,X.useEffect)(()=>{e&&(async()=>{d(!0);try{let t=await Y.get(`${Qr.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,X.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 xt=(V?.length??0)>0&&!G&&!(Oe&&De)&&oe.length<=1,{documents:St,count:Ct,ready:wt,setCue:Tt,resync:Et,rank:Dt}=eS({workspaceRef:e,specs:(0,X.useMemo)(()=>{let e={features:{allOf:ge,anyOf:_e,noneOf:ve},filters:xe};return C!==`workspace`&&(ba(W)===`directory`?e.directory={tree:W,path:U}:e.context=U),[{label:`scope`,spec:e}]},[Ce,U,W,C]),opts:(0,X.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:xt}),Ot=xt&&wt,kt=(0,X.useRef)(!1);(0,X.useEffect)(()=>{kt.current=Ot},[Ot]);let At=oe.length===1?oe[0].trim():``;(0,X.useEffect)(()=>{wt&&Dt(At?{text:At}:null,{limit:R,offset:(ie-1)*R}).catch(()=>{})},[wt,At,R,ie,Dt]);let jt=(V??[]).join(`,`);(0,X.useEffect)(()=>{wt&&Tt(`lens`,{ids:V??[]}).catch(()=>{})},[wt,jt,Tt,V]);let Mt=Ot?St:f,Nt=Ot?Ct:g,Pt=(0,X.useRef)(new Set);(0,X.useEffect)(()=>{Pt.current=new Set(Mt.map(e=>Number(e.id)))},[Mt]);let Ft=le.geoSelection;(0,X.useEffect)(()=>{me(Mt,s?.name??null)},[Mt,s?.name,me]),(0,X.useEffect)(()=>()=>me([]),[me]);let It=(0,X.useMemo)(()=>Ft?Mt.filter(e=>Gg(e,Ft,le.filters.geo.includeUnlocated)):Mt,[Mt,Ft,le.filters.geo.includeUnlocated]),Lt=(0,X.useRef)(0),Rt=(0,X.useRef)(``),zt=(0,X.useCallback)(async t=>{if(!e||kt.current)return;let n=++Lt.current,r=Oe&&De?`${C}:unfiled`:C,a=(V?.length??0)>0,o=uS(e,W,U,ie,R,oe.join(`␟`),Ce,G&&Ne?Ne:``,r),s=a&&o===Rt.current;Rt.current=o;let c=uS(e,W,U,ie,R,oe.join(`␟`),Se,G&&Ne?Ne:``,r),l=a||v?void 0:cS.get(c);if(l){p(l.documents),_(l.totalCount),h(!1);return}(t?.silent??s)||h(!0);try{let t;t=Oe&&De?await Wi(e,De.driver,De.address,{linked:!1,limit:R,offset:(ie-1)*R}):G&&Ne&&C!==`workspace`?await Fa(e,W,Ne,{limit:R,page:ie,queries:oe,allOf:ge,anyOf:_e,noneOf:ve,filters:xe,ids:V,sortBy:H.sortBy||void 0,order:H.order}):await Ki(e,U,ge,{limit:R,page:ie,treeName:W,treeType:W===`directory`||W===`backends`?`directory`:`context`,queries:oe,anyOf:_e,noneOf:ve,filters:xe,ids:V,sortBy:H.sortBy||void 0,order:H.order,scope:C,debug:v&&oe.length>0,debugLimit:200});let r=t.payload||[],i=t.totalCount||t.count||0;if(a||cS.set(c,{documents:r,totalCount:i}),n!==Lt.current)return;let o=t.debug,l=o?.imageDistances??o?.distances??null;b(l?{query:oe[oe.length-1]??``,distances:l}:null),p(s?e=>e.length===r.length&&e.every((e,t)=>e.id===r[t].id)?e:r:r),_(i)}catch(e){if(n!==Lt.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),p([]),_(0)}finally{n===Lt.current&&h(!1)}},[e,U,W,Ne,G,ie,R,s?.status,oe,Se,C,Oe,v]);(0,X.useEffect)(()=>{zt()},[zt]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Le({treeName:n.treeName||`context`,path:cv(n.path||`/`)}),ze(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,W,U]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(e&&pS(e,n),!(n?.treeName&&n.treeName!==W)&&(n?.path&&n.path!==U||(e&&dS(e,W,U),zt({silent:!0}))))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[zt,e,U,W]);let Bt=s?.name,Vt=s?.id;(0,X.useEffect)(()=>{if(!e||!Bt&&!Vt)return;let t=[Bt,Vt].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>Xu.emit(`subscribe`,{channel:e}));n();let r=Xu.on(`connect`,n),i=new Map,a=!1,o=()=>{Lr(e).then(e=>{a||(i=Bx(e))}).catch(()=>{})};o();let s=null,c=0,l=()=>{if(s=null,c=Date.now(),kt.current){Et();return}zt({silent:!0})},u=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=Vx(t,n,i);fS(e,r),Wx(r,{tree:W,kind:ba(W),path:U,wholeWorkspace:C===`workspace`},Pt.current)&&(s||=setTimeout(l,Math.max(200,c+1500-Date.now())))},d=[`document.inserted`,`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,u(e)]);return d.forEach(([e,t])=>Xu.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),d.forEach(([e,t])=>Xu.off(e,t))}},[e,Vt,Bt,W,U,C,zt,Et]);let Ht=`${U}\0${W}\0${Ne??``}\0${C}`,[Ut,Wt]=(0,X.useState)(Ht);Ut!==Ht&&(Wt(Ht),L(1),z(null));let Gt=`${U}\0${W}\0${Ne??``}`,[Kt,qt]=(0,X.useState)(Gt);Kt!==Gt&&(qt(Gt),w(`path`));let Jt=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;M(n),A({parentPath:e,captureView:t})},Yt=a.get(`createCanvas`)===`1`,[Xt,Zt]=(0,X.useState)(!1);Xt!==Yt&&(Zt(Yt),Yt&&Jt(U,!1)),(0,X.useEffect)(()=>{if(!Yt)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}`,{replace:!0})},[Yt,U]);let Qt=(0,X.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.pathname,n.search,r]),$t=o.join(`␟`),[en,tn]=(0,X.useState)($t);en!==$t&&(tn($t),se(o),L(1));let nn=`${$t}\0${qe??``}\0${ot}\0${U}\0${ce??``}`,[rn,an]=(0,X.useState)(nn);rn!==nn&&(an(nn),o.length>0||qe!==`canvas`||ce===U||(se(ot?[ot]:[]),L(1)));let on=(0,X.useCallback)(e=>{let t=e.trim();t&&(z(null),se(e=>{if(e.includes(t))return e;let n=[...e,t];return Qt(n),L(1),n}))},[Qt,z,se,L]),sn=(0,X.useCallback)(e=>{se(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&z(U),Qt(n),L(1),n})},[Qt,U,z,se,L]),cn=oe.join(` `).trim(),ln=!!le.activeContextType&&(le.isDirty||cn!==(qe===`canvas`?ot:le.savedSearchQuery||``));!e&&Pe!==null&&Fe(null),(0,X.useEffect)(()=>{let t=!1;if(!e)return;let n=(n=!1)=>{n&&fa(e,W),vi(e,W,{force:n}).then(n=>{t||(Je.current=`${e}/${W}`,Fe(n))}).catch(()=>{t||Fe(null)})};n(!1);let r=t=>{let r=t.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==W||n(!0)};window.addEventListener(`workspace:tree:refresh`,r);let i=null,a=()=>{i&&clearTimeout(i),i=setTimeout(()=>{window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}}))},200)},o=[`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.layer.updated`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`];return o.forEach(e=>Xu.on(e,a)),()=>{t=!0,i&&clearTimeout(i),window.removeEventListener(`workspace:tree:refresh`,r),o.forEach(e=>Xu.off(e,a))}},[e,W]),!(e&&qe===`canvas`&&!G)&&ne!==null&&re(null),(0,X.useEffect)(()=>{let t=!1;if(!(!e||qe!==`canvas`||G))return Gr(e,U,W).then(e=>{t||re(e)}).catch(()=>{t||re(null)}),()=>{t=!0}},[e,U,W,qe,G]);let un=async()=>{if(s){E(!0);try{let t=await ui(e||s.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{E(!1)}}},dn=async t=>{if(s)try{await Or(e||s.id,[t],U,[],W,yn,{trashIfOrphaned:!0}),dS(e||s.id,W,U),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document removed from workspace path.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},fn=async t=>{if(s)try{await Ha(e||s.id,[t],U,[],W,yn),dS(e||s.id,W,U),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},pn=async t=>{if(s)try{await Or(e||s.id,t,U,[],W,yn,{trashIfOrphaned:!0}),dS(e||s.id,W,U),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},mn=async t=>{if(s)try{await Ha(e||s.id,t,U,[],W,yn),dS(e||s.id,W,U),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},hn=async t=>{if(s)try{let n=await Mr(e||s.id,[t]);if(n.failed?.length){i({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},gn=async t=>{if(s)try{let n=await Mr(e||s.id,t),r=new Set(n.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);p(e=>e.filter(e=>!r.has(e.id))),_(e=>Math.max(0,e-r.size));let a=[n.successful?.length?`${n.successful.length} destroyed`:null,n.failed?.length?`${n.failed.length} failed`:null].filter(Boolean).join(`, `);i({title:`Done`,description:a||`No documents destroyed`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},_n=e=>{O({documentIds:e,operation:`copy`,sourcePath:U,sourceTreeName:W}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},vn=e=>{O({documentIds:e,operation:`cut`,sourcePath:U,sourceTreeName:W}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},yn=ba(W),bn=async(t,n,r={})=>{if(!e)return!1;let a=r.targetTreeName??W,o=r.targetTreeType??yn;try{let s=await $r(e,t,n,a,o);if(s){dS(e,a,t);let o=r.sourceTreeName||D?.sourceTreeName,s=r.sourcePath||D?.sourcePath;if((r.move||D?.operation===`cut`)&&s&&o){let t=ba(o);await Or(e,n,s,[],o,t),dS(e,o,s),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:s,treeName:o}}))}await zt(),O(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:a}})),i({title:`Success`,description:`${n.length} document(s) ${r.move||D?.operation===`cut`?`moved`:`pasted`} to "${t}"`})}return s}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},xn=async(t,n)=>{if(!e)return!1;try{let r=(await Fi(e,n,t,W,yn)).length>0;return r&&(window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:W}})),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}},Sn=async()=>{if(!(!s||g===0)&&window.prompt(`Type PURGE to permanently delete all ${g} matching documents.`)===`PURGE`)try{let t=await ci(e||s.id,U,[],[],{},W);await zt(),i({title:`Success`,description:`${t.deleted} document(s) purged.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}},Cn=()=>Jt(U,!0),wn=async()=>{if(!(!e||!k||!j.trim())){P(!0);try{let t=j.trim(),n=k.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`;await Ja(e,i,W,k.captureView?{metadata:{toolbox:le.filters},querySpec:{features:le.filters.features,filters:[...Oy(le.filters.timeline),...Ty(le.filters.geo)],query:cn||void 0,sort:le.filters.sort?.sortBy?le.filters.sort:null}}:{}),A(null),fa(e,W);try{let t=await vi(e,W,{force:!0});Fe(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(dv(e,i,W))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{P(!1)}}},Tn=async()=>{if(!(!e||qe!==`canvas`)){I(!0);try{let t=ne||await Ai(e,U,W);re(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)}}},En=async()=>{if(ne){I(!0);try{await Ga(ne.code),re(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:W}})),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)}}},Dn=async()=>{if(!e||qe!==`canvas`||U===`/`)return;let t=st?.label||U.split(`/`).pop()||`canvas`,n=ne?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){te(!0);try{if(ne)await Ga(ne.code),re(null);else if(Ke?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await xi(e,U,!1,W);let n=U.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:W}})),r(dv(e,a,W)),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{te(!1)}}},On=(0,X.useCallback)(async t=>{if(!e||!Ie)return;let n={treeName:W,path:U},r=Re===`left`?n:Ie,a=Re===`left`?Ie:n,o=Re===`left`?Be:We;if(o.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let s=ba(a.treeName);try{if(!await $r(e,a.path,o,a.treeName,s))return;if(dS(e,a.treeName,a.path),t){let t=ba(r.treeName);await Or(e,o,r.path,[],r.treeName,t),dS(e,r.treeName,r.path)}[r,a].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),i({title:t?`Moved`:`Copied`,description:`${o.length} document(s) → "${a.path}"`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,Ie,Re,W,U,Be,We,i]);if((0,X.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(),On(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ie,On]),u)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!s)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let kn=qe===`canvas`&&!G&&!!Ke,An=(0,Z.jsx)(Sx,{urlType:G?ba(W)===`directory`?`${W}-layer`:`context-layer`:qe===`canvas`?`canvas`:ba(W)===`directory`?W:`context`,urlDisplay:vt,contextPath:U,treeName:W,workspaceId:e||s.id,documents:It,isLoading:m,totalCount:Nt,currentPage:ie,pageSize:R,onPageChange:L,onPageSizeChange:e=>{ae(e),L(1)},onRemoveDocument:U===`/`?void 0:dn,onDeleteDocument:fn,onDestroyDocument:hn,onRemoveDocuments:U===`/`?void 0:pn,onDeleteDocuments:mn,onDestroyDocuments:gn,onCopyDocuments:_n,onCutDocuments:vn,onPasteDocuments:we?void 0:bn,onImportDocuments:we?void 0:xn,onSelectionChange:Ve,selectedCount:Be.length,onUrlClick:()=>He(`workspaces`,`detail`,e??null),onUrlSubmit:t=>r(dv(e,cv(`/`+t),W)),folders:Ye,onOpenFolder:t=>r(dv(e,cv(t),W)),scope:C,onScopeChange:w,pastedDocumentIds:D?.documentIds,linkTree:Pe,onPurgeDocuments:we?void 0:Sn,disablePurgeDocuments:!1,canvasInfo:st??void 0,isCanvasPinned:mt,onTogglePinCanvas:pt?_t:void 0,onSaveAsCanvas:Pe&&qe!==`canvas`&&!G&&!we?Cn:void 0,onShareCanvas:qe===`canvas`&&!G?Tn:void 0,onUnshareCanvas:ne?En:void 0,onDeleteCanvas:qe===`canvas`&&!G?Dn:void 0,isSharingCanvas:F,isDeletingCanvas:ee,isCanvasShared:!!ne,isCanvasLocked:!!Ke?.locked,backendSearchQueries:oe,onBackendSearch:on,serverSort:le.filters.sort,onServerSortChange:fe,onRemoveBackendQuery:sn,canSaveChanges:ln,isSavingChanges:le.isSaving,onSaveChanges:ue,contentBanner:v&&y?(0,Z.jsx)(oS,{data:y,className:`mb-3`}):null,children:kn&&Ke?(0,Z.jsx)(Pv,{workspaceId:e||s.id,treeName:W,path:U,layerId:Ke.id,querySpec:Ke.querySpec,metadata:Ke.metadata,isLocked:!!Ke.locked,fetchDocuments:le.isDirty?bt:void 0}):!we&&rt.kind===`columns`?(0,Z.jsx)(Fx,{documents:It,workspaceId:e||s.id,columns:rt.columns??[],onColumnsChange:e=>at(tt.map(t=>t.id===rt.id?{...t,columns:e}:t))}):!we&&rt.kind===`app`&&rt.app?(0,Z.jsx)(Mx,{app:rt.app,workspaceId:e||s.id,treeName:W,path:U}):null});return(0,Z.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0`,children:[(0,Z.jsx)(vx,{workspaceId:s.id,workspaceName:s.label||s.name},s.id),(0,Z.jsxs)(`div`,{className:`relative shrink-0 max-sm:border-b`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border max-sm:hidden`,style:Hf(s.color)?{backgroundColor:Hf(s.color)}:void 0}),!kn&&!we&&Xe&&(0,Z.jsxs)(`div`,{className:`relative px-2 pt-1.5 sm:hidden`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border`,style:Hf(s.color)?{backgroundColor:Hf(s.color)}:void 0}),(0,Z.jsx)(Dx,{accentColor:Hf(s.color),views:tt,activeId:nt,onSelect:it,onSave:at,readOnly:!1})]}),(0,Z.jsxs)(`div`,{className:`flex h-12 items-center gap-3 px-4`,children:[(0,Z.jsx)(mb,{title:Ue?`Back to workspace tree`:`Back to workspaces`,onBack:()=>Ue?He(`workspaces`,`detail`,e||s.id):r(`/workspaces`)}),(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0 ${s.status===`active`?`bg-success`:s.status===`error`?`bg-destructive`:`bg-muted-foreground`}`,title:s.status}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>He(`workspaces`,`detail`,e||s.id),title:`Browse workspace tree`,className:`flex min-w-0 items-center gap-1.5 truncate rounded px-1 -mx-1 text-left text-sm font-medium transition-colors hover:bg-accent`,children:[(0,Z.jsx)(c,{icon:s.icon||`ph:stack-fill`,width:16,height:16,color:Hf(s.color),className:K(`shrink-0`,!Hf(s.color)&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`truncate`,children:s.label||s.name})]}),!kn&&!we&&Xe?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Dx,{className:`min-w-0 flex-1 self-stretch max-sm:hidden`,accentColor:Hf(s.color),views:tt,activeId:nt,onSelect:it,onSave:at,onOpenToSide:e=>{Le({treeName:W,path:U,viewId:e}),ze(`right`)},readOnly:!1}),(0,Z.jsx)(`div`,{className:`flex-1 sm:hidden`})]}):(0,Z.jsx)(`div`,{className:`flex-1`}),De&&(0,Z.jsx)(`button`,{onClick:()=>{ke(!Oe),L(1)},className:K(`flex items-center gap-1.5 px-3 py-1 text-xs border rounded-md transition-colors`,Oe?`bg-warning/15 border-warning/40 text-warning`:`hover:bg-accent text-muted-foreground hover:text-foreground`),title:`Show only documents not filed into any context/directory tree (safe to purge from the backend)`,children:`Unfiled only`}),s.status===`active`?(0,Z.jsx)(`button`,{onClick:()=>de(`tools`),className:K(`flex h-7 w-7 items-center justify-center border rounded-md transition-colors touch-target`,he?`border-info bg-info text-info-foreground hover:bg-info/90`:le.t1Open&&le.t1View===`tools`?`bg-accent text-foreground`:`hover:bg-accent text-muted-foreground hover:text-foreground`),"aria-label":`Filters`,title:he?`Toolbox filters are active and narrow this view`:`Open the toolbox filters`,children:(0,Z.jsx)(Qe,{className:`h-3.5 w-3.5`})}):(0,Z.jsx)(`button`,{onClick:un,disabled:T,className:`px-3 py-1 text-xs border rounded-md hover:bg-accent disabled:opacity-50 touch-target`,children:T?`Starting…`:`Start`}),(0,Z.jsx)(pb,{})]})]}),k&&(0,Z.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,Z.jsx)(vb,{title:`New canvas`,onClose:()=>A(null),children:(0,Z.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),wn()},className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,Z.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:j,onChange:e=>M(e.target.value),onKeyDown:e=>{e.key===`Escape`&&A(null)},autoFocus:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,Z.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:k.parentPath===`/`?`/`:k.parentPath})]})]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:k.captureView,onChange:e=>A({...k,captureView:e.target.checked})}),(0,Z.jsxs)(`span`,{children:[`Capture the current view`,(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:!j.trim()||N,children:N?`Creating…`:`Create canvas`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})})}),(0,Z.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2 p-2 bg-muted/20`,children:[(0,Z.jsx)(`div`,{"data-canvas-pane":!0,className:K(`flex-1 min-w-0 rounded-lg border bg-background overflow-hidden`,Ie&&(Re===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||ze(`left`)},children:An}),Ie&&e&&(0,Z.jsx)(_S,{workspaceName:e,pane:Ie,isFocused:Re===`right`,clipboard:D,setClipboard:O,onFocus:()=>ze(`right`),onSelectionChange:Ge,onNavigate:e=>Le(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Le(null),ze(`left`),Ge([])}})]})]})}function gS(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 _S({workspaceName:e,pane:t,isFocused:n=!1,clipboard:r,setClipboard:i,onFocus:a,onSelectionChange:o,onNavigate:s,onClose:c}){let{showToast:l}=po(),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(0),[v,y]=(0,X.useState)(1),[b,x]=(0,X.useState)(50),S=ba(t.treeName),C=gS(u,t.path),w=C?.type===`canvas`,T=(0,X.useMemo)(()=>S===`directory`?sS(u,t.path):[],[u,t.path,S]),E=t.viewId?Ex(C?.metadata).find(e=>e.id===t.viewId)??null:null,D=`${e}://${t.path===`/`?``:t.path.replace(/^\//,``)}`,O=(0,X.useCallback)(async()=>{let n=uS(e,t.treeName,t.path,v,b,``,``),r=cS.get(n);if(r){p(r.documents),_(r.totalCount);return}h(!0);try{let r=await Ki(e,t.path,[],{limit:b,page:v,treeName:t.treeName,treeType:S}),i=r.payload||[],a=r.totalCount||r.count||0;p(i),_(a),cS.set(n,{documents:i,totalCount:a})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),p([]),_(0)}finally{h(!1)}},[e,t.path,t.treeName,S,b,v,l]);(0,X.useEffect)(()=>{let n=!1,r=(r=!1)=>{r&&fa(e,t.treeName),vi(e,t.treeName,{force:r}).then(e=>{n||d(e)}).catch(()=>{n||d(null)})};r(!1);let i=n=>{let i=n.detail;i?.workspaceName&&i.workspaceName!==e||i?.treeName&&i.treeName!==t.treeName||r(!0)};return window.addEventListener(`workspace:tree:refresh`,i),()=>{n=!0,window.removeEventListener(`workspace:tree:refresh`,i)}},[e,t.treeName]),(0,X.useEffect)(()=>{O()},[O]),(0,X.useEffect)(()=>{let n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||(pS(e,r),!(r?.treeName&&r.treeName!==t.treeName)&&(r?.path&&r.path!==t.path||(dS(e,t.treeName,t.path),O())))};return window.addEventListener(`workspace:documents:refresh`,n),()=>window.removeEventListener(`workspace:documents:refresh`,n)},[O,e,t.treeName,t.path]);let k=(0,X.useCallback)(async(n,a,o={})=>{let s=o.targetTreeName??t.treeName,c=o.targetTreeType??S;try{let t=await $r(e,n,a,s,c);if(t){dS(e,s,n);let t=o.sourcePath||r?.sourcePath,c=o.sourceTreeName||r?.sourceTreeName;if((o.move||r?.operation===`cut`)&&t&&c){let n=ba(c);await Or(e,a,t,[],c,n),dS(e,c,t),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:c}}))}i(null),await O(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:s}}))}return t}catch(e){return l({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,t.treeName,S,O,l,r,i]),A=(0,X.useCallback)(()=>{dS(e,t.treeName,t.path),O()},[e,t.treeName,t.path,O]),j=(0,X.useCallback)(async n=>{try{await Or(e,n,t.path,[],t.treeName,S),A(),l({title:`Removed`,description:`${n.length} document(s) removed from "${t.path}"`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,t.path,t.treeName,S,A,l]),M=(0,X.useCallback)(async n=>{try{await Ha(e,n,t.path,[],t.treeName,S),A(),l({title:`Deleted`,description:`${n.length} document(s) deleted.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,t.path,t.treeName,S,A,l]),N=(0,X.useCallback)(async t=>{try{let n=await Mr(e,t);if(n.failed?.length&&!n.successful?.length){l({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}A(),l({title:`Destroyed`,description:`${n.successful?.length??t.length} document(s) removed from all backends.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,A,l]);return(0,Z.jsxs)(`div`,{className:K(`relative flex-1 min-w-0 rounded-lg border bg-background overflow-hidden`,n?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||a()},children:[c&&(0,Z.jsx)(`button`,{type:`button`,onClick:c,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`}),(0,Z.jsx)(Sx,{urlType:w?`canvas`:S===`directory`?t.treeName:`context`,urlDisplay:D,contextPath:t.path,treeName:t.treeName,workspaceId:e,documents:f,isLoading:m,totalCount:g,currentPage:v,pageSize:b,onPageChange:y,onPageSizeChange:e=>{x(e),y(1)},onRemoveDocument:t.path===`/`?void 0:e=>j([e]),onRemoveDocuments:t.path===`/`?void 0:j,onDeleteDocument:e=>M([e]),onDeleteDocuments:M,onDestroyDocument:e=>N([e]),onDestroyDocuments:N,onCopyDocuments:e=>{i({documentIds:e,operation:`copy`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{i({documentIds:e,operation:`cut`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:t.treeName===`backends`?void 0:k,onSelectionChange:o,pastedDocumentIds:r?.documentIds,linkTree:u,folders:T,onOpenFolder:s,canvasInfo:w?{label:C?.label,description:C?.description,color:C?.color}:void 0,children:E?.kind===`columns`?(0,Z.jsx)(Fx,{documents:f,workspaceId:e,columns:E.columns??[],onColumnsChange:()=>{},readOnly:!0}):E?.kind===`app`&&E.app?(0,Z.jsx)(Mx,{app:E.app,workspaceId:e,treeName:t.treeName,path:t.path}):null})]})}function vS(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 yS={id:`sketch`,label:`Sketch`,icon:rt,schemas:[lo],canCreate:!0,canEdit:e=>e.schema===lo,createUrl(e){let t=vS(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=vS(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},bS=[{kind:`message`,label:`New Message`,icon:It},{kind:`note`,label:`Note`,icon:xn},{kind:`link`,label:`Link`,icon:Xt},{kind:`todo`,label:`Todo`,icon:On},{kind:`identity`,label:`Identity`,icon:Ze},{kind:`sketch`,label:`Sketch`,icon:rt},{kind:`file`,label:`File`,icon:re},{kind:`photo`,label:`Photo/Video`,icon:L},{kind:`existing`,label:`Existing document`,icon:Ot},{kind:`folder`,label:`Folder`,icon:ut}];function xS(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?bS:bS.filter(e=>e.kind!==`photo`)}function SS({onSelect:e,variant:t=`list`,omit:n}){let r=xS().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,Z.jsx)(Z.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,Z.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,Z.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,Z.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,Z.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,Z.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}var CS=`data/schema/note`,wS=`2.0`;function TS(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!1),u=ih(),d=n.trim().length>0&&!c;async function f(t){l(!0);try{let r=await u.capture(),a={schema:CS,schemaVersion:wS,...i.trim()?{comment:i.trim()}:{},data:{...e.trim()?{title:e.trim()}:{},content:n},metadata:{features:_p(o),...r?{geo:r}:{}}};return await ts(t,[a])}finally{l(!1)}}return{title:e,setTitle:t,content:n,setContent:r,comment:i,setComment:a,tags:o,setTags:s,saving:c,canSave:d,save:f,geotag:u}}function ES(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 DS({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,X.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.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:K(`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,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,Z.jsx)(Mt,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,Z.jsx)(yt,{className:K(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,Z.jsx)(`div`,{className:K(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,Z.jsx)(`div`,{className:K(`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,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.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,Z.jsx)(en,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`p`,{id:`${t}-hint`,className:K(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:ES(e)}),n&&(0,Z.jsx)(Dp,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}function OS(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 kS({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}){let h=Zc(),[g,_]=(0,X.useState)(`portrait`),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),E=o||w;Sf(()=>x(!1),b&&!E),Sf(()=>y(!1),v&&!b);let D=(0,X.useRef)(null),O=km(),{showSuccessToast:k,showErrorToast:A}=to(),j=O&&!u&&!v,[M,N]=(0,X.useState)(!1),P=!u&&!v&&!p&&!M;(0,X.useEffect)(()=>{b&&D.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[b]);let F=async(e,t)=>{if(!(!r||E)){T(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>$r(t.workspaceName,e,a,t.treeName,t.treeType))),k(c),n(),i&&h(OS({...t,path:e[0]}),{replace:!0})}catch(e){A(e instanceof Error?e.message:`Failed to save`)}finally{T(!1)}}},I=async e=>{if(!(!f||!l||e.targetIds.length===0)){C(!0);try{await Xi(l,f,e.predicate,e.targetIds,e.direction),k(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Qp(),x(!1)}catch(e){A(e instanceof Error?e.message:`Failed to create relations`)}finally{C(!1)}}},ee=v?b?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:j?void 0:g===`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},te=!!(f&&l),ne=r&&b&&(0,Z.jsx)(dp,{onClose:()=>x(!1),onConfirm:F,fixedWorkspaceName:l,saving:E||S,savingContent:s,tabs:te?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:te?I:void 0,relationWorkspaceName:l,relationExcludeIds:te?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}),re=(0,Z.jsxs)(`div`,{style:p&&!v?{width:`100%`,height:`100%`,minWidth:0}:ee,onAnimationEnd:e=>{P&&e.target===e.currentTarget&&N(!0)},className:K(`flex flex-col overflow-hidden`,p&&!v?`strip-document-card`:`rounded-2xl border bg-card shadow-elevation-4 transition-[width,height]`,u&&!v&&!p&&`w-full md:w-[var(--document-card-width,min(560px,90vw))]`,j&&`fixed inset-2 z-40 shadow-elevation-5`,P&&`animate-card-in`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,Z.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(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,Z.jsx)(ar,{className:`h-4 w-4`})}),r&&(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>x(!0),disabled:!a||E,children:E?`Saving…`:`Save / Link to…`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p&&!v?p.onToggleExpanded():y(e=>!e),className:K(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,!v&&!p&&`max-md:hidden`),"aria-label":p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,title:p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,children:v||p?.expanded?(0,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,disabled:E,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":`Close`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)($p.Provider,{value:()=>y(e=>!e),children:(0,Z.jsx)(`div`,{className:K(`min-h-0 flex-1 overflow-y-auto`,v&&!d&&`mx-auto w-full max-w-3xl`),children:p&&ne?ne:m})})]});return v?(0,yf.createPortal)((0,Z.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[re,ne&&(0,Z.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:ne})]}),document.body):(0,Z.jsxs)(Z.Fragment,{children:[re,!p&&ne&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!E&&x(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{ref:D,className:`relative shrink-0 md:z-panel md:ml-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:ne})]})]})}function AS({onClose:e,initialData:t}){let n=TS();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setContent(t.content)},[]),(0,Z.jsx)(kS,{title:`New Note`,icon:xn,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Note created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-note-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(Eu,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(To,{kind:`markdown`,value:n.content,onChange:n.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(DS,{geotag:n.geotag,idPrefix:`qa-note-geotag`})]})})}var jS=`data/schema/tab`,MS=`2.0`;function NS(e){try{return new URL(e),!0}catch{return!1}}function PS(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),c=ih(),l=e.trim(),u=NS(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:jS,schemaVersion:MS,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:_p(i),...t?{geo:t}:{}}};return await ts(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 FS({onClose:e,initialData:t}){let n=PS();return(0,X.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,Z.jsx)(kS,{title:`New Link`,icon:Xt,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(DS,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function IS({onClose:e,initialData:t}){let n=mh();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,Z.jsx)(kS,{title:`New Todo`,icon:On,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(eg,{...n,idPrefix:`qa-todo`}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,Z.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,Z.jsx)(DS,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function LS({onClose:e,initialData:t}){let n=lg();return(0,X.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,Z.jsx)(kS,{title:`New Identity`,icon:Ze,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(mg,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,Z.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 RS=3;function zS(e){return`${e.name}:${e.size}:${e.lastModified}`}function BS(e=[]){let[t,n]=(0,X.useState)(()=>e.map(e=>({id:zS(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(t),o=(0,X.useRef)(null),s=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,X.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,X.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,X.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(zS(e))).map(e=>({id:zS(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,X.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,X.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,X.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,X.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await ms(e),d=r===`backends`?await ds(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(RS,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 co(n,{...d,key:Zo(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`);l(e.id,{status:`hashing`});try{let t=await hs(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 fo(n,[...new Set(r.values())])}catch{i={}}let a=m.filter(e=>r.has(e.id)),o=0;await Promise.all(Array.from({length:Math.min(RS,a.length)},async()=>{for(;o<a.length;){if(p.signal.aborted)return;let s=a[o++],c=r.get(s.id);try{let r=i[c]??null;r?l(s.id,{status:`linking`,progress:1,resumed:!0}):(l(s.id,{status:`uploading`,progress:0}),r=await ao(n,s.file,{signal:p.signal,onProgress:(e,t)=>l(s.id,{progress:t?e/t:0})}),l(s.id,{status:`linking`,progress:1}));let a=await ts(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`)&&$o(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 VS(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function HS(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 VS(e.file.size)}}function US({item:e}){switch(e.status){case`done`:return(0,Z.jsx)($e,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,Z.jsx)(B,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,Z.jsx)(bt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function WS({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,Z.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:K(`h-full rounded-full transition-[width] duration-200`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function GS({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,Z.jsx)(Z.Fragment,{children:e.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(Eu,{children:[e.length,` file(s)`,r>0&&(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,Z.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(US,{item:e}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,Z.jsx)(`span`,{className:K(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:HS(e)}),!t&&e.status!==`done`&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(WS,{item:e})]},e.id))})]})})}function KS({items:e,running:t,onCancel:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,Z.jsx)(GS,{items:e,running:!0,onRemove:()=>{}}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function qS(e){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return jr(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var JS=`data/schema/file`,YS=`3.0`;function XS(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:qS(e),geotag:ih()}}function ZS(e,t,n={}){let r=_p(n.tags??[]),i=n.comment?.trim();return{schema:JS,schemaVersion:YS,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 QS=`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 $S({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${t}-comment`,children:`Comment`}),(0,Z.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:QS}),n&&e.tags.length+e.comment.trim().length>0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,Z.jsx)(DS,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var eC={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 tC(e){return/^(image|video)\//.test(e.type)}async function nC(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
|
|
10
|
+
</head><body>${t}</body></html>`;return{url:URL.createObjectURL(new Blob([i],{type:`text/html;charset=utf-8`})),remoteCount:r}}finally{Ss.removeHook(`afterSanitizeAttributes`)}}function Th(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function Eh({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=vo(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],s=typeof a.bodyHtml==`string`&&a.bodyHtml.trim()?a.bodyHtml:null,c=typeof a.body==`string`?a.body:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!s),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(0),[_,v]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!s||d)return;let e=!1,n=[],i=o.filter(e=>e.contentId&&e.url);return Promise.all(i.slice(0,20).map(async e=>{try{let{blob:n}=await r(t.id,{url:e.url}),i=await Th(n);return[String(e.contentId).replace(/^<|>$/g,``),i]}catch{return null}})).then(t=>{if(e)return;let r=new Map(t.filter(Boolean)),{url:i,remoteCount:a}=wh(s,r,p);n.push(i),u(i),g(a)}).catch(t=>{e||v(String(t instanceof Error?t.message:t))}),()=>{e=!0,n.forEach(e=>URL.revokeObjectURL(e)),u(null)}},[e,t.id,s,d,p]);let b=typeof a.date==`string`?new Date(a.date).toLocaleString():null,x=o.filter(e=>!e.isInline||!e.contentId),S=async e=>{if(e.url)try{await i(t.id,e.filename||`attachment`,{url:e.url})}catch(e){v(e instanceof Error?e.message:String(e))}};return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 ${n}`,children:[(0,Z.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-3 text-sm`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,Z.jsx)(`div`,{className:`text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,xh(a.from)]}),Sh(a.to)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Sh(a.to)]}),Sh(a.cc)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Sh(a.cc)]}),b&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:b})]}),s&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap justify-end gap-2`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>f(!d),children:[d?(0,Z.jsx)(j,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(wn,{className:`mr-1.5 h-3.5 w-3.5`}),d?`HTML`:`Plain text`]}),!d&&h>0&&(0,Z.jsxs)(J,{size:`sm`,variant:p?`secondary`:`outline`,onClick:()=>m(!p),title:`Remote images can reveal your IP/read status to the sender`,children:[p?(0,Z.jsx)(V,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(y,{className:`mr-1.5 h-3.5 w-3.5`}),p?`Hide remote images`:`Show remote images (${h})`]})]})]})}),_&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:_}),!d&&s?l?(0,Z.jsx)(`iframe`,{src:l,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,Z.jsx)(`pre`,{className:`min-h-[12rem] flex-1 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-sm`,children:c||`(empty body)`}),x.length>0&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,x.length,`)`]}),x.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(wn,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:Ch(e.size)})]}),e.url&&(0,Z.jsxs)(`button`,{onClick:()=>S(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Z.jsx)(er,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}var Dh={email:Cn,phone:be,sms:Me,chat:Me,slack:Me,matrix:Me,web:oe,url:oe},Oh={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},kh=e=>Array.isArray(e)?e:[];function Ah(e,t){return t?e===`email`?`mailto:${t}`:e===`phone`||e===`sms`?`tel:${t.replace(/[^\d+]/g,``)}`:/^https?:\/\//i.test(t)?t:null:null}function jh({title:e,count:t,children:n}){return t===0?null:(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`space-y-1`,children:n})]})}function Mh({icon:e,primary:t,children:n,title:r}){return(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 rounded-md border bg-card px-2.5 py-1.5 text-sm`,title:r,children:[(0,Z.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,Z.jsx)(Ln,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function Nh({document:e,className:t}){let n=e.data??{},r=kh(n.identifiers),i=kh(n.channels),a=kh(n.organizations),o=kh(n.links),s=kh(n.tags),c=String(n.displayName||``).trim(),l=io(e.schema,oo),u=String(n.primaryEmail||``).trim(),d=n.name&&typeof n.name==`object`?n.name:{},f=[d.prefix,d.given,d.middle,d.family,d.suffix].map(e=>String(e||``).trim()).filter(Boolean).join(` `),p=i.some(e=>e.kind===`email`&&e.value===u);return(0,Z.jsxs)(`div`,{className:K(`space-y-4`,t),children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:Oh[l]||l}),f&&f!==c&&(0,Z.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,Z.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,Z.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,Z.jsx)(jh,{title:`Primary email`,count:1,children:(0,Z.jsx)(Mh,{icon:Cn,primary:!0,children:(0,Z.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,Z.jsx)(jh,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=Ah(n,r),a=Dh[n]||Me;return(0,Z.jsxs)(Mh,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,Z.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,Z.jsx)(jh,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,Z.jsxs)(Mh,{icon:In,primary:e.primary,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,Z.jsx)(jh,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,Z.jsxs)(Mh,{icon:st,children:[e.name,e.role&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,Z.jsx)(jh,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,Z.jsxs)(Mh,{icon:Xt,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function Ph({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function Fh(e){let t=e.schema;if(t===`data/schema/note`)return Jm;if(t===`data/schema/drawing`)return Vm;if(t===`data/schema/task`)return bh;if(t===`data/schema/message/email`)return Eh;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return Nh;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return ro(t)?Ym:Zm(t)?Xm:$m}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(so(n,mo(e))){case`image`:return Vm;case`audio`:return Hm;case`video`:return Um;case`pdf`:return Wm;case`markdown`:return Jm;case`text`:return qm;default:return Ph}}function Ih({workspaceId:e,document:t,className:n}){let r=Fh(t);return r?(0,Z.jsx)(r,{workspaceId:e,document:t,className:n}):(0,Z.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var Lh=15,Rh=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function zh(e){return String(e).padStart(2,`0`)}function Bh(e){let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(e||``);return t?{date:`${t[1]}-${t[2]}-${t[3]}`,time:`${t[4]}:${t[5]}`}:null}function Vh(e){return`${e.getFullYear()}-${zh(e.getMonth()+1)}-${zh(e.getDate())}`}function Hh(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function Uh(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/Lh)*Lh),`${zh(e.getHours())}:${zh(e.getMinutes())}`}function Wh(){let e=[];for(let t=0;t<1440;t+=Lh)e.push(`${zh(Math.floor(t/60))}:${zh(t%60)}`);return e}var Gh=Wh();function Kh(e){let t=new Date(e.getFullYear(),e.getMonth(),1),n=(t.getDay()+6)%7,r=new Date(t);return r.setDate(t.getDate()-n),Array.from({length:42},(e,t)=>{let n=new Date(r);return n.setDate(r.getDate()+t),n})}function qh(e){let[t,n]=e.split(`:`).map(Number);return new Date(2e3,0,1,t,n).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function Jh(e){let t=Bh(e);if(!t)return``;let[n,r,i]=t.date.split(`-`).map(Number),[a,o]=t.time.split(`:`).map(Number);return new Date(n,r-1,i,a,o).toLocaleString(void 0,{weekday:`short`,day:`numeric`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}function Yh({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,X.useState)(!1),u=(0,X.useRef)(null),d=Bh(e),f=d?Jh(e):``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:K(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,Z.jsx)(pe,{className:K(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Z.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(G,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Z.jsx)(Xh,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Xh({anchorRef:e,value:t,onChange:n,onClose:r}){let i=Bh(t),a=i?.date??Vh(new Date),o=i?.time??null,[s,c]=(0,X.useState)(()=>{let e=Hh(a);return new Date(e.getFullYear(),e.getMonth(),1)}),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(null);(0,X.useLayoutEffect)(()=>{let t=l.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));f({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,X.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let p=(0,X.useMemo)(()=>!o||Gh.includes(o)?Gh:[...Gh,o].sort(),[o]);(0,X.useEffect)(()=>{let e=u.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let m=(e,t)=>n(`${e}T${t}`),h=e=>{let t=o??Uh();m(Vh(e),t),e.getMonth()!==s.getMonth()&&c(new Date(e.getFullYear(),e.getMonth(),1))},g=e=>{m(a,e),r()},_=e=>{let t=new Date;t.setDate(t.getDate()+e);let n=o??Uh();m(Vh(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},v=Vh(new Date),y=Kh(s);return(0,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Z.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},children:[(0,Z.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(se,{className:`h-4 w-4`})}),(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:Rh.map(e=>(0,Z.jsx)(`span`,{children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:y.map(e=>{let t=Vh(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>h(e),"aria-pressed":r,className:K(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===v&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,Z.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,Z.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Z.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&m(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,Z.jsx)(`div`,{ref:u,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:p.map(e=>{let t=e===o;return(0,Z.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>g(e),"aria-pressed":t,className:K(`block w-full rounded px-2 py-1 text-left text-xs tabular-nums transition-colors`,t?`bg-primary text-primary-foreground`:`hover:bg-muted`),children:qh(e)},e)})})]})]})]}),document.body)}var Zh={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Qh=`flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`,$h=`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 eg({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-title`,children:`Title`}),(0,Z.jsx)(q,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-desc`,children:`Description`}),(0,Z.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:$h})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-due`,children:`Due`}),(0,Z.jsx)(Yh,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Z.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Qh,children:[(0,Z.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Z.jsx)(`option`,{value:e,children:Zh[e]},e))]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${u}-status`,children:`Status`}),(0,Z.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Qh,children:oh.map(e=>(0,Z.jsx)(`option`,{value:e,children:sh[e]},e))})]})]})}var tg=`3.0`,ng=[`person`,`organization`,`service`,`bot`],rg={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},ig=[`email`,`phone`,`sms`,`chat`,`web`],ag=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function og(e){let t=e.primaryEmail.trim().toLowerCase(),n=e.channels.map(e=>({...e,kind:e.kind.trim(),value:e.value.trim(),label:e.label?.trim()||void 0})).filter(e=>e.kind&&e.value);if(t&&!n.some(e=>e.kind===`email`&&e.value===t)){for(let e of n)e.kind===`email`&&(e.primary=!1);n.push({kind:`email`,value:t,label:void 0,primary:!0})}let r=e.given.trim(),i=e.family.trim();return{displayName:e.displayName.trim(),...t?{primaryEmail:t}:{},...r||i?{name:{...r?{given:r}:{},...i?{family:i}:{}}}:{},channels:n,identifiers:e.identifiers.map(e=>({...e,type:e.type.trim(),identifier:e.identifier.trim(),provider:e.provider?.trim()||void 0})).filter(e=>e.type&&e.identifier),organizations:e.organizations.map(({identityId:e,...t})=>({...t,name:t.name.trim(),role:t.role?.trim()||void 0,...e?{metadata:{identityId:e}}:{}})).filter(e=>e.name)}}function sg(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=io(String(e?.schema||``),oo);return{displayName:String(t.displayName||``),type:ng.includes(i)?i:`person`,primaryEmail:String(t.primaryEmail||``),given:String(n.given||``),family:String(n.family||``),channels:r(t.channels),identifiers:r(t.identifiers),organizations:r(t.organizations).map(e=>({name:String(e.name||``),role:e.role?String(e.role):void 0,identityId:Number(e.metadata?.identityId)||void 0}))}}async function cg(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await Xi(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function lg(e){let[t,n]=(0,X.useState)(e?.displayName??``),[r,i]=(0,X.useState)(e?.type??`person`),[a,o]=(0,X.useState)(e?.primaryEmail??``),[s,c]=(0,X.useState)(e?.given??``),[l,u]=(0,X.useState)(e?.family??``),[d,f]=(0,X.useState)(e?.channels??[]),[p,m]=(0,X.useState)(e?.identifiers??[]),[h,g]=(0,X.useState)(e?.organizations??[]),[_,v]=(0,X.useState)([]),[y,b]=(0,X.useState)(``),[x,S]=(0,X.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${oo}/${C.type}`,schemaVersion:tg,data:og(C),...t?{comment:t}:{},metadata:{features:_p(_)}},r=await ts(e,[n]);return await cg(e,r[0],h),r}finally{S(!1)}}return{displayName:t,setDisplayName:n,type:r,setType:i,primaryEmail:a,setPrimaryEmail:o,given:s,setGiven:c,family:l,setFamily:u,channels:d,setChannels:f,identifiers:p,setIdentifiers:m,organizations:h,setOrganizations:g,tags:_,setTags:v,comment:y,setComment:b,values:C,saving:x,canSave:T,emailValid:w,save:E}}var ug=`h-9 shrink-0 rounded-md border border-input bg-transparent px-2 text-sm shadow-elevation-1 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`;function dg({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(Eu,{children:e}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(H,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},i))})]})}function fg(e,t){let n=e[t].kind,r=e[t].primary;return e.map((e,i)=>e.kind===n?{...e,primary:!r&&i===t}:e)}function pg(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Va(e,`organization`);t||n(r.map(e=>({id:e.id,name:bo(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function mg({idPrefix:e,workspaceName:t,displayName:n,setDisplayName:r,type:i,setType:a,primaryEmail:o,setPrimaryEmail:s,given:c,setGiven:l,family:u,setFamily:d,channels:f,setChannels:p,identifiers:m,setIdentifiers:h,organizations:g,setOrganizations:_,emailValid:v=!0}){let y=pg(t);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Z.jsx)(q,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-type`,children:`Type`}),(0,Z.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:K(ug,`w-full`),children:ng.map(e=>(0,Z.jsx)(`option`,{value:e,children:rg[e]},e))})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Z.jsx)(q,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-given`,children:`Given name`}),(0,Z.jsx)(q,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${e}-family`,children:`Family name`}),(0,Z.jsx)(q,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Z.jsx)(dg,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:K(ug,`w-24`),children:[ig.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!ig.includes(e.kind)&&(0,Z.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Z.jsx)(q,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(fg(f,f.indexOf(e))),className:K(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,Z.jsx)(Ln,{className:K(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Z.jsx)(dg,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:K(ug,`w-24`),children:[ag.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!ag.includes(e.type)&&(0,Z.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Z.jsx)(q,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,Z.jsx)(dg,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[y.length>0?(0,Z.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:K(ug,`min-w-0 flex-1`),children:[(0,Z.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Z.jsx)(q,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(q,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function hg(e){return e===`data/schema/note`||e===`data/schema/link`||e===`data/schema/tab`||e===`data/schema/task`||e===`data/schema/drawing`||e===`data/schema/identity`||e.startsWith(`data/schema/identity/`)}function gg(e){return hg(e.schema)||xo(e)}function _g(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function vg(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await Ta(e,t,{resolve:!1}),a=new Set(i.outgoing.filter(e=>e.p===`member-of`).map(e=>e.to));for(let n of r)a.has(n)||await Xi(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await Xr(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function yg({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=to(),a=hg(e.schema),o=e.schema===no,s=xo(e),c=Do(e)??`markdown`,l=s&&ho(e),u=e.schema===uo,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=_g(e.schema),[m,h]=(0,X.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,X.useState)(String(e.data?.[p]??``)),[v,y]=(0,X.useState)(String(e.data?.content??``)),[b,x]=(0,X.useState)(String(e.data?.description??``)),[S,C]=(0,X.useState)(e.data?.status??`pending`),[w,T]=(0,X.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,X.useState)(e.data?.dueDate?uh(String(e.data.dueDate)):fh()),O=lg(sg(e)),[k,A]=(0,X.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[M,N]=(0,X.useState)(j),P=JSON.stringify(M??null)!==JSON.stringify(j??null),F=e.features??e.metadata?.features,[I,ee]=(0,X.useState)(vp(F).length?vp(F):e.data?.tags??[]),te=Oo(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:wo,version:e.checksumArray?.[0]??null}),[ne,re]=(0,X.useState)(null),ie=`${e.id}:${e.checksumArray?.[0]??``}`;s&&te.text!=null&&ne!==ie&&(re(ie),y(te.text));let[L,R]=(0,X.useState)([]),[ae,oe]=(0,X.useState)(!1),{replicating:se,mirror:ce}=ea(e);(0,X.useEffect)(()=>{let e=!1;return jr(t).then(t=>{e||R(t)}).catch(()=>{}),()=>{e=!0}},[t]);let z=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),le=!ae&&(s?!l&&te.text!=null&&!te.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?g.trim().length>0:o?v.trim().length>0:z:!0),ue=async()=>{oe(!0);try{if(s){await ko(t,e,v,{comment:k.trim(),...P?{metadata:{geo:M}}:{}}),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n();return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:k.trim()};if(d){let{type:t,...n}=e.data??{};i.schema=`${oo}/${O.values.type}`,i.data={...n,...og(O.values)},i.metadata={features:_p(I)}}else if(u)i.data={...e.data,...ph({title:g,description:b,status:S,priority:w,due:E})},i.metadata={features:_p(I)};else if(a){let t=I.map(e=>e.trim()).filter(Boolean),n;o?n={...g.trim()?{title:g.trim()}:{},content:v}:(n={...e.data},f&&(n[f]=m.trim()),g.trim()?n[p]=g.trim():delete n[p],n.tags=t),i.data=n,i.metadata={features:_p(I)}}P&&(i.metadata={...i.metadata??{},geo:M}),await Ui(t,i),d&&await vg(t,e.id,O.values.organizations),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{oe(!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`edit-url`,children:`URL`}),(0,Z.jsx)(q,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!z&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Z.jsx)(mg,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Z.jsx)(eg,{idPrefix:`edit-todo`,title:g,setTitle:_,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`edit-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-title`,value:g,onChange:e=>_(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Body`}),l?(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&te.error?(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:te.error}):s&&te.text==null?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Z.jsx)(To,{kind:o?`markdown`:c,value:v,onChange:y,placeholder:o?`Write your note…`:void 0})]}),a&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:I,onChange:ee,suggestions:L})]}),(0,Z.jsx)(Ap,{value:M,onChange:N}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`edit-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`edit-comment`,value:k,onChange:e=>A(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,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 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:n,disabled:ae,children:`Cancel`}),(0,Z.jsx)(J,{size:`sm`,onClick:ue,disabled:!le,children:ae?se?`Replicating to ${ce.label}…`:`Saving…`:`Save changes`})]})]})}var bg=(0,X.createContext)(null),xg={open:()=>{},close:()=>{}};function Sg(){return(0,X.useContext)(bg)??xg}var Cg=`main`,wg=(0,X.createContext)(null);function Tg(){return(0,X.useContext)(wg)}function Eg({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=Sg(),o=Bp(),s=Tg(),c=n===`out`?e.to:e.from,l=e.document??null,u=!e.meta||e.meta.src===`doc`;return(0,Z.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,Z.jsx)(qn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Z.jsx)(Bt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Z.jsx)(ep,{document:l,size:3.5}):null,l?(0,Z.jsx)(`button`,{type:`button`,onClick:()=>s?o.open(l,t):a(l,t),className:`min-w-0 flex-1 truncate text-left hover:underline`,title:`Open document ${c}`,children:bo(l).title}):(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Z.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!u&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),u&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function Dg({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=to(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),m=(0,X.useCallback)(async()=>{try{let n=await Ta(t,e.id);a(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[t,e.id]),h=`${t}:${e.id}`,[g,_]=(0,X.useState)(h);h!==g&&(_(h),a(null),s(null)),(0,X.useEffect)(()=>{async function e(){await m()}return e(),window.addEventListener(Zp,e),()=>window.removeEventListener(Zp,e)},[m]);let v=async(i,a)=>{let o=a===`out`?i.to:i.from;if(o==null)return;let s=`${a}:${i.p}:${o}`;p(s);try{await Xr(t,e.id,i.p,o,a),n(`Relation removed`),Qp()}catch(e){r(e instanceof Error?e.message:`Failed to remove relation`)}finally{p(null)}},y=[{dir:`out`,title:`Points at`,hint:`this document as the subject`,entries:i?.outgoing??[]},{dir:`in`,title:`Pointed at by`,hint:`this document as the object`,entries:i?.incoming??[]}];return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Z.jsx)(H,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?y.every(e=>e.entries.length===0)?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Z.jsx)(`div`,{className:`space-y-4`,children:y.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,Z.jsx)(Eg,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void v(n,e)},i)})]},n))]},e))}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),c&&(0,Z.jsx)(pp,{onClose:()=>{u||l(!1)},children:(0,Z.jsx)(dp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,tabs:[`relations`],fixedWorkspaceName:t,documentCount:1,saving:u,relationPredicates:i?.predicates,relationExcludeIds:new Set([e.id]),onClose:()=>l(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:i,direction:a,targetIds:o})=>{d(!0);try{await Xi(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),Qp()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var Og=(0,X.lazy)(()=>m(()=>import(`./SketchEditor-BbXQRr1e.js`),__vite__mapDeps([8,3,4,1,9,10,11,12,13,14,15,16,17,18,19,20]))),kg=(0,X.lazy)(()=>m(()=>import(`./TextDocumentEditor-BU0qu4aP.js`),__vite__mapDeps([21,3,4,9,11,10,12,13,22,1,19]))),Ag={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},jg={reply:F,replyAll:M,forward:ie};function Mg({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Eo()!=null,{showErrorToast:a}=to(),[o,s]=(0,X.useState)(null),c=e.schema===`data/schema/message/email`,l=!i&&(c||[`slack`,`whatsapp`].includes(String(e.data?.platform))),u=c?[`reply`,`replyAll`,`forward`]:[`reply`],d=e=>s(t=>t===e?null:e),f=!i,[p,m]=(0,X.useState)(n&&gg(e)),h=e.schema===lo,[g,_]=(0,X.useState)(!1),v=e.schema===`data/schema/note`||xo(e),[y,b]=(0,X.useState)(!1),x=`${e.id}:${n}`,[S,C]=(0,X.useState)(x);return x!==S&&(C(x),m(n&&gg(e))),p&&f?(0,Z.jsx)(yg,{document:e,workspaceId:t,onClose:()=>{m(!1),r?.()}}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[f&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[l&&u.map(e=>{let t=jg[e];return(0,Z.jsxs)(J,{size:`sm`,variant:o===e?`secondary`:`outline`,onClick:()=>d(e),children:[(0,Z.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),Ag[e]]},e)}),e.schema===`data/schema/file`&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Zr(t,e.id,mo(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Z.jsx)(er,{className:`mr-1 h-3 w-3`}),` Download`]}),h&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Z.jsx)(rt,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),v&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Z.jsx)(T,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(!0),children:[(0,Z.jsx)(Fe,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),g&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(Og,{doc:e,workspaceName:t,onSaved:()=>{_(!1),r?.()},onClose:()=>_(!1),onDetails:()=>{_(!1),m(!0)}})}),y&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Z.jsx)(kg,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),m(!0)}})}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:[(0,Z.jsx)(Ih,{workspaceId:t,document:e}),o&&l&&(0,Z.jsx)(vm,{workspaceId:t,replyToDocumentId:Number(e.id),mode:o,originalSubject:c&&typeof e.data?.subject==`string`?e.data.subject:void 0,onClose:()=>s(null)},`${e.id}:${o}`)]}),e.comment?.trim()&&(0,Z.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Z.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var Ng=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,Pg=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function Fg({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Z.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,Pg(n.exposureTime)),n&&i(`ISO`,Number.isFinite(n.iso)?n.iso:null),n&&i(`Focal length`,Number.isFinite(n.focalLength)?`${n.focalLength} mm`:null),n&&i(`Captured`,Ng(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Z.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function Ig({document:e}){let t=e.metadata;return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:Ng(e.createdAt)})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:Ng(e.updatedAt)})]})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Z.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Z.jsx)(Fg,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=Bg(e.url);return(0,Z.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Z.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),r&&(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Z.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function Lg({document:e}){let{showSuccessToast:t,showErrorToast:n}=to(),r=JSON.stringify(e,null,2);return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Z.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function Rg({document:e,workspaceId:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,X.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,X.useEffect)(()=>{let n=!1;return qr(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Z.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Z.jsx)(Dg,{document:e,workspaceId:t})]}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function zg(e){return e===`stored`?wt:e===`workspace-file`?hr:e===`imap`?Cn:e===`readonly`?oe:fn}function Bg(e){let t=e.match(/^([a-z][a-z0-9+.-]*):\/\/([^/]*)\/?(.*)$/i);return t?{backend:`${t[1]}://${t[2]}`,key:t[3]}:{backend:e,key:``}}function Vg({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=to(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(!1),_=`${t}:${e.id}`,[v,y]=(0,X.useState)(_);_!==v&&(y(_),o(null),c(null),f(null));let b=()=>{Br(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,X.useEffect)(()=>{let n=!1;return Br(t,e.id).then(e=>{n||o(e)}).catch(e=>{n||c(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[_]);let x=async(a,o)=>{u(a),f(null);try{let i=await Mr(t,[e.id],{urls:[a],...o===void 0?{}:{keepDocument:o}}),s=i.successful[0];if(!s)throw Error(i.failed[0]?.reason||`Destroy failed`);s.docDeleted?r(`Removed from backend; document removed from index`):s.deleted.includes(a)?r(`Removed from backend`):r(`Reference dropped (backend is read-only)`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n?.(),b()}catch(e){i(e instanceof Error?e.message:String(e))}finally{u(null)}},S=async(a,o,s)=>{g(!0);try{let i=await Pi(t,[e.id],{to:a,mode:o,keepDocument:s.keepDocument,folder:s.folder,filename:s.filename,onConflict:s.onConflict}),c=i.successful[0];if(!c)throw Error(i.failed[0]?.reason||`Transfer failed`);let l=c.transfers?.flatMap(e=>e.state===`unchanged`?[]:[e.backend])??[],u=a.join(`, `);o===`delete`?r(`Deleted from ${u}`):l.length===0?r(`Nothing to do — already on ${u}`):r(`${o===`move`?`Moved to`:`Copied to`} ${l.join(`, `)}${c.transfers?.some(e=>e.state===`pending`)?` (pending sync)`:``}`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),m(null),n?.(),b()}catch(e){i(e instanceof Error?e.message:String(e))}finally{g(!1)}},C=e=>{if((a?.length??0)<=1){f(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&x(e.url)};if(s)return(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let w=a.length===0,T=mo(e);return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(wt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Z.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),w?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,Z.jsx)(qn,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=zg(n.kind),{backend:a,key:o}=Bg(n.url),s=l===n.url;return(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,Z.jsx)(`button`,{onClick:()=>Zr(t,e.id,T||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,Z.jsx)(er,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{onClick:()=>C(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),d===n.url&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Z.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(J,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!1),children:`Also remove index entry`}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>f(null),children:`Cancel`})]})]})]},n.url)}),p&&(0,yf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(Ip,{workspaceId:t,documentCount:1,initialMode:p,defaultFilename:T,saving:h,onConfirm:S,onClose:()=>{h||m(null)}})}),window.document.body)]})}function Hg(e){let t=e.metadata?.geo,n=t?.lat,r=t?.lon;if(n==null||r==null||n===``||r===``)return null;let i=Number(n),a=Number(r);return!Number.isFinite(i)||!Number.isFinite(a)||i===0&&a===0?null:{lat:i,lon:a}}function Ug(e,t,n){let r=!1;for(let i=0,a=n.length-1;i<n.length;a=i++){let o=n[i].lat,s=n[i].lon,c=n[a].lat,l=n[a].lon;o>e!=c>e&&t<(l-s)*(e-o)/(c-o)+s&&(r=!r)}return r}function Wg(e,t,n){if(n.kind===`rect`){let r=n.bbox;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLon&&t<=r.maxLon}return n.points.length>=3&&Ug(e,t,n.points)}function Gg(e,t,n=!1){let r=Hg(e);return r?Wg(r.lat,r.lon,t):n}var Kg=(0,X.lazy)(()=>m(()=>import(`./LocationTab-ARqmeXmv.js`),__vite__mapDeps([23,3,4,24,25]))),qg=[{id:`view`,label:`View`,icon:Vt},{id:`location`,label:`Location`,icon:yt},{id:`metadata`,label:`Metadata`,icon:A},{id:`json`,label:`JSON`,icon:je},{id:`synapses`,label:`Synapses`,icon:_n},{id:`backends`,label:`Backends`,icon:wt}];function Jg({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1}){let s=Eo()!=null,c=Hg(e),l=qg.filter(e=>(e.id!==`location`||c!==null)&&(!s||![`synapses`,`backends`].includes(e.id))),[u,d]=(0,X.useState)(n),f=`${e.id}:${n}`,[p,m]=(0,X.useState)(f);f!==p&&(m(f),d(n));let h=l.some(e=>e.id===u)?u:`view`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[(0,Z.jsx)(cm,{tabs:l,active:h,onChange:d,className:`shrink-0 px-2`,iconOnly:o}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-4`,children:[h===`view`&&(0,Z.jsx)(Mg,{document:e,workspaceId:t,initialEdit:r&&!s,onChanged:i}),h===`location`&&c&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Z.jsx)(Kg,{lat:c.lat,lon:c.lon})}),h===`metadata`&&(0,Z.jsx)(Ig,{document:e,workspaceId:t}),h===`json`&&(0,Z.jsx)(Lg,{document:e,workspaceId:t}),h===`synapses`&&!s&&(0,Z.jsx)(Rg,{document:e,workspaceId:t}),h===`backends`&&!s&&(0,Z.jsx)(Vg,{document:e,workspaceId:t,onChanged:i})]})]})}function Yg(e,t){let[n,r]=(0,X.useState)(null),i=t?.id??null,[a,o]=(0,X.useState)(i);i!==a&&(o(i),r(null));let s=(0,X.useRef)(i);(0,X.useEffect)(()=>{s.current=i},[i]);let c=(0,X.useCallback)(()=>{!e||i==null||Sr(e,i).then(e=>{s.current===i&&e&&r(e)}).catch(()=>{})},[e,i]);return{document:n??t,refresh:c}}function Xg(e){let t=sm(),n=(0,X.useContext)(Rp),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,X.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Z.jsx)(Zg,{...e})}function Zg({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,X.useState)(!1),c=Io(),{document:l,refresh:u}=Yg(r,e);if(Sf(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,yf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:K(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,Z.jsxs)(`div`,{className:K(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-lg md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-lg`),onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:bo(l).title}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=yo(l);return e?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,Z.jsx)(gn,{className:`h-4 w-4`})}):null})(),(0,Z.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)($p.Provider,{value:()=>s(e=>!e),children:(0,Z.jsx)(Jg,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Qg={sortBy:`crud:created`,order:`desc`},$g={"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function e_(e){return $g[e]??e}function t_(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{let t=!1;return Wa(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,X.useMemo)(()=>[...new Set([`crud:created`,`crud:updated`,...t])].map(e=>({value:e,label:e_(e)})),[t])}function n_({workspaceId:e,value:t,onChange:n}){let r=t_(e);return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Z.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by timeline`,children:[!r.some(e=>e.value===t.sortBy)&&(0,Z.jsx)(`option`,{value:t.sortBy,children:e_(t.sortBy)}),r.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending (oldest first)`:`Descending (newest first)`,className:`flex h-7 w-7 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent hover:text-foreground touch-target`,children:t.order===`asc`?(0,Z.jsx)(Rn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(hn,{className:`h-3.5 w-3.5`})})]})}var r_={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},i_=e=>e*1e6;function a_(){try{let e=new Intl.Locale(navigator.language),t=(typeof e.getWeekInfo==`function`?e.getWeekInfo():e.weekInfo)?.firstDay;if(typeof t==`number`&&t>=1&&t<=7)return t}catch{}return 1}function o_(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function s_(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=o_(e);return r.setDate(r.getDate()-n),r}var c_=864e5;function l_(e){let t=a_(),n=o_(e),r=s_(e,t);return{today:n.getTime(),yesterday:n.getTime()-c_,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*c_,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function u_(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:i_(r_.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:i_(r_.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:i_(r_.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:i_(r_.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:i_(r_.lastWeek)};let n=new Date(e),r=n.getFullYear()*12+n.getMonth();if(r===t.month)return{key:`this-month`,label:`Earlier this month`,rank:i_(r_.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:i_(r_.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:i_(r_.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:i_(r_.year)+i}}function d_(e,t,n=`desc`,r=new Date){let i=l_(r),a=new Map;for(let n of e){let e=u_(t(n),i),r=a.get(e.key);r?r.items.push(n):a.set(e.key,{...e,items:[n]})}let o=[...a.values()].sort((e,t)=>n===`asc`?e.rank-t.rank:t.rank-e.rank),s=o.filter(e=>e.key===`unknown`);return s.length?[...o.filter(e=>e.key!==`unknown`),...s]:o}function f_({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,X.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map(e=>({schema:e.schema,schemaVersion:e.schemaVersion,data:e.data,metadata:e.metadata})),l=JSON.stringify(c,null,2),u=async()=>{try{await navigator.clipboard.writeText(l),a(`copied`),setTimeout(()=>a(`idle`),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e),a(`error`),setTimeout(()=>a(`idle`),2e3)}};return(0,yf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,Z.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,Z.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsx)(`div`,{className:`space-y-4`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,Z.jsxs)(J,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,Z.jsx)(Ve,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,Z.jsx)(`textarea`,{className:`w-full h-96 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&u()}},onFocus:e=>e.target.select()})]})}),(0,Z.jsx)(`div`,{className:`mt-8 pt-4 border-t flex justify-end`,children:(0,Z.jsx)(J,{onClick:o,children:`Close`})})]})})}),window.document.body)}function p_({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e.schema||!e.data){c(`Each document must have "schema" and "data" fields`);return}o(!0),await n(a)?(i(``),t()):c(`Failed to import documents`)}catch{c(`Invalid JSON format`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,yf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data containing documents to import`})]}),(0,Z.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,Z.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),className:`w-full h-64 p-3 border rounded-lg font-mono text-sm`,placeholder:`[{"schema": "data/schema/tab", "schemaVersion": "2.0", "data": {...}, "metadata": {...}}]`,disabled:a,autoFocus:!0})]}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,Z.jsx)(J,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,Z.jsx)(J,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function m_({document:e,open:t,onClose:n,onViewDetails:r,onEdit:i,onLink:a,onOpenToSide:o,onRemove:s,onDelete:c}){if(Sf(n,t),!t)return null;let l=bo(e),u=e=>()=>{n(),e()},d=`flex w-full items-center gap-3 rounded-xl border bg-card px-4 py-4 text-base font-medium transition-transform active:scale-[.98]`;return(0,yf.createPortal)((0,Z.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-background animate-in slide-in-from-bottom-10 fade-in duration-200`,onClick:n,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(ep,{document:e,chip:!0}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-base font-semibold`,children:l.title}),(0,Z.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,e.id,` · `,e.schema]})]}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,Z.jsx)(G,{className:`h-5 w-5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 px-4 pt-2`,style:{paddingBottom:`calc(var(--safe-bottom) + 1.25rem)`},onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`button`,{onClick:u(r),className:d,children:[(0,Z.jsx)(Vt,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` View details`]}),i&&(0,Z.jsxs)(`button`,{onClick:u(i),className:d,children:[(0,Z.jsx)(Fe,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Edit`]}),a&&(0,Z.jsxs)(`button`,{onClick:u(a),className:d,children:[(0,Z.jsx)(Gt,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Link to…`]}),o&&(0,Z.jsxs)(`button`,{onClick:u(o),className:d,children:[(0,Z.jsx)(ce,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Open to the side`]}),s&&(0,Z.jsxs)(`button`,{onClick:u(s),className:d,children:[(0,Z.jsx)(G,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),` Remove from context`]}),c&&(0,Z.jsxs)(`button`,{onClick:u(c),className:`${d} border-destructive/30 text-destructive`,children:[(0,Z.jsx)(lt,{className:`h-5 w-5 shrink-0`}),` Delete permanently`]}),(0,Z.jsx)(`button`,{onClick:n,className:`${d} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function h_({document:e}){let{replicating:t,label:n}=ea(e);return t?(0,Z.jsxs)(`span`,{role:`status`,className:`inline-flex shrink-0 items-center gap-1 rounded-full border bg-muted/60 px-2 py-0.5 text-[11px] font-normal text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),n]}):null}function g_({document:e,isSelected:t,workspaceId:n,onSelect:r,onRemoveDocument:i,onDeleteDocument:a,onLinkDocument:o,onOpenToSide:s,onRightClick:c,onDragStart:l}){let u=_f(),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),_=Eo()!=null,v=gg(e),{replicating:y}=ea(e),b=e.schema===`data/schema/tab`,x=b?e.data.url:null,S=bo(e),C=v_(e),w=C||b_(e),{blobUrl:T}=Lm(n??``,e.id,128,{enabled:w,blobFallback:C,version:e.checksumArray?.[0]??null}),E=t=>{l?.(t,e.id)},D=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),O=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),k=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(b&&x?window.open(x,`_blank`,`noopener,noreferrer`):(m(!1),f(!0)))},A=e=>{e.shiftKey&&e.preventDefault()},j=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),c?.(n,e.id)},M=e=>{e.stopPropagation(),m(!1),f(!0)},N=e=>{e.stopPropagation(),m(!0),f(!0)},P=t=>{t.stopPropagation(),i?.(e.id)},F=t=>{t.stopPropagation(),a?.(e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Gp,{className:`cursor-pointer transition-opacity ${y?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:k,onMouseDown:A,...u,onContextMenu:j,draggable:!0,onDragStart:E,children:[(0,Z.jsx)(qp,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:!!t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}})}),(0,Z.jsx)(qp,{className:`w-12`,children:T?(0,Z.jsx)(`img`,{src:T,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,Z.jsx)(ep,{document:e,chip:!0})}),(0,Z.jsx)(qp,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:S.title,children:S.title}),S.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(h_,{document:e})]}),S.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:S.subtitle,children:S.subtitle})]})}),(0,Z.jsx)(qp,{className:`hidden md:table-cell`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:S.schemaLabel})}),(0,Z.jsx)(qp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,Z.jsx)(qp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:O&&(0,Z.jsx)(`span`,{className:`font-mono`,title:`${O.algo} checksum`,children:O.hash})}),(0,Z.jsx)(qp,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:D(e.createdAt)}),(0,Z.jsxs)(qp,{children:[(0,Z.jsxs)(`div`,{className:`hidden items-center gap-1 md:flex`,children:[(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:M,title:`View document details`,children:(0,Z.jsx)(Vt,{className:`h-4 w-4`})}),v&&!_&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:N,title:`Edit document`,children:(0,Z.jsx)(Fe,{className:`h-4 w-4`})}),o&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:t=>{t.stopPropagation(),o(e.id)},title:`Link document to other paths`,children:(0,Z.jsx)(Gt,{className:`h-4 w-4`})}),s&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:t=>{t.stopPropagation(),s(e)},title:`Open to the side`,children:(0,Z.jsx)(ce,{className:`h-4 w-4`})}),i&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:P,title:`Remove document from context`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:F,title:`Delete document permanently`,className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,className:`md:hidden`,onClick:e=>{e.stopPropagation(),g(!0)},title:`Actions`,"aria-label":`Document actions`,children:(0,Z.jsx)(gt,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(m_,{document:e,open:h,onClose:()=>g(!1),onViewDetails:()=>{m(!1),f(!0)},onEdit:v&&!_?()=>{m(!0),f(!0)}:void 0,onLink:o?()=>o(e.id):void 0,onOpenToSide:s?()=>s(e):void 0,onRemove:i?()=>i(e.id):void 0,onDelete:a?()=>a(e.id):void 0}),(0,Z.jsx)(Xg,{document:e,isOpen:d,onClose:()=>f(!1),workspaceId:n,initialEdit:p})]})}function __({document:e,isSelected:t,workspaceId:n,onSelect:r,onRemoveDocument:i,onDeleteDocument:a,onLinkDocument:o,onOpenToSide:s,onRightClick:c,onDragStart:l}){let u=_f(),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(!1),_=Eo()!=null,v=e.schema===`data/schema/tab`,y=gg(e),{replicating:b}=ea(e),x=v?e.data.url:null,S=bo(e),C=v_(e),w=C||b_(e),{blobUrl:T,loading:E}=Lm(n??``,e.id,128,{enabled:w,blobFallback:C,version:e.checksumArray?.[0]??null}),D=t=>{l?.(t,e.id)},O=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),k=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),A=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(v&&x?window.open(x,`_blank`,`noopener,noreferrer`):(m(!1),f(!0)))},j=e=>{e.shiftKey&&e.preventDefault()},M=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),c?.(n,e.id)},N=e=>{e.stopPropagation(),m(!1),f(!0)},P=e=>{e.stopPropagation(),m(!0),f(!0)},F=t=>{t.stopPropagation(),i?.(e.id)},I=t=>{t.stopPropagation(),a?.(e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`border rounded-lg p-4 transition cursor-pointer ${b?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${v&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:A,onMouseDown:j,...u,onContextMenu:M,draggable:!0,onDragStart:D,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[w&&(0,Z.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:T?(0,Z.jsx)(`img`,{src:T,alt:S.title,loading:`lazy`,className:`h-full w-full object-cover`}):E?(0,Z.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(ep,{document:e})})}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,Z.jsx)(ep,{document:e,chip:!0}),(0,Z.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:S.title,children:S.title}),S.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(`span`,{className:`px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:S.schemaLabel}),(0,Z.jsx)(h_,{document:e})]}),S.subtitle&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:S.subtitle,children:S.subtitle}),S.preview&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:S.preview}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),k&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(Ne,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{className:`font-mono`,title:`${k.algo} checksum`,children:k.hash})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(_e,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{title:`Created: ${O(e.createdAt)}`,children:O(e.createdAt)})]})]})]}),(0,Z.jsxs)(`div`,{className:`hidden items-center gap-2 md:flex`,children:[(0,Z.jsx)(`button`,{onClick:N,className:`p-1 hover:bg-muted rounded-sm`,title:`View document details`,children:(0,Z.jsx)(Vt,{className:`h-4 w-4`})}),y&&!_&&(0,Z.jsx)(`button`,{onClick:P,className:`p-1 hover:bg-muted rounded-sm`,title:`Edit document`,children:(0,Z.jsx)(Fe,{className:`h-4 w-4`})}),o&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(e.id)},className:`p-1 hover:bg-muted rounded-sm`,title:`Link document to other paths`,children:(0,Z.jsx)(Gt,{className:`h-4 w-4`})}),s&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),s(e)},className:`p-1 hover:bg-muted rounded-sm`,title:`Open to the side`,children:(0,Z.jsx)(ce,{className:`h-4 w-4`})}),i&&(0,Z.jsx)(`button`,{onClick:F,className:`p-1 hover:bg-muted rounded-sm`,title:`Remove document from context (keep in database)`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(`button`,{onClick:I,className:`p-1 hover:bg-destructive hover:text-destructive-foreground rounded-sm text-destructive`,title:`Delete document permanently from database`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{onClick:e=>{e.stopPropagation(),g(!0)},className:`p-2 hover:bg-muted rounded-sm md:hidden`,title:`Actions`,"aria-label":`Document actions`,children:(0,Z.jsx)(gt,{className:`h-4 w-4`})})]})}),(0,Z.jsx)(m_,{document:e,open:h,onClose:()=>g(!1),onViewDetails:()=>{m(!1),f(!0)},onEdit:y&&!_?()=>{m(!0),f(!0)}:void 0,onLink:o?()=>o(e.id):void 0,onOpenToSide:s?()=>s(e):void 0,onRemove:i?()=>i(e.id):void 0,onDelete:a?()=>a(e.id):void 0}),(0,Z.jsx)(Xg,{document:e,isOpen:d,onClose:()=>f(!1),workspaceId:n,initialEdit:p})]})}function v_(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function y_(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function b_(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function x_({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=go(e,t),[a,o]=(0,X.useState)(!1);return i||a?(0,Z.jsx)(Z.Fragment,{children:n}):r?(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,Z.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,Z.jsx)(Oe,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function S_({document:e,workspaceId:t,markdown:n}){let r=(0,X.useRef)(null),[i,a]=(0,X.useState)(()=>typeof IntersectionObserver>`u`);(0,X.useEffect)(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(a(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let{text:o,loading:s,error:c}=Oo(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,Z.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,Z.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,Z.jsx)(Km,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,Z.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,Z.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,Z.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,Z.jsx)(ep,{document:e,size:10,chip:!0}),i&&s&&(0,Z.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function C_({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onDragStart:o}){let s=_f(),[c,l]=(0,X.useState)(!1),u=e.schema===`data/schema/tab`,d=u?e.data.url:null,f=v_(e),p=y_(e),m=f||b_(e),h=bo(e),g=so(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||mo(e)),_=e.schema===`data/schema/file`&&(g===`markdown`||g===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,v=!m&&e.schema!==`data/schema/file`&&!!(h.preview||h.subtitle),{replicating:y}=ea(e),{blobUrl:b,loading:x}=Lm(n??``,e.id,768,{enabled:m,blobFallback:f,version:e.checksumArray?.[0]??null}),S=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&r(e.id,!i||!t,i),i||(u&&d?window.open(d,`_blank`,`noopener,noreferrer`):l(!0))},C=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-lg border transition cursor-pointer hover:shadow-elevation-2 ${y?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:S,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...s,onContextMenu:C,draggable:!0,onDragStart:t=>o?.(t,e.id),title:h.title,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`absolute left-2 top-2 z-10 h-4 w-4 cursor-pointer accent-primary ${t?``:`reveal-on-hover`}`,checked:t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}}),(0,Z.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${m&&b||v||_&&n||p&&n?``:`aspect-square`}`,children:[m&&x&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),m&&b?(0,Z.jsx)(`img`,{src:b,alt:h.title,loading:`lazy`,className:`block h-auto w-full`}):p&&n?(0,Z.jsx)(x_,{workspaceId:n,documentId:e.id,fallback:(0,Z.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,Z.jsx)(ep,{document:e,size:10,chip:!0})})}):_&&n?(0,Z.jsx)(S_,{document:e,workspaceId:n,markdown:g===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):v?(0,Z.jsxs)(`div`,{className:`flex min-h-28 w-full flex-col gap-1.5 overflow-hidden bg-card p-3 pt-7 text-left`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(ep,{document:e}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:h.schemaLabel})]}),(0,Z.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:h.title}),h.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:h.subtitle}),(0,Z.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:h.preview})]}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(ep,{document:e,size:10,chip:!0})}),i&&(0,Z.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`absolute right-2 top-2 rounded-sm bg-scrim p-1 text-scrim-foreground reveal-on-hover`,title:`Open to the side`,children:(0,Z.jsx)(ce,{className:`h-3.5 w-3.5`})})]}),!v&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:h.title,children:h.title}),h.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,Z.jsx)(Xg,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function w_(e,t,n,r){let[i,a]=(0,X.useState)(!1),o=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:i,onDragOver:e=>{!t||!o(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,i||a(!0))},onDragLeave:()=>a(!1),onDrop:async i=>{if(a(!1),!t||!o(i))return;i.preventDefault(),i.stopPropagation();let s=null;try{s=JSON.parse(i.dataTransfer.getData(`application/json`))}catch{s=null}if(!(s?.type!==`document`||!Array.isArray(s.documentIds)||s.documentIds.length===0))try{await t(e.path,s.documentIds,{move:!1,sourcePath:s.sourcePath??n,sourceTreeName:s.sourceTreeName??r})}catch{}}}}function T_({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,Z.jsx)(O,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,Z.jsx)(ge,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var E_=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function D_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=w_(e,n,r,i);return(0,Z.jsxs)(`button`,{type:`button`,title:E_(e),onClick:()=>t?.(e.path),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,className:`folder-surface group flex min-w-0 max-w-full items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm transition-colors hover:bg-accent ${a.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,Z.jsx)(T_,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,Z.jsx)(O,{className:`hidden h-4 w-4 group-hover:block`}):(0,Z.jsx)(Ae,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function O_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=w_(e,n,r,i),o=e.color?{color:e.color}:void 0;return(0,Z.jsxs)(`button`,{type:`button`,title:E_(e),onClick:()=>t?.(e.path),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-lg border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${a.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,Z.jsx)(O,{className:`h-10 w-10`,strokeWidth:1.5}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(ge,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:o}),(0,Z.jsx)(Ae,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:o})]})}),(0,Z.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function k_({folders:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-4 grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(O_,{folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i},e.path))})}function A_({folders:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(D_,{folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i},e.path))})}function j_({folder:e,onOpen:t,onPasteDocuments:n,contextPath:r,treeName:i}){let a=w_(e,n,r,i);return(0,Z.jsxs)(Gp,{className:`cursor-pointer ${a.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:e=>e.stopPropagation(),onDragOver:a.onDragOver,onDragLeave:a.onDragLeave,onDrop:a.onDrop,title:E_(e),children:[(0,Z.jsx)(qp,{className:`w-10`}),(0,Z.jsx)(qp,{className:`w-12`,children:(0,Z.jsx)(T_,{folder:e})}),(0,Z.jsx)(qp,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,Z.jsx)(qp,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,Z.jsx)(qp,{className:`hidden lg:table-cell`}),(0,Z.jsx)(qp,{className:`hidden lg:table-cell`}),(0,Z.jsx)(qp,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,Z.jsx)(qp,{className:`w-12 md:w-auto`})]})}function M_({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,Z.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-1 mb-2 flex items-center gap-2 bg-background/95 px-1 py-1.5 backdrop-blur-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 cursor-pointer accent-primary ${r||i?``:`reveal-on-hover`}`,checked:r,ref:e=>{e&&(e.indeterminate=i&&!r)},onChange:e=>o(e.target.checked),title:`Select everything in "${e}"`,onClick:e=>e.stopPropagation()}),(0,Z.jsxs)(`button`,{type:`button`,onClick:a,"aria-expanded":!n,className:`flex min-w-0 items-center gap-1.5 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,Z.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function N_({documents:e,isLoading:t,contextPath:n,treeName:r,workspaceId:i,totalCount:a,onRemoveDocument:o,onDeleteDocument:s,onDestroyDocument:c,onRemoveDocuments:l,onDeleteDocuments:u,onDestroyDocuments:d,onCopyDocuments:f,onCutDocuments:p,onPasteDocuments:m,onImportDocuments:h,onSelectionChange:g,pastedDocumentIds:_,viewMode:v=`card`,allowViewToggle:y=!1,activeContextUrl:x,currentContextUrl:S,currentPage:C=1,pageSize:T=50,onPageChange:E,onPageSizeChange:D,onPurgeDocuments:O,disablePurgeDocuments:A=!1,backendSearchQueries:j=[],onBackendSearch:M,onRemoveBackendQuery:N,serverSort:P,onServerSortChange:F,scope:I=`path`,onScopeChange:ee,canSaveChanges:te=!1,isSavingChanges:ne=!1,onSaveChanges:ie,linkTree:L,folders:R,onOpenFolder:ae}){let[ce,z]=(0,X.useState)(()=>{if(!y)return v;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return v}),le=y?ce:v,ue=(0,X.useCallback)(e=>{z(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[de,fe]=(0,X.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),pe=(0,X.useCallback)(()=>{fe(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[me,he]=(0,X.useState)(new Set),ge=(0,X.useCallback)(e=>{he(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[_e,ye]=(0,X.useState)(new Set),[B,be]=(0,X.useState)(null),[V,xe]=(0,X.useState)(null),Se=Io(),Ce=!!(Se&&i),U=(0,X.useCallback)(t=>{if(!Se||!i)return;let n=t.map(t=>e.find(e=>e.id===t)).filter(e=>!!e);n.length!==0&&Se.openAddRelated({workspaceName:i,documents:n})},[Se,i,e]),[W,we]=(0,X.useState)(!1),[Te,Ee]=(0,X.useState)(null),[De,Oe]=(0,X.useState)(!1),[ke,Ae]=(0,X.useState)(!1),[je,Me]=(0,X.useState)(null),[Ne,Pe]=(0,X.useState)(null),Ie=Eo()==null&&!!i,[Le,Re]=(0,X.useState)(null),ze=!!(L&&m),Be=!!i,{showSuccessToast:He,showErrorToast:Ue}=to(),We=Bp(),Ke=i?e=>We.open(e,i):void 0,qe=I===`workspace`,Je=qe?void 0:o,Xe=qe?void 0:l,[Ze,Qe]=(0,X.useState)(null),[$e,et]=(0,X.useState)(!1),[tt,nt]=(0,X.useState)(!1),[rt,it]=(0,X.useState)(!1),[at,ot]=(0,X.useState)(``),[st,ct]=(0,X.useState)(!1),ut=j.length>0,dt=(0,X.useRef)(null),ft=(0,X.useCallback)(()=>{ot(``),dt.current&&(dt.current.value=``)},[]);(0,X.useEffect)(()=>{if(!y||window.matchMedia(`(max-width: 767px)`).matches)return;let e=dt.current;if(!e)return;let t=setTimeout(()=>e.focus(),60);return()=>clearTimeout(t)},[y]);let[pt,mt]=(0,X.useState)(n);n!==pt&&(mt(n),ye(new Set)),(0,X.useEffect)(()=>{let e=()=>{ze&&_e.size>0&&xe(Array.from(_e))};return window.addEventListener(`workspace:documents:link-selection`,e),()=>window.removeEventListener(`workspace:documents:link-selection`,e)},[ze,_e]),(0,X.useEffect)(()=>{g?.(Array.from(_e))},[_e,g]);let gt=(0,X.useCallback)(()=>{if(!M)return;let e=at.trim();e&&(M(e),ft())},[M,at,ft]),_t=(0,X.useCallback)(()=>{ft(),N&&j.length>0&&N(-1)},[N,j.length,ft]),vt=(0,X.useCallback)((e,t)=>{let i;_e.has(t)&&_e.size>1?i=Array.from(_e):(i=[t],ye(new Set([t])));let a={type:`document`,documentIds:i,sourcePath:n,sourceTreeName:r};e.dataTransfer.setData(`application/json`,JSON.stringify(a)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[_e,n,r]),yt=(0,X.useCallback)(async e=>{if(!m)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let r=null;try{r=JSON.parse(t)}catch{return}r?.type!==`document`||!Array.isArray(r.documentIds)||r.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),ct(!1),await m(n,r.documentIds,{move:e.shiftKey,sourcePath:r.sourcePath,sourceTreeName:r.sourceTreeName}),ye(new Set))},[n,m]),xt=(0,X.useCallback)(e=>{m&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,ct(!0))},[m]),St=(0,X.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||ct(!1)},[]),Ct=(0,X.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2},{name:`schema`,weight:.1}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),wt=(0,X.useMemo)(()=>e.length===0?null:new Po(e,Ct),[e,Ct]),Tt=(0,X.useDeferredValue)(at),Et=(0,X.useMemo)(()=>!Tt.trim()||!wt?e:wt.search(Tt).map(e=>e.item),[e,Tt,wt]),Dt=(0,X.useMemo)(()=>!R||R.length===0||Tt.trim()?[]:R,[R,Tt]),At=Dt.length>0,Mt={folders:Dt,onOpen:ae,onPasteDocuments:m,contextPath:n,treeName:r},{sorted:Nt,sort:Pt,toggleSort:Ft}=Xp(Et,(0,X.useMemo)(()=>({title:e=>bo(e).title?.toLowerCase()??``,schema:e=>bo(e).schemaLabel??``,type:e=>(e.metadata?.contentType||e.schema||``).toLowerCase(),id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),It=(0,X.useCallback)(e=>{let t=P?.sortBy===`crud:updated`?e.updatedAt:e.createdAt,n=Date.parse(t??``);return Number.isNaN(n)?null:n},[P?.sortBy]),Lt=(0,X.useMemo)(()=>d_(Et,It,P?.order===`asc`?`asc`:`desc`),[Et,It,P?.order]),zt=de&&Lt.length>1,Bt=(0,X.useCallback)((e,t)=>{ye(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),Ht=(0,X.useMemo)(()=>(le===`table`?Nt:zt?Lt.filter(e=>!me.has(e.key)).flatMap(e=>e.items):Et).map(e=>e.id),[le,Nt,zt,Lt,me,Et]),Ut=(0,X.useRef)(null),Wt=JSON.stringify([i,n,r,C]),Kt=(0,X.useCallback)((e,t,n,r=!1)=>{let i=Ut.current,a=i?.scope===Wt&&Ht.includes(i.id)?i.id:null;(!r||a===null)&&(Ut.current={scope:Wt,id:e}),ye(i=>{if(r)return vf(Ht,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[Wt,Ht]),qt=(0,X.useCallback)((e,t)=>{if(e.target.closest?.(`[role="dialog"]`))return;e.preventDefault(),e.stopPropagation();let n;_e.has(t)?n=Array.from(_e):(n=[t],ye(new Set([t]))),be({x:e.clientX,y:e.clientY,documentIds:n})},[_e]),Jt=(0,X.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){we(!0);try{for(let n of t)await Xi(i,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;He(`Created ${n} relation${n===1?``:`s`}`),Qp(),xe(null)}catch(e){Ue(e instanceof Error?e.message:`Failed to create relations`)}finally{we(!1)}}},[i,He,Ue]),Yt=(0,X.useCallback)(async(e,t,n)=>{if(m){for(let r of e)await m(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});ye(new Set)}},[m]),Zt=(0,X.useCallback)(async(e,t,n)=>{if(!(!i||!Te)){Oe(!0);try{let r=await Pi(i,Te.ids,{to:e,mode:t,keepDocument:n.keepDocument,folder:n.folder,filename:n.filename,onConflict:n.onConflict}),a=r.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,o=r.successful.length-a,s=r.failed.length,c=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,l=e.join(`, `),u=[a?`${a} already there`:null,s?`${s} skipped`:null].filter(Boolean).join(` · `);o>0?He(`${c} ${l}: ${o} document${o===1?``:`s`}${u?` · ${u}`:``}`):a>0?He(`Nothing to do — already on ${l}`):s>0&&Ue(r.failed[0]?.reason||`Transfer failed`),s>0&&console.warn(`Backend transfer skipped documents:`,r.failed),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),Ee(null),ye(new Set)}catch(e){Ue(e instanceof Error?e.message:String(e))}finally{Oe(!1)}}},[i,Te,He,Ue]),Qt=(0,X.useCallback)(async(t,n)=>{switch(t){case`edit`:if(n.length===1){let t=e.find(e=>e.id===n[0]);if(t){Re({document:t,edit:!0}),be(null);return}}break;case`copy`:f?.(n);break;case`cut`:p?.(n);break;case`link-to`:xe(n),be(null);return;case`add-related`:U(n),be(null);return;case`remove`:n.length===1?o?.(n[0]):l?.(n);break;case`delete`:n.length===1?s?.(n[0]):u?.(n);break;case`destroy`:n.length===1?c?.(n[0]):d?.(n);break;case`view-details`:if(n.length===1){let t=e.find(e=>e.id===n[0]);if(t){Re({document:t}),be(null);return}}break;case`open-url`:if(n.length===1){let t=e.find(e=>e.id===n[0]);t&&t.schema===`data/schema/tab`&&t.data.url&&window.open(t.data.url,`_blank`,`noopener,noreferrer`)}break;case`copy-id`:if(n.length===1)try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(n[0].toString());else{let e=document.createElement(`textarea`);e.value=n[0].toString(),document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e)}}catch(e){console.error(`Failed to copy ID to clipboard:`,e);let t=document.createElement(`textarea`);t.value=n[0].toString(),document.body.appendChild(t),t.select(),document.execCommand(`copy`),document.body.removeChild(t)}}be(null),ye(new Set)},[f,p,o,l,s,u,c,d,e,U]),$t=(0,X.useCallback)(e=>{e.target.closest?.(`[role="dialog"]`)||!(_&&_.length>0&&m)&&!h||(e.preventDefault(),e.stopPropagation(),Qe({x:e.clientX,y:e.clientY}))},[_,m,h]),en=(0,X.useCallback)(async()=>{if(!(!m||!_||_.length===0))try{await m(n,_)}catch(e){console.error(`Failed to paste documents:`,e)}finally{Qe(null)}},[m,_,n]),tn=(0,X.useCallback)(()=>{_e.size===Et.length?ye(new Set):ye(new Set(Et.map(e=>e.id)))},[_e.size,Et]),rn=(0,X.useCallback)(async e=>{if(!h)return!1;try{return await h(e,n)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[h,n]),an=e=>zt?Lt.map(t=>{let n=me.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!_e.has(t),0);return(0,Z.jsxs)(`section`,{className:`group mb-4`,children:[(0,Z.jsx)(M_,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>ge(t.key),onSelectAll:e=>Bt(r,e)}),!n&&e(t.items)]},t.key)}):e(Et);return t?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})}):(0,Z.jsxs)(`div`,{className:`flex-1 flex flex-col min-h-0 p-4 rounded-lg transition-colors ${st?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:xt,onDragLeave:St,onDrop:yt,children:[(0,Z.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,Z.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:at?`${Et.length} of ${e.length}`:`${a.toLocaleString()} document${a===1?``:`s`}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{className:`min-w-0 truncate`,children:[`Context: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n}),x&&S&&x!==S&&(0,Z.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,Z.jsxs)(`p`,{className:`shrink-0`,children:[_e.size>0&&(0,Z.jsxs)(`span`,{className:`text-info`,children:[_e.size,` selected`]}),_e.size>0&&(at||a>T)&&(0,Z.jsx)(`span`,{className:`mx-1`,children:`·`}),at?`on this page`:a>T?`Showing ${Math.min((C-1)*T+1,a)}–${Math.min(C*T,a)}`:null]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[ee&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>ee(`path`),className:`px-2.5 py-2 transition-colors ${I===`path`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List documents in the selected path`,children:`This path`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>ee(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${I===`workspace`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List every document in the workspace (staging excluded)`,children:[(0,Z.jsx)(oe,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),y&&(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,Rt,`Table view`],[`tile`,dr,`Tile view`],[`card`,ht,`Card view`]].map(([e,t,n])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>ue(e),title:n,"aria-pressed":le===e,className:`rounded-sm p-1.5 transition-colors ${le===e?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(t,{className:`h-4 w-4`})},e))}),y&&le!==`table`&&(0,Z.jsx)(`button`,{type:`button`,onClick:pe,title:de?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":de,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors ${de?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(Nn,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,Z.jsx)(pr,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,Z.jsx)(`input`,{ref:dt,type:`text`,placeholder:M?ut?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,defaultValue:``,onChange:e=>ot(e.target.value),onFocus:e=>{let t=e.currentTarget;window.matchMedia(`(max-width: 767px)`).matches&&setTimeout(()=>t.scrollIntoView({block:`center`,behavior:`smooth`}),250)},onKeyDown:e=>{e.key===`Enter`&&M&&(e.preventDefault(),gt())},className:`w-full pl-10 pr-9 py-2 border border-input rounded-md bg-background text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent`}),(at||ut)&&(0,Z.jsx)(`button`,{onClick:_t,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]}),M&&at.trim()&&!j.includes(at.trim())&&(0,Z.jsxs)(J,{size:`sm`,variant:`default`,onClick:gt,className:`shrink-0`,title:ut?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,Z.jsx)(pr,{className:`h-3.5 w-3.5 mr-1`}),ut?`Refine`:`Search server`]}),te&&ie&&(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:ie,disabled:ne,className:`shrink-0`,title:`Save current query and filters`,children:[(0,Z.jsx)(k,{className:`h-3.5 w-3.5 mr-1`}),ne?`Saving...`:`Save filters`]})]}),ut&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),j.map((e,t)=>(0,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),N&&(0,Z.jsx)(`button`,{onClick:()=>N(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),N&&j.length>1&&(0,Z.jsx)(`button`,{onClick:()=>N(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),E&&a>0&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mt-3 pt-3 border-t max-sm:flex-nowrap max-sm:gap-1`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Show:`}),(0,Z.jsxs)(`select`,{value:T,onChange:e=>D?.(Number(e.target.value)),className:`h-control-sm rounded-(--input-radius) border-(length:--input-border-width) border-input bg-background px-2 text-sm focus-ring`,children:[(0,Z.jsx)(`option`,{value:25,children:`25`}),(0,Z.jsx)(`option`,{value:50,children:`50`}),(0,Z.jsx)(`option`,{value:100,children:`100`}),(0,Z.jsx)(`option`,{value:200,children:`200`})]}),(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`per page`})]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 max-sm:gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((C-1)*T+1,a),` - `,Math.min(C*T,a),` of `,a]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(1),disabled:C===1,className:`p-1 touch-target`,children:(0,Z.jsx)(w,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(C-1),disabled:C===1,className:`p-1 touch-target`,children:(0,Z.jsx)(se,{className:`h-4 w-4`})}),(0,Z.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),C,(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,Z.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(a/T)]}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(C+1),disabled:C>=Math.ceil(a/T),className:`p-1 touch-target`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>E(Math.ceil(a/T)),disabled:C>=Math.ceil(a/T),className:`p-1 touch-target`,children:(0,Z.jsx)(gr,{className:`h-4 w-4`})})]})]})]}),e.length>0&&(0,Z.jsxs)(`div`,{className:`mt-3 pt-3 border-t`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>et(e=>!e),"aria-expanded":$e,className:`flex w-full items-center justify-between gap-2 rounded-md border px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-accent/50 sm:hidden`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(kt,{className:`h-3.5 w-3.5`}),`Actions`,_e.size>0?` (${_e.size} selected)`:``]}),(0,Z.jsx)(Ge,{className:`h-3.5 w-3.5 transition-transform ${$e?`rotate-180`:``}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap ${$e?`max-sm:mt-2`:`max-sm:hidden`}`,children:[F&&P&&i&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(n_,{workspaceId:i,value:P,onChange:F})]}),le!==`table`&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:tn,className:`flex items-center gap-2`,disabled:Et.length===0,children:_e.size===Et.length?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Tn,{className:`h-4 w-4`}),`Deselect Page`,at&&` (${Et.length})`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(nn,{className:`h-4 w-4`}),`Select Page`,at&&` (${Et.length})`]})}),O&&a>0&&_e.size===0&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:O,disabled:A||!!at,className:`flex items-center gap-2 text-destructive hover:text-destructive-foreground hover:bg-destructive`,title:A||at?`Purge is disabled while local search is active`:`Delete all documents matching the current server-side filters across all pages`,children:[(0,Z.jsx)(lt,{className:`h-4 w-4`}),`Purge All (`,a,`)`]}),_e.size>0&&(0,Z.jsxs)(Z.Fragment,{children:[Ie&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Pe(Array.from(_e)),children:[(0,Z.jsx)(Fe,{className:`mr-2 h-4 w-4`}),`Bulk Edit… (`,_e.size,`)`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{let e=Array.from(_e);f?.(e)},className:`flex items-center gap-2`,title:`Copy selected documents`,children:[(0,Z.jsx)(Ve,{className:`h-4 w-4`}),`Copy (`,_e.size,`)`]}),ze&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>xe(Array.from(_e)),className:`flex items-center gap-2`,title:`Link selected documents to another path`,children:[(0,Z.jsx)(Gt,{className:`h-4 w-4`}),`Link to… (`,_e.size,`)`]}),Ie&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Me(Array.from(_e)),children:[(0,Z.jsx)(Ve,{className:`mr-1 h-4 w-4`}),`Copy to workspace…`]}),Ce&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>U(Array.from(_e)),className:`flex items-center gap-2`,title:`Create a new document related to the selected ones`,children:[(0,Z.jsx)(H,{className:`h-4 w-4`}),`Add related… (`,_e.size,`)`]}),Be&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Ee({ids:Array.from(_e),mode:`copy`}),className:`flex items-center gap-2`,title:`Copy, move, or delete the file data on storage backends`,children:[(0,Z.jsx)(hr,{className:`h-4 w-4`}),`Backends… (`,_e.size,`)`]}),p&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{p(Array.from(_e))},className:`flex items-center gap-2`,title:`Cut selected documents`,children:[(0,Z.jsx)(lr,{className:`h-4 w-4`}),`Cut (`,_e.size,`)`]}),(o||l)&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,disabled:qe,onClick:()=>{let e=Array.from(_e);e.length===1?Je?.(e[0]):Xe?.(e),ye(new Set)},className:`flex items-center gap-2`,title:qe?`Switch to “This path” to remove documents from a folder`:`Remove selected documents from this folder (kept in index)`,children:[(0,Z.jsx)(G,{className:`h-4 w-4`}),`Remove (unlink) from folder (`,_e.size,`)`]}),(s||u)&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>{let e=Array.from(_e);e.length===1?s?.(e[0]):u?.(e),ye(new Set)},className:`flex items-center gap-2 text-destructive hover:text-destructive-foreground hover:bg-destructive`,title:`Delete from index (data stays on backends)`,children:[(0,Z.jsx)(lt,{className:`h-4 w-4`}),`Delete from index (`,_e.size,`)`]}),(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>nt(!0),className:`flex items-center gap-2`,title:`Export selected documents`,children:[(0,Z.jsx)(er,{className:`h-4 w-4`}),`Export (`,_e.size,`)`]})]}),_&&_.length>0&&m&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>m(n,_),className:`flex items-center gap-2`,title:`Paste documents to current context`,children:[(0,Z.jsx)(b,{className:`h-4 w-4`}),`Paste (`,_.length,`)`]}),_e.size===0&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>nt(!0),className:`flex items-center gap-2`,title:`Export all documents`,children:[(0,Z.jsx)(er,{className:`h-4 w-4`}),`Export All`]}),h&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>it(!0),className:`flex items-center gap-2`,title:`Import documents`,children:[(0,Z.jsx)(re,{className:`h-4 w-4`}),`Import`]}),m&&(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:()=>Ae(!0),className:`flex items-center gap-2`,title:`Browse and add existing documents to this folder`,children:[(0,Z.jsx)(Ot,{className:`h-4 w-4`}),`Add existing…`]})]})]})]}),Et.length===0&&!At?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,onContextMenu:$t,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(bt,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:at?`No documents match your search`:`No documents found in this context`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:at?(0,Z.jsxs)(Z.Fragment,{children:[`Search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,at,`"`]})]}):(0,Z.jsxs)(Z.Fragment,{children:[`Path: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n})]})}),at&&(0,Z.jsx)(`button`,{onClick:ft,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!at&&_&&_.length>0&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click to paste `,_.length,` document(s)`]})]})}):le===`tile`?(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:$t,children:[(0,Z.jsx)(k_,{...Mt}),Et.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),an(e=>(0,Z.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,Z.jsx)(C_,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Kt,onRemoveDocument:Je,onDeleteDocument:s,onLinkDocument:ze?e=>xe([e]):void 0,onOpenToSide:Ke,onRightClick:qt,onDragStart:vt},e.id))}))]}):le===`table`?(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:$t,children:(0,Z.jsxs)(Vp,{children:[(0,Z.jsx)(Hp,{children:(0,Z.jsxs)(Gp,{children:[(0,Z.jsx)(Kp,{className:`w-10`,children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:Et.length>0&&_e.size===Et.length,ref:e=>{e&&(e.indeterminate=_e.size>0&&_e.size<Et.length)},onChange:tn,title:`Select all on this page`})}),(0,Z.jsx)(Yp,{label:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:Pt,onSort:Ft,className:`w-12`}),(0,Z.jsx)(Yp,{label:`Title`,sortKey:`title`,sort:Pt,onSort:Ft,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,Z.jsx)(Yp,{label:`Schema`,sortKey:`schema`,sort:Pt,onSort:Ft,className:`hidden md:table-cell`}),(0,Z.jsx)(Yp,{label:`ID`,sortKey:`id`,sort:Pt,onSort:Ft,className:`hidden lg:table-cell`}),(0,Z.jsx)(Kp,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,Z.jsx)(Yp,{label:`Created`,sortKey:`created`,sort:Pt,onSort:Ft,className:`hidden sm:table-cell`}),(0,Z.jsx)(Kp,{className:`w-12 md:w-auto`,children:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,Z.jsxs)(Up,{children:[Dt.map(e=>(0,Z.jsx)(j_,{folder:e,onOpen:ae,onPasteDocuments:m,contextPath:n,treeName:r},e.path)),Nt.map(e=>(0,Z.jsx)(g_,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Kt,onRemoveDocument:Je,onDeleteDocument:s,onLinkDocument:ze?e=>xe([e]):void 0,onOpenToSide:Ke,onRightClick:qt,onDragStart:vt},e.id))]})]})}):(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:$t,children:[(0,Z.jsx)(A_,{...Mt}),Et.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),an(e=>(0,Z.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,Z.jsx)(`div`,{onContextMenu:t=>{t.stopPropagation(),qt(t,e.id)},children:(0,Z.jsx)(__,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Kt,onRemoveDocument:Je,onDeleteDocument:s,onLinkDocument:ze?e=>xe([e]):void 0,onOpenToSide:Ke,onRightClick:qt,onDragStart:vt})},e.id))}))]}),B&&(0,Z.jsxs)(Cf,{x:B.x,y:B.y,onClose:()=>be(null),className:`bg-background border rounded-lg shadow-elevation-3 py-1 min-w-[120px]`,children:[(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`copy`,B.documentIds),children:[(0,Z.jsx)(Ve,{className:`h-3 w-3`}),`Copy `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),Ie&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Me(B.documentIds),be(null)},children:[(0,Z.jsx)(Ve,{className:`h-3 w-3`}),`Copy to workspace…`]}),p&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`cut`,B.documentIds),children:[(0,Z.jsx)(lr,{className:`h-3 w-3`}),`Cut `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),ze&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`link-to`,B.documentIds),children:[(0,Z.jsx)(Gt,{className:`h-3 w-3`}),`Link to… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),Ie&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Pe(B.documentIds),be(null)},children:[(0,Z.jsx)(Fe,{className:`h-3 w-3`}),`Bulk Edit… (`,B.documentIds.length,`)`]}),Ce&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`add-related`,B.documentIds),children:[(0,Z.jsx)(H,{className:`h-3 w-3`}),`Add related document… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),B.documentIds.length===1&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`view-details`,B.documentIds),children:[(0,Z.jsx)(Vt,{className:`h-3 w-3`}),`View Details`]}),(()=>{let t=e.find(e=>e.id===B.documentIds[0]);return t?.schema===`data/schema/note`||t?.schema===`data/schema/link`?(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`edit`,B.documentIds),children:[(0,Z.jsx)(Fe,{className:`h-3 w-3`}),`Edit`]}):null})(),(()=>{let t=e.find(e=>e.id===B.documentIds[0]);return t?.schema===`data/schema/tab`&&t?.data.url?(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`open-url`,B.documentIds),children:[(0,Z.jsx)(gn,{className:`h-3 w-3`}),`Open URL`]}):null})(),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>Qt(`copy-id`,B.documentIds),children:[(0,Z.jsx)(Xt,{className:`h-3 w-3`}),`Copy ID`]})]}),(Je||Xe)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Unlinks from this folder; the document stays in the index`,onClick:()=>Qt(`remove`,B.documentIds),children:[(0,Z.jsx)(ve,{className:`h-3 w-3`}),`Remove (unlink) from folder `,B.documentIds.length>1?`(${B.documentIds.length})`:``]})]}),(s||u)&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2 text-destructive`,title:`Removes the document from the index entirely; file data stays on its backend(s)`,onClick:()=>Qt(`delete`,B.documentIds),children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from index `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),Be&&B.documentIds.some(t=>(e.find(e=>e.id===t)?.locations?.length??0)>0)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsx)(`div`,{className:`px-3 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:`Backends`}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Copy the file data to another storage backend (keeps the existing copies)`,onClick:()=>{Ee({ids:B.documentIds,mode:`copy`}),be(null)},children:[(0,Z.jsx)(hr,{className:`h-3 w-3`}),`Copy to backend… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,title:`Move the file data to another storage backend (source released once the copy is durable)`,onClick:()=>{Ee({ids:B.documentIds,mode:`move`}),be(null)},children:[(0,Z.jsx)(jt,{className:`h-3 w-3`}),`Move to backend… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]}),(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-destructive hover:text-destructive-foreground text-sm flex items-center gap-2 text-destructive font-medium`,title:`Delete the file data from selected backends (copies elsewhere are kept)`,onClick:()=>{Ee({ids:B.documentIds,mode:`delete`}),be(null)},children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from backend… `,B.documentIds.length>1?`(${B.documentIds.length})`:``]})]}),!Be&&(c||d)&&B.documentIds.some(t=>(e.find(e=>e.id===t)?.locations?.length??0)>0)&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-destructive hover:text-destructive-foreground text-sm flex items-center gap-2 text-destructive font-medium`,title:`Deletes the document and its file data from the storage backend(s)`,onClick:()=>Qt(`destroy`,B.documentIds),children:[(0,Z.jsx)(lt,{className:`h-3 w-3`}),`Delete from backend(s) `,B.documentIds.length>1?`(${B.documentIds.length})`:``]})]}),Ze&&(0,Z.jsxs)(Cf,{x:Ze.x,y:Ze.y,onClose:()=>Qe(null),className:`bg-background border rounded-lg shadow-elevation-3 py-1 min-w-[120px]`,children:[_&&_.length>0&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:en,children:[(0,Z.jsx)(b,{className:`h-3 w-3`}),`Paste Documents (`,_.length,`)`]}),h&&(0,Z.jsxs)(`button`,{className:`w-full text-left px-3 py-1 hover:bg-muted text-sm flex items-center gap-2`,onClick:()=>{Qe(null),it(!0)},children:[(0,Z.jsx)(re,{className:`h-3 w-3`}),`Import Documents`]})]}),(0,Z.jsx)(f_,{isOpen:tt,onClose:()=>nt(!1),documents:e,selectedDocuments:_e}),(0,Z.jsx)(p_,{isOpen:rt,onClose:()=>it(!1),onImport:rn}),je&&i&&(0,Z.jsx)(hp,{workspaceId:i,ids:je,onClose:()=>Me(null)}),V&&L&&(0,Z.jsx)(pp,{onClose:()=>xe(null),children:(0,Z.jsx)(dp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,documentCount:V.length,fixedWorkspaceName:i,tabs:[`context`,`directory`,`relations`],saving:W,relationExcludeIds:new Set(V),onConfirm:(e,t)=>Yt(e,V,t),onConfirmRelation:e=>Jt(e,V),onClose:()=>xe(null)})}),Te&&i&&(0,yf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(Ip,{workspaceId:i,documentCount:Te.ids.length,initialMode:Te.mode,defaultFilename:Te.ids.length===1?mo(e.find(e=>e.id===Te.ids[0])??{}):``,saving:De,onConfirm:Zt,onClose:()=>{De||Ee(null)}})}),window.document.body),ke&&m&&(0,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>Ae(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(Lp,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:i,onConfirm:async e=>{await m(n,e),Ae(!1)},onClose:()=>Ae(!1)})})]}),window.document.body),Ne&&i&&(0,Z.jsx)(jp,{workspaceId:i,documentIds:Ne,onClose:()=>Pe(null)}),(0,Z.jsx)(Xg,{document:Le?.document??null,isOpen:!!Le,onClose:()=>Re(null),workspaceId:i,initialEdit:Le?.edit})]})}function P_(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,X.useState)(e.canvasQueries??[]),a=(0,X.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,X.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,X.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,X.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,X.useCallback)(()=>o([]),[o])}}function F_({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,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(1),[u,d]=(0,X.useState)(!0),f=t.canvasSort??Qg,{queries:p,runSearch:m,removeQuery:h}=P_(t,()=>l(1));(0,X.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,X.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(n_,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsx)(N_,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}pf({type:`documents-table`,name:`Documents`,icon:Rt,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:F_});function I_({config:e,setConfig:t,canvas:n}){let[r,i]=(0,X.useState)(()=>new Date),a=e.format!==`24`;return(0,X.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,Z.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,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,Z.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`})]})}pf({type:`clock`,name:`Clock`,icon:cn,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:I_});var L_=450,R_=10;function z_(e,t){let{open:n}=Sg(),r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.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()},L_))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>R_&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function B_({doc:e,workspaceId:t}){let n=bo(e),{activationProps:r}=z_(e,t);return(0,Z.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,Z.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function V_({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null);return(0,X.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,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,Z.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,Z.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,Z.jsx)(B_,{doc:e,workspaceId:t.workspaceId},e.id))})}pf({type:`recent-documents`,name:`Recent documents`,icon:Bn,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:V_});function H_({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,Z.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`})}pf({type:`note`,name:`Note`,icon:xn,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:H_});var U_=`data/schema/file`,W_=`data/schema/drawing`;function G_(e){return(e.schema===U_||e.schema===W_)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function K_(e){return e.schema===U_&&String(e.metadata?.contentType||``).startsWith(`video/`)}var q_=`data/mime/image`;function J_(e,t,n=!1){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(1),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=P_(e,()=>c(1)),y=e.canvasSort??Qg;(0,X.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:[q_,`data/mime/video`]}:{allOf:[q_]}});if(r)return;i((a.payload||[]).filter(e=>G_(e)||n&&K_(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,X.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,X.useCallback)(()=>{m(``),v()},[v]),S=(0,X.useCallback)(e=>{_(e)},[_]),C=(0,X.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,X.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}}function Y_({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=Lm(e,t.id,512,{blobFallback:!K_(t),version:t.checksumArray?.[0]??null}),c=mo(t)||`image-${t.id}`,l=Co(t),u=l!==``&&i!==`off`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-lg border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!K_(t)&&(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,Z.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-200 group-hover:scale-105`}),K_(t)&&(0,Z.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,Z.jsx)(Oe,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,Z.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,Z.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,Z.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,Z.jsx)(v,{className:`h-3 w-3`})})]})}function X_({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Oo(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!K_(a)}),l=mo(a)||`image-${a.id}`,u=Co(a),[d,f]=(0,X.useState)(!1);return Sf(r),(0,X.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,yf.createPortal)((0,Z.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,Z.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,Z.jsx)(G,{className:`h-5 w-5`})}),n>0&&!d&&(0,Z.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,Z.jsx)(se,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,Z.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,Z.jsx)(Ye,{className:`h-6 w-6 touch-target`})}),(0,Z.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,Z.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),K_(a)&&(0,Z.jsx)(Q_,{workspaceId:e,doc:a},a.id),o&&(0,Z.jsx)(Tm,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,Z.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,Z.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&&!K_(a)&&(0,Z.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function Z_({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,Z.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,Z.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}),_&&(0,Z.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,Z.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,Z.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,Z.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,Z.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,Z.jsx)(v,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(n_,{workspaceId:e,value:u,onChange:d}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,Z.jsx)(ud,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,Z.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,Z.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,Z.jsx)(se,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,Z.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,Z.jsx)(Ye,{className:`h-3.5 w-3.5`})})]})]})]})}function Q_({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=go(e,t.id);return(0,Z.jsxs)(Z.Fragment,{children:[r&&(0,Z.jsx)(`span`,{children:`Loading video…`}),i&&(0,Z.jsx)(`span`,{role:`alert`,children:i}),n&&(0,Z.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function $_({config:e,setConfig:t,canvas:n}){let r=J_(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=Eo()==null&&(n.interactive??!n.readOnly),[a,o]=(0,X.useState)(new Set),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.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,X.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Z_,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,Z.jsx)(J,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,Z.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,Z.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,Z.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,Z.jsx)(Y_,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,Z.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,Z.jsx)(Cf,{x:d.x,y:d.y,onClose:()=>f(null),className:`rounded-lg border bg-popover p-1 shadow-elevation-3`,children:(0,Z.jsxs)(`button`,{className:`px-3 py-2 text-sm hover:bg-muted`,onClick:()=>{u(d.ids),f(null)},children:[`Bulk Edit… (`,d.ids.length,`)`]})}),l&&(0,Z.jsx)(jp,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,Z.jsx)(X_,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}pf({type:`gallery`,name:`Gallery`,icon:sn,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:$_});var ev=150;function tv(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function nv(e){let t=e.metadata??{},n=e.data??{};return{w:tv(t.width)||tv(t.imageWidth)||tv(n.width)||tv(n.imageWidth),h:tv(t.height)||tv(t.imageHeight)||tv(n.height)||tv(n.imageHeight)}}function rv(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=nv(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 iv({config:e,setConfig:t,canvas:n}){let r=J_(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,X.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Z_,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,Z.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,Z.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${ev}px, 1fr))`,gridAutoRows:`${ev}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=rv(e,t);return(0,Z.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,Z.jsx)(Y_,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,Z.jsx)(X_,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}pf({type:`mosaic`,name:`Mosaic`,icon:$n,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:iv});var av=`data/schema/task`;function ov({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=hh(e),[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=ea(e),l=i.status===`completed`,u=i.status??`pending`,d=_h(i),{activationProps:f,stopRowActivation:p}=z_(e,t),m=async()=>{if(!(n||a)){o(!0);try{await yh(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,Z.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,Z.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,Z.jsx)(Mt,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,Z.jsx)($e,{className:`h-3 w-3`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${gh[u]}`,children:sh[u]}),i.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(pe,{className:`h-3 w-3`}),vh(i.dueDate)]}),typeof i.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,Z.jsx)(bn,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function sv({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,X.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,X.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[av],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===uo))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,X.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,X.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>hh(e).status!==`completed`):i,v=i.filter(e=>{let t=hh(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,Z.jsx)(ov,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}pf({type:`todos`,name:`Todos`,icon:On,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:sv});function cv(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var lv=`context`;function uv(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:lv,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:lv,path:e?`/${e}`:`/`}}return{treeName:lv,path:`/`}}function dv(e,t,n){let r=n&&n!==lv?`/trees/${encodeURIComponent(n)}`:``,i=cv(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function fv({canvas:e}){return Eo()!=null||!rd()?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,Z.jsx)(pv,{workspaceId:e.workspaceId},e.workspaceId)}function pv({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(`Workspace`),[a,o]=(0,X.useState)(!0),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([wi(e),qa(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),l(null)}catch{if(t||a!==r)return;n([]),l(`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 c=Xu.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),c?.(),window.clearInterval(u)}},[e,u]),(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,Z.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>d(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,Z.jsx)(Te,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,Z.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=Hf(t.color),i=(0,Z.jsxs)(Z.Fragment,{children:[n?(0,Z.jsx)(at,{className:`h-5 w-5 shrink-0 text-warning`}):(0,Z.jsx)(c,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,Z.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,Z.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-lg border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,Z.jsx)(`li`,{children:n?(0,Z.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,Z.jsx)(mu,{to:dv(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,Z.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.`})})]})}pf({type:`workspace-pins`,name:`Workspace pins`,icon:ne,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:fv});function mv({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,X.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,Z.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-lg border bg-background overflow-hidden`,children:[(0,Z.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,Z.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(hv,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:de}),(0,Z.jsx)(hv,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:jn})]}),(0,Z.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,Z.jsx)(it,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(Fn,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,Z.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,Z.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,yf.createPortal)(d,u??document.body):d}function hv({on:e,onClick:t,label:n,icon:r}){return(0,Z.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,Z.jsx)(r,{className:`w-3.5 h-3.5`})})}var gv=(0,df.WidthProvider)(df.default),_v=12,vv=80,yv=40,bv=[12,12],xv=[8,8],Sv={w:!1,h:!1};function Cv(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function wv(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function Tv(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 Ev(e,t,n=0){let r=n>0?n:Cv(e);return e.map(e=>{let n=t[e.i]??Sv;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?_v:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var Dv=4;function Ov(e,t,n=bv[1]){return Math.max(1,Math.ceil((e-n-Dv)/(t+n)))}var kv=45,Av=640;function jv(e,t,n=0,r){let i=[...Ev(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:_v,y:a,h:n};return a+=n,i})}var Mv=e=>e&&e.trim()?[e]:[];function Nv(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(Tv):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=_v,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function Pv({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,X.useMemo)(()=>Nv(a),[a]),[p,m]=(0,X.useState)(f.layout),[h,g]=(0,X.useState)(f.widgets),[_,v]=(0,X.useState)(f.fills),y=(0,X.useRef)(f.fills),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(0),N=(0,X.useRef)(0),P=(0,X.useCallback)(e=>{y.current=e,v(e)},[]),[F,I]=(0,X.useState)(()=>i?.sort??Qg),ee=(0,X.useRef)(!1),[te,ne]=(0,X.useState)(()=>Mv(i?.query)),re=(0,X.useRef)(!1),ie=(0,X.useRef)(null),L=(0,X.useRef)(f),R=(0,X.useCallback)(e=>{let t=mf(h[e]?.type??``)?.mobileHeight;if(!(!t||j<=0))return Math.max(1,Math.round(j*t))},[h,j]),ae=(0,X.useMemo)(()=>O?jv(p,_,j,R):Ev(p,_,j),[p,_,O,j,R]),oe=O?yv:vv,se=(0,X.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,X.useEffect)(()=>{let e=Nv(a);m(e.layout),g(e.widgets),P(e.fills),L.current=e,I(i?.sort??Qg),ee.current=!1,ne(Mv(i?.query)),re.current=!1,C(!1)},[n,r]),(0,X.useEffect)(()=>{if(!s)return;let e=Nv(a);m(e.layout),g(e.widgets),P(e.fills),L.current=e},[s,se,a,P]),(0,X.useEffect)(()=>{let e=ie.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<Av;A(n),N.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?xv:bv;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&M(Ov(t,n?yv:vv,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let ce=(0,X.useCallback)(e=>{I(e),ee.current=!0,C(!0)},[]),z=(0,X.useCallback)(e=>{ne(e),re.current=!0,C(!0)},[]),le=(0,X.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:F,setCanvasSort:d?ce:void 0,canvasQueries:te,setCanvasQueries:d?z:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await Si(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 Si(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,F,ce,te,z]),ue=(0,X.useCallback)((e,t,n)=>{L.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),de=(0,X.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:L.current.widgets,layout:L.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};L.current={...r,fills:y.current};let o=ee.current||re.current?{...i||{},...ee.current?{sort:F.sortBy?F:null}:{},...re.current?{query:te.join(` `).trim()||null}:{}}:void 0;await Di(e,n,t,{...a||{},ui:r},o),ee.current=!1,re.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,F,te]),fe=(0,X.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 ue(n,h),n})},[d,O,ue,h]),pe=(0,X.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??Sv,i=bv[1]+(n.y+n.h)*(vv+bv[1]),a={w:n.x+n.w>=_v,h:N.current>0&&i>=N.current-kv};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};P(o),ue(L.current.layout,h,o)},[d,P,ue,h]),me=(0,X.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??Sv,r={...y.current,[e]:{...n,[t]:!n[t]}};P(r),ue(p,h,r)},[d,P,ue,p,h]),he=(0,X.useCallback)(e=>{let t=mf(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:wv(ae),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>=_v,h:!1}};m(l),g(u),P(d),x(!1),ue(l,u,d)},[p,ae,h,P,ue]),ge=(0,X.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),P(r),ue(t,n,r)},[p,h,P,ue]),_e=(0,X.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return ue(p,r),r})},[p,ue]),ve=Object.keys(h);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Z.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,Z.jsx)(H,{className:`w-3.5 h-3.5`}),`Add`,(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,Z.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:hf().map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>he(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,Z.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:de,disabled:!S||w,className:K(`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,Z.jsx)(k,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[ve.length,` widget`,ve.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,Z.jsx)(`div`,{ref:ie,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:ve.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,Z.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,Z.jsx)(gv,{className:`layout`,layout:ae,cols:_v,rowHeight:oe,margin:O?xv:bv,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:fe,onResizeStop:pe,compactType:`vertical`,children:ve.map(e=>{let t=h[e],n=mf(t.type),r=_[e]??Sv,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,Z.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,Z.jsx)(mv,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>ge(e),fill:_[e]??Sv,onToggleFill:d?t=>me(e,t):void 0,children:(0,Z.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>_e(e,t),canvas:le})}):(0,Z.jsx)(mv,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>ge(e),children:(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var Fv=`data/schema/file`;function Iv(e){return String(e.locations?.[0]?.url||``).trim()}function Lv(e){let t=Iv(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function Rv(e){return e.schema===Fv&&String(e.metadata?.contentType||``).startsWith(`image/`)}function zv(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 Bv(e){if(e.schema!==Fv)return bo(e);let t=Lv(e),n=String(e.metadata?.contentType||``).trim(),r=zv(e.metadata?.size);return{...bo(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:Iv(e),schemaLabel:`file`}}function Vv(e){return/^https?:\/\/[^\s]+$/i.test(e)}function Hv(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return Vv(t)?t:null}return t.isExternal&&Vv(t.subtitle)?t.subtitle:Vv(t.title)?t.title:null}function Uv(e,t,n=!1){return _o(e,t,{download:n})}function Wv(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>Vv(e)?(0,Z.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 Gv(e){return e?new Date(e).toLocaleString():``}function Kv(){let{code:e=``}=tl(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),d=(0,X.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=Bv(t);return[t.schema,n.title,n.preview,n.subtitle,Lv(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,X.useCallback)(async()=>{if(e){i(!0);try{let t=await Y.get(`${ti}/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,X.useEffect)(()=>{p()},[p]),(0,X.useEffect)(()=>{if(!e)return;let t=$a(`${si}/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,X.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,X.useCallback)(()=>{u(``)},[]),g=(0,X.useCallback)(async()=>({payload:d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Z.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Z.jsxs)(Du,{className:`max-w-md bg-card`,children:[(0,Z.jsx)(Ou,{children:(0,Z.jsx)(ku,{children:`Canvas unavailable`})}),(0,Z.jsx)(ju,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Z.jsx)(qu,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,Z.jsx)(Ao.Provider,{value:e,children:(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Z.jsxs)(Du,{className:`bg-card shadow-elevation-3`,children:[(0,Z.jsx)(Ou,{className:`border-b p-3 sm:p-6`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Z.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,Z.jsx)($n,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Z.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,Z.jsx)(S,{className:`h-3 w-3 text-success`}):(0,Z.jsx)(qe,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Z.jsx)(ku,{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,Z.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,Z.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,Z.jsx)(S,{className:`h-3.5 w-3.5 text-success`}):(0,Z.jsx)(qe,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Z.jsxs)(ju,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Z.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,Z.jsxs)(`span`,{className:`truncate`,children:[`· `,Gv(t.stats.refreshedAt)]})]}),(0,Z.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Z.jsx)(qv,{label:`Path`,value:t.share.path,mono:!0}),(0,Z.jsx)(qv,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Z.jsx)(qv,{label:`Shown`,value:String(f.length)}),(0,Z.jsx)(qv,{label:`Refreshed`,value:Gv(t.stats.refreshedAt)})]}),v&&(0,Z.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,Z.jsx)(Pv,{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,Z.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Z.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,Z.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.jsx)(G,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Z.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,Z.jsx)(Te,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,Z.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,Z.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,Z.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=Bv(t),r=Hv(t,n),i=t.schema===Fv,a=i?Uv(e,t.id):null,o=a||r;return(0,Z.jsxs)(`article`,{className:`p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Z.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Z.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Z.jsxs)(`a`,{href:Uv(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,Z.jsx)(er,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Z.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:Gv(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Z.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:Wv(n.preview)}),Rv(t)&&(0,Z.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Z.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,Z.jsx)(qu,{className:`mt-6 text-center`})]})})})}function qv({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var Jv=(0,X.createContext)(void 0);function Yv(){let e=(0,X.useContext)(Jv),t=Io()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,X.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 Xv({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,X.useRef)(null),o=(0,X.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,X.useEffect)(()=>{o()},[e,o]),(0,Z.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 Zv({onLinkTo:e,onDelete:t}){return(0,Z.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,Z.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,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function Qv({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=to(),[a,o]=(0,X.useState)(!1);return(0,Z.jsx)(pp,{onClose:n,children:(0,Z.jsx)(dp,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await $r(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:fp,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 Xi(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Qp(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var $v=1200;function ey(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 ty(e,t){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=(0,X.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([is(n,[t]),as(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 Ki(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,X.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,X.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,X.useEffect)(()=>{u()},[u]),(0,X.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,X.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await Ha(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}var ny=`2.0`;function ry({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let[s,c]=(0,X.useState)(String(e.data?.title??``)),[l,u]=(0,X.useState)(String(e.data?.content??``)),[d,f]=(0,X.useState)(`idle`),p=(0,X.useRef)({title:String(e.data?.title??``),content:String(e.data?.content??``)}),m=(0,X.useRef)(null),h=(0,X.useRef)(0),g=(0,X.useCallback)(async(n,r)=>{if(!t||n===p.current.title&&r===p.current.content||!r.trim())return;let i=++h.current;f(`saving`);try{if(await Ui(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data||{},...n.trim()?{title:n.trim()}:{title:void 0},content:r},metadata:e.metadata}),i!==h.current)return;p.current={title:n,content:r},f(`saved`),setTimeout(()=>f(e=>e===`saved`?`idle`:e),1500)}catch{i===h.current&&f(`error`)}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),_=(0,X.useCallback)((e,t)=>{f(`dirty`),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(e,t),$v)},[g]),v=(0,X.useCallback)(()=>{m.current&&=(clearTimeout(m.current),null),g(s,l)},[g,s,l]);return(0,X.useEffect)(()=>()=>{m.current&&clearTimeout(m.current)},[]),(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[ey(e.createdAt),` · #`,e.id]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[d===`saving`&&(0,Z.jsx)(Mt,{className:`inline h-3 w-3 animate-spin`}),d===`saved`&&(0,Z.jsx)($e,{className:`inline h-3 w-3 text-success`}),d===`dirty`&&`·`,d===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Zv,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsx)(`input`,{value:s,onChange:e=>{c(e.target.value),_(e.target.value,l)},onBlur:v,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,Z.jsx)(Xv,{value:l,onChange:e=>{u(e),_(s,e)},onBlur:v,innerRef:t=>r(e.id,t)})]})}function iy({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:r,onChange:e=>i(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,Z.jsx)(Xv,{value:a,onChange:o,placeholder:`Write your note…`}),l&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!a.trim()||!e||s)){c(!0),u(null);try{await ts(e,[{schema:no,schemaVersion:ny,data:{...r.trim()?{title:r.trim()}:{},content:a},metadata:{features:[]}}]),t()}catch(e){u(e instanceof Error?e.message:`Failed to create note`),c(!1)}}},disabled:!a.trim()||s,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:s?`Saving…`:`Save note`})})]})}function ay({autoAdd:e=!1}){let t=Yv(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=ty(t,no),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(`desc`),[m,h]=(0,X.useState)(e),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(new Map),y=(0,X.useRef)(new Map),b=(0,X.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,X.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,X.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,X.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,X.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,X.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,X.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,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.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,Z.jsx)(hn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(H,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,Z.jsx)(iy,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)}),r&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,Z.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,Z.jsx)(ry,{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,Z.jsx)(Qv,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:ps(t)})}var oy=`2.1`,sy=new Set([`completed`,`cancelled`]);function cy({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,X.useState)(String(e.data?.title??``)),[u,d]=(0,X.useState)(String(e.data?.description??``)),[f,p]=(0,X.useState)(e.data?.status||`pending`),[m,h]=(0,X.useState)(uh(e.data?.dueDate)),[g,_]=(0,X.useState)(`idle`),{replicating:v,label:y}=ea(e),b=(0,X.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),x=(0,X.useRef)(null),S=(0,X.useRef)(0),C=(0,X.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++S.current;_(`saving`);try{let i=dh(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 Ui(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]),w=(0,X.useCallback)((e,t)=>{(e!==b.current.title||t!==b.current.description)&&(_(`dirty`),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>C({title:e,description:t,status:f,due:m}),$v))},[C,f,m]),T=(0,X.useCallback)(()=>{x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:m})},[C,c,u,f,m]);(0,X.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]);let E=(0,X.useCallback)(async()=>{let t=f,n=f===`completed`?`pending`:`completed`;p(n),await C({title:c,description:u,status:n,due:m})?s(e.id,n):p(t)},[f,C,c,u,m,e.id,s]),D=(0,X.useCallback)(e=>{h(e),x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:e})},[C,c,u,f]),O=sy.has(f);return(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0`,children:[ey(e.createdAt),` · #`,e.id,f!==`pending`&&(0,Z.jsxs)(`span`,{children:[` · `,sh[f]??f]})]}),(0,Z.jsx)(Yh,{value:m,onChange:D,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,Z.jsx)(Mt,{className:`inline h-3 w-3 animate-spin`}),v&&(0,Z.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,Z.jsx)($e,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Zv,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:E,className:`mt-0.5 shrink-0 text-muted-foreground transition-colors hover:text-foreground`,"aria-label":O?`Mark as pending`:`Mark as completed`,title:O?`Mark as pending`:`Mark as completed`,children:O?(0,Z.jsx)(te,{className:`h-4 w-4 text-success`}):(0,Z.jsx)(an,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),w(e.target.value,u)},onBlur:T,placeholder:`Untitled`,spellCheck:!1,className:K(`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold outline-none placeholder:text-muted-foreground/50`,O?`text-muted-foreground line-through`:`text-foreground`)}),(0,Z.jsx)(Xv,{value:u,onChange:e=>{d(e),w(c,e)},onBlur:T,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function ly({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(fh()),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]}),(0,Z.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,Z.jsx)(Xv,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(Yh,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await ts(e,[{schema:uo,schemaVersion:oy,data:ph({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 uy({autoAdd:e=!1}){let t=Yv(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=ty(t,uo),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(0),[p,m]=(0,X.useState)(`desc`),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(e),[y,b]=(0,X.useState)(null),x=(0,X.useRef)(new Map),S=(0,X.useRef)(new Map),C=(0,X.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,X.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,X.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,X.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,X.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!sy.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,X.useMemo)(()=>n.filter(e=>sy.has(String(e.data?.status??`pending`))).length,[n]),k=(0,X.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,X.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,X.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,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.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,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:K(`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,Z.jsx)(Vt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(kn,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(hn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(H,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,Z.jsx)(ly,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,Z.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,Z.jsx)(cy,{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,Z.jsx)(Qv,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:ps(t)})}var dy=(0,X.createContext)(null);function fy(){let e=(0,X.useContext)(dy);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function py(e=!0){let{registerViewer:t}=fy();(0,X.useEffect)(()=>{if(e)return t()},[e,t])}var my=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],hy=`canvas.lens.camera`,gy={min:1,max:4,step:.1,hardware:!1};function _y(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(hy)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:my.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function vy(e,t){let n=my.find(t=>t.id===e.resolution)??my[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function yy(e={}){let t=(0,X.useRef)(null),n=(0,X.useRef)(e.onEnded);(0,X.useEffect)(()=>{n.current=e.onEnded});let r=(0,X.useRef)(null),i=(0,X.useRef)(null),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(_y),p=(0,X.useRef)(d),[m,h]=(0,X.useState)([]),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(1),w=(0,X.useRef)(1),[T,E]=(0,X.useState)(!1),D=(0,X.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,X.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,X.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,X.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,X.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,X.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:vy(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:vy(e,!1),audio:!1});throw t}},[]),P=(0,X.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]),F=(0,X.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]),I=(0,X.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(hy,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]),ee=(0,X.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),te=(0,X.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),ne=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),re=(0,X.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]),ie=(0,X.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,X.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:P,startScreen:F,stop:j,captureFrame:ie,camera:(0,X.useMemo)(()=>g?{devices:m,prefs:d,setPrefs:I,size:b,zoomRange:v?.zoom?{min:v.zoom.min,max:v.zoom.max,step:v.zoom.step||.1,hardware:!0}:gy,zoom:S,setZoom:ee,torchSupported:!!v?.torch,torch:T,setTorch:te,focusSupported:ne,focusAt:re}:null,[g,m,d,I,b,v,S,ee,T,te,ne,re])}}async function by(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(`${Qr.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 xy=[{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}],Sy=1e3,Cy={sortBy:`crud:created`,order:`desc`},wy={features:{allOf:[],anyOf:[],noneOf:[]},timeline:{quickFilter:null,customRanges:[],indexCreated:!0,indexUpdated:!0,indexDeleted:!1,contentEvents:!1,selectedTimelines:[]},geo:{bbox:null,includeUnlocated:!1},lens:{gps:null,ids:null},sort:{...Cy}};function Ty(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function Ey(e,t=!1){if(!e.gps)return[];let{lat:n,lon:r,radiusM:i}=e.gps;return[`geo:near:${n},${r},${Math.max(1,Math.round(i))}m`,...t?[`geo:missing`]:[]]}function Dy(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function Oy(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Dy(e),c=s.length>0?s.map(e=>`${e.start}..${e.end}`):t?[t]:[];if(c.length===0)return[];let l=[];return n&&l.push(`crud:created`),r&&l.push(`crud:updated`),i&&l.push(`crud:deleted`),a&&l.push(`content`),l.push(...o),l.flatMap(e=>c.map(t=>`t:${e}:${t}`))}function ky(e,t,n=[]){return{features:e.features,filters:[...Oy(e.timeline),...Ty(e.geo),...Ey(e.lens,e.geo.includeUnlocated)],queryOptions:{ids:e.lens.ids,sortBy:e.sort.sortBy,order:e.sort.order,queries:n,geoSelection:t,includeUnlocated:e.geo.includeUnlocated??!1}}}var Ay=32,jy=12,My=`canvas.lens.fit`;function Ny({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=fy(),a=(0,X.useRef)(null),[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,X.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.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:K(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,Z.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 Py({children:e}){let t=Io(),n=(0,X.useRef)(t);(0,X.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,X.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=yy({onEnded:()=>a.current()}),[m,h]=(0,X.useState)(null),g=(0,X.useRef)(m);(0,X.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(Sy),[C,w]=(0,X.useState)(``),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)([]),[F,I]=(0,X.useState)(null),[ee,te]=(0,X.useState)(null),ne=ee&&ee.frame===F?ee:null,re=(0,X.useRef)(null),[ie,L]=(0,X.useState)(0),[R,ae]=(0,X.useState)(``),[oe,se]=(0,X.useState)(()=>{try{return localStorage.getItem(My)===`cover`?`cover`:`contain`}catch{return`contain`}}),ce=(0,X.useCallback)(e=>{se(e);try{localStorage.setItem(My,e)}catch{}},[]),z=(0,X.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:Sy,snapshot:!1}),le=(0,X.useRef)([]),ue=(0,X.useRef)(new Map),de=(0,X.useRef)(null),fe=(0,X.useRef)(null),pe=(0,X.useRef)(null),me=(0,X.useRef)(0),he=(0,X.useRef)(``),ge=(0,X.useRef)(!1),_e=(0,X.useRef)(async()=>{}),ve=(0,X.useRef)(()=>{});(0,X.useEffect)(()=>{z.current.text=T,z.current.maxDistance=C===``?NaN:Number(C),z.current.rateMs=x,z.current.paused=y},[T,C,x,y]);let ye=(0,X.useCallback)(()=>(L(e=>e+1),()=>L(e=>Math.max(0,e-1))),[]),B=(0,X.useCallback)(e=>{le.current=[...le.current.slice(-2),e];let t=le.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=de.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(de.current=i,n.current?.setLensIds(i))},[]),be=(0,X.useCallback)((e,t)=>{for(let n of e)ue.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);le.current=[...le.current.slice(-2),n];let r=le.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...ue.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>ue.current.get(e)).filter(e=>!!e);M(s.length),P(s)},[]),V=(0,X.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;pe.current?.abort();let a=new AbortController;pe.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await by(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?[...Oy(o.filters.timeline),...Ty(o.filters.geo),...Ey(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?jy:Ay,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||z.current!==t||!t.running?!1:(me.current=0,A(Math.round(performance.now()-r)),O(null),i?be(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):B(c.ids),!0)}catch(e){return a.signal.aborted||z.current!==t||!t.running?!1:(me.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[be,B]),xe=(0,X.useCallback)(async()=>{let e=z.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await V(t,e)}if(z.current.running){let e=Math.max(me.current?Math.min(3e4,1e3*2**Math.min(me.current-1,5)):0,z.current.rateMs-(performance.now()-t));fe.current=window.setTimeout(()=>void _e.current(),e)}},[p,V]);(0,X.useEffect)(()=>{_e.current=xe},[xe]);let H=(0,X.useCallback)(()=>{let e=z.current.consumer===`filter`;z.current.running=!1,me.current=0,z.current.consumer=null,fe.current&&window.clearTimeout(fe.current),pe.current?.abort(),f(),le.current=[],ue.current.clear(),de.current=null,h(null),v(null),b(!1),ae(``),P([]),I(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,X.useEffect)(()=>{a.current=H},[H]);let Se=(0,X.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||ge.current||(z.current.running&&H(),e===`photo`&&!r.image))return!1;ge.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return ge.current=!1,i?(le.current=[],ue.current.clear(),de.current=null,P([]),M(null),O(null),ae(r.workspaceRef),z.current={...z.current,running:!0,paused:!1,consumer:t,workspaceRef:r.workspaceRef,contextPath:r.contextPath??null,snapshot:e===`photo`},I(e===`photo`?r.image:null),h(e),v(t),b(!1),t===`filter`&&n.current?.setLensIds([]),e===`photo`?ve.current(r.image):xe(),!0):!1},[u,d,H,xe]),Ce=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,X.useEffect)(()=>{he.current!==Ce&&(he.current=Ce,z.current.consumer===`filter`&&(pe.current?.abort(),le.current=[],de.current=null,n.current?.setLensIds([])))},[Ce]);let U=(0,X.useCallback)(e=>{z.current.contextPath=e},[]),W=(0,X.useCallback)(e=>{z.current.paused=e,b(e)},[]),we=JSON.stringify([T,C,Ce]),Te=(0,X.useRef)(we);(0,X.useEffect)(()=>{Te.current=we});let Ee=(0,X.useCallback)(e=>{let t=z.current;!t.running||!t.workspaceRef||(re.current={frame:e,key:Te.current},le.current=[],ue.current.clear(),de.current=null,M(null),V(e,t))},[V]);(0,X.useEffect)(()=>{ve.current=Ee},[Ee]);let De=(0,X.useCallback)(()=>{let e=z.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,I(t),Ee(t))},[p,Ee]),Oe=(0,X.useCallback)(()=>{if(z.current.running&&g.current===`photo`){H();return}z.current.snapshot=!1,pe.current?.abort(),le.current=[],ue.current.clear(),I(null)},[H]),ke=(0,X.useCallback)(async(e,t,n)=>{let r=z.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,I(e),Ee(e),!0):Se(`photo`,t,{...n,image:e})},[Se,Ee]);(0,X.useEffect)(()=>{if(!F)return;let e=!0,t=new Image;return t.onload=()=>{e&&te({frame:F,width:t.naturalWidth,height:t.naturalHeight})},t.src=F,()=>{e=!1}},[F]),(0,X.useEffect)(()=>{if(!F)return;let e=re.current;if(e&&e.frame===F&&e.key===we)return;let t=window.setTimeout(()=>Ee(F),350);return()=>window.clearTimeout(t)},[F,we,Ee]),(0,X.useEffect)(()=>{!i||!z.current.running||r&&r===z.current.workspaceRef||H()},[i,r,H]);let Ae=(0,X.useCallback)(()=>{let e=n.current;if(e){if(z.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,X.useEffect)(()=>H,[H]);let je=(0,X.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:oe,setFit:ce,workspaceRef:R,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:Se,setContextPath:U,stop:H,setPaused:W,snapshot:F,takeSnapshot:De,clearSnapshot:Oe,snapshotSize:ne,searchPhoto:ke,reopen:Ae,hasViewer:ie>0,registerViewer:ye}),[m,y,_,s,c,oe,ce,R,x,C,T,l,D,k,j,N,Se,U,H,W,F,De,Oe,ne,ke,Ae,ie,ye]);return(0,Z.jsxs)(dy.Provider,{value:je,children:[e,(0,Z.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 Fy=`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`,Iy=`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`,Ly=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function Ry({className:e}){let{camera:t,fit:n,setFit:r}=fy();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,Z.jsxs)(`div`,{className:K(`flex flex-col gap-2`,e),children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,Z.jsxs)(`select`,{className:K(Fy,`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,Z.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,Z.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,Z.jsx)(`select`,{className:Fy,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:my.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:Iy,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,Z.jsx)(Zt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(pn,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:Iy,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,Z.jsx)(cr,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:K(Iy,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,Z.jsx)(Lt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,Z.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,Z.jsx)(z,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:Ly(l)})]})]})}function zy(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=fy();return e?n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:K(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,Z.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,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(G,{className:`h-3.5 w-3.5`}),` Close`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(He,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,Z.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,Z.jsx)(Wt,{className:`h-5 w-5`})}):null}async function By(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 Vy({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=fy(),o=(0,X.useRef)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await By(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(rn,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,Z.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,Z.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var Hy=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,Uy=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function Wy({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=jo(t),{blobUrl:a}=Lm(e,t.id,256,{enabled:i}),o=bo(t);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-lg 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,Z.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,Z.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,Z.jsx)(ep,{document:t,size:10})}),(0,Z.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,Z.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function Gy(){let e=Yv(),t=Sg(),n=fy(),{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:[];py(p);let _=p?n.snapshotSize??n.camera?.size:null,v=!!_&&_.height>_.width,y=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:b}=n;return(0,X.useEffect)(()=>{p&&b(f)},[p,f,b]),e?.mode===`workspace`?(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:Hy,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:xy.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(Uy,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,Z.jsx)(`input`,{className:K(Uy,`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,Z.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,Z.jsx)(Ce,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y(`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,Z.jsx)(L,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y(`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,Z.jsx)(me,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(Vy,{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,Z.jsxs)(`div`,{className:K(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,v?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[p&&(0,Z.jsx)(Ny,{className:`h-full w-full`,interactive:!0}),p&&(0,Z.jsx)(zy,{}),!p&&(0,Z.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,Z.jsx)(g,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),p&&(0,Z.jsx)(Ry,{className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,Z.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,Z.jsxs)(Z.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,Z.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,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,Z.jsx)(Wy,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,Z.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.`})}function Ky({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=Lm(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-lg border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,Z.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,Z.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,Z.jsx)(rt,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,Z.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,Z.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:ey(e.updatedAt||e.createdAt)})]})]}),(0,Z.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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function qy({autoAdd:e}){let t=Yv(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=ty(t,lo),[c,l]=(0,X.useState)(e?`new`:null),{showErrorToast:u}=to();return t?(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,Z.jsxs)(J,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,Z.jsx)(H,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,Z.jsx)(Ky,{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,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(Og,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var Jy=[{id:`notes`,label:`Notes`,icon:xn,modes:[`context`],description:`All notes in the current context, editable in place`,Component:ay},{id:`todo`,label:`Todos`,icon:On,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:uy},{id:`sketch`,label:`Sketch`,icon:rt,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:qy},{id:`lens`,label:`Lens`,icon:ze,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:Gy}];function Yy(e){return Jy.filter(t=>t.modes.includes(e))}function Xy({target:e,children:t}){return(0,Z.jsx)(Jv.Provider,{value:e,children:t})}function Zy({children:e}){let[t,n]=(0,X.useState)(null),r=(0,X.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,X.useCallback)(()=>n(null),[]),a=(0,X.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,Z.jsxs)(bg.Provider,{value:a,children:[e,(0,Z.jsx)(Xg,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var Qy=`universe`;function $y(){let{appletId:e}=tl(),[t,n]=bu(),r=Jy.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||Qy,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,X.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,X.useState)([]),[f,p]=(0,X.useState)([]);(0,X.useEffect)(()=>{Pr().then(d).catch(()=>d([])),Yo().then(p).catch(()=>p([]))},[]);let[m,h]=(0,X.useState)(o),[g,_]=(0,X.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,Z.jsxs)(`div`,{className:`flex h-viewport flex-col items-center justify-center gap-3 surface-desk`,children:[(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:Jy.map(e=>(0,Z.jsx)(mu,{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,Z.jsx)(Zy,{children:(0,Z.jsx)(Py,{children:(0,Z.jsxs)(`div`,{className:`flex h-viewport flex-col surface-desk p-shell gap-shell`,children:[(0,Z.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,Z.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,Z.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:K(`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,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,Z.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,Z.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,Z.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,Z.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,Z.jsx)(`div`,{className:`grow`}),(0,Z.jsx)(mu,{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,Z.jsx)(Se,{className:`h-3.5 w-3.5`})})]}),(0,Z.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,Z.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,Z.jsx)(Xy,{target:l,children:(0,Z.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})})})}var eb=`false`,tb=`false`,nb=eb===`true`,rb=tb===`true`;function ib(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,nb||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await m(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()},!rb){if(nb)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 ab=new Set,ob=!1,sb=ib({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){ob=!0,ab.forEach(e=>e())}});function cb(e){return ab.add(e),ob&&e(),()=>{ab.delete(e)}}function lb(){sb(!0)}function ub(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>cb(()=>t(!0)),[]),!e||n?null:(0,Z.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>lb(),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,Z.jsx)(Te,{className:`h-3 w-3`}),` Reload`]}),(0,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})})}function db(e){return e.isShared||e.type===`shared`?e.id:e.name}function fb({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=Zc();return(0,Z.jsxs)(`div`,{className:K(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,Z.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,Z.jsx)(Bt,{className:`h-5 w-5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h1`,{className:K(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,Z.jsx)(`p`,{className:K(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,Z.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,Z.jsx)(G,{className:`h-4 w-4`})}),n&&(0,Z.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 pb({className:e}){let t=Zc();return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:K(`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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})}function mb({onBack:e,title:t=`Back`,className:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:K(`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,Z.jsx)(Bt,{className:`h-4 w-4`})})}var hb=180;function gb({x:e,y:t,current:n,onChange:r,onClose:i}){Sf(i);let[a,o]=(0,X.useState)(``),[s,l]=(0,X.useState)([]),[u,d]=(0,X.useState)({q:``,list:[]}),[f,p]=(0,X.useState)(!0),m=(0,X.useRef)(null),h=(0,X.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,X.useEffect)(()=>{m.current?.focus()},[]),(0,X.useEffect)(()=>{let e=!0;return Tf().then(t=>{e&&(l(t),p(!1))}),()=>{e=!1}},[]),(0,X.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{Ef(e).then(t=>{d({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=u.q===_,y=_!==``&&!v,b=(0,X.useMemo)(()=>(_?v?u.list:[]:s).slice(0,hb),[_,v,u.list,s]),x=(0,X.useRef)(null),[S,C]=(0,X.useState)({x:e,y:t});return(0,X.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,yf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,Z.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[Df.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:K(`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,Z.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:K(`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,Z.jsx)(G,{className:`w-3 h-3`})}),(0,Z.jsx)(`label`,{title:`Custom color`,className:K(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!Df.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!Df.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,Z.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,Z.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`}),f||y?(0,Z.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,Z.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:K(`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,Z.jsx)(G,{className:`w-4 h-4`})}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(c,{icon:e,width:18,height:18,color:n.color})},e))]}),!f&&!y&&b.length===0&&(0,Z.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function _b(e,t,n){let r=(0,X.useRef)(n);(0,X.useEffect)(()=>{r.current=n}),(0,X.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 vb({title:e,onClose:t,children:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-lg border bg-card p-4 shadow-elevation-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,Z.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,Z.jsx)(G,{className:`h-4 w-4`})})]}),n]})}function yb({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,X.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=Hf(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsxs)(Du,{className:`relative ${S}`,style:C,children:[(0,Z.jsx)(Ou,{children:(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(ku,{className:`truncate`,children:e.label||e.name}),(0,Z.jsx)(Au,{children:p?`Shared from ${m}`:e.description||``})]}),(0,Z.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>n(db(e)),title:`Stop Workspace`,disabled:d||f,children:(0,Z.jsx)(nn,{className:`h-4 w-4`})}):(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>t(db(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,Z.jsx)(Oe,{className:`h-4 w-4`})}),l&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>r(db(e)),title:`Enter Workspace`,disabled:d||f,children:(0,Z.jsx)(fr,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:`Workspace settings`,"aria-label":`Workspace settings`,disabled:f,children:(0,Z.jsx)(Qt,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,Z.jsx)(J,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,Z.jsx)(xt,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,Z.jsxs)(Zi,{open:s,onOpenChange:c,children:[(0,Z.jsx)(Ua,{asChild:!0,children:(0,Z.jsx)(J,{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,Z.jsx)(lt,{className:`h-4 w-4`})})}),(0,Z.jsxs)(Ya,{children:[(0,Z.jsxs)(mi,{children:[(0,Z.jsx)(Ar,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,Z.jsx)(Li,{children:y?(0,Z.jsxs)(Z.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,Z.jsx)(`br`,{}),(0,Z.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,Z.jsxs)(Z.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,Z.jsxs)(Ka,{children:[(0,Z.jsx)(Ba,{children:`Cancel`}),(0,Z.jsx)(ji,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,Z.jsx)(ju,{children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.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,Z.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,Z.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,Z.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,Z.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 bb(){let[e,t]=bu(),n=e.get(`create`)===`1`,[r,i]=(0,X.useState)(n),[a,o]=(0,X.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,X.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var xb=`canvas:lastPath`,Sb=200;function Cb(){try{let e=localStorage.getItem(xb);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function wb(e){try{localStorage.setItem(xb,JSON.stringify(e))}catch{}}function Tb(e,t,n){if(!e)return;let r=Cb(),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>Sb)for(let e of a.slice(0,a.length-Sb))delete r[e];wb(r)}function Eb(e){let t=Cb()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function Db(e){let t=Eb(e);return t?dv(e,t.path,t.tree):`/workspaces/${e}`}var Ob=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:Ke,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:Le,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:C,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:D,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:me,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:Vn,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:_n,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:Ue,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:Xn,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/auth`,icon:rr,label:`Authentication`,description:`Configure sign-in backends: local passwords, LDAP and IMAP.`},{path:`/admin/embedding`,icon:Vn,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:Tt,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:Ct,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:Ae,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:dt,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:A,label:`About Canvas`,description:`View versions and information about this installation.`}]}],kb=[`/settings`,...Ob.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function Ab(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var jb=[{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.`}],Mb=`canvas:layout`;function Nb(){try{return localStorage.getItem(Mb)===`strip`?`strip`:`classic`}catch{return`classic`}}var Pb=Nb(),Fb=new Set;function Ib(){for(let e of Fb)e()}function Lb(){return Pb}function Rb(e){try{e===`strip`?localStorage.setItem(Mb,e):localStorage.removeItem(Mb)}catch{}Pb=e,Ib()}function zb(e){Fb.add(e);let t=t=>{(t.key===Mb||t.key===null)&&(Pb=Nb(),e())};return window.addEventListener(`storage`,t),()=>{Fb.delete(e),window.removeEventListener(`storage`,t)}}function Bb(){return(0,X.useSyncExternalStore)(zb,Lb,()=>`classic`)}var Vb=[{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.`}],Hb=`canvas:layout-nav`;function Ub(){try{let e=localStorage.getItem(Hb);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var Wb=Ub(),Gb=new Set;function Kb(){return Wb}function qb(e){try{e===`shift`?localStorage.removeItem(Hb):localStorage.setItem(Hb,e)}catch{}Wb=e;for(let e of Gb)e()}function Jb(e){Gb.add(e);let t=t=>{(t.key===Hb||t.key===null)&&(Wb=Ub(),e())};return window.addEventListener(`storage`,t),()=>{Gb.delete(e),window.removeEventListener(`storage`,t)}}function Yb(){return(0,X.useSyncExternalStore)(Jb,Kb,()=>`shift`)}function Xb(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}}var Zb=(0,X.createContext)(null);function Qb(){let e=(0,X.useContext)(Zb);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function $b(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`||kb.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function ex(e,t){let n=Jc(),r=Zc(),i=(0,X.useRef)(!1),a=(0,X.useRef)(e);return(0,X.useEffect)(()=>{a.current=e},[e]),(0,X.useEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=$b(n.pathname);if(e===null&&n.pathname!==`/`&&Lb()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=window.matchMedia(`(max-width: 767px)`).matches&&Lb()!==`strip`;t({type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,t]),{navigateToEntity:(0,X.useCallback)(e=>{i.current=!0,r(e)},[r])}}function tx(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=$a(Qr.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 nx=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function rx(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await Vi(e,`/${n}`,!0,a);let t=Pf(`/${n}`);t&&await Ca(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return fa(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function ix(){let[e,t]=(0,X.useState)(new Set),[n,r]=(0,X.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 ax({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,Z.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:nx.map(n=>{let r=Of[n.toLowerCase()];return(0,Z.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,Z.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,Z.jsx)(c,{icon:r.icon,width:16,height:16,color:r.color}),(0,Z.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var ox=[{value:`full`,icon:Mn,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:hr,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 sx({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,Z.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:ox.map(i=>{let a=e===i.value,o=i.icon;return(0,Z.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,Z.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,Z.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,Z.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function cx(){let[e,t]=(0,X.useState)(`full`),[n,r]=(0,X.useState)(!1);return(0,X.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 lx(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 ux(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function dx(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 fx(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.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 px(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(zf()),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(``),[_,v]=cx(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=bb(),D=ix(),[O,k]=(0,X.useState)(!1),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(!1),[P,F]=(0,X.useState)(null),{showToast:I}=po(),ee=Zc(),te=km(),{openM2Drawer:ne}=Qb(),re=tx();_b(re,`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))}),(0,X.useEffect)(()=>{(async()=>{try{r(!0);let e=await Pr();t(lx(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),I({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}})()},[re,I]);let ie=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await za({name:o,description:l||void 0,color:d,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),D.selected.size>0){try{await ui(e.name);let{ok:t,failed:n}=await rx(e.name,Array.from(D.selected),D.tree);n&&I({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),I({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}D.setSelected(new Set)}s(``),u(``),f(zf()),m(null),g(``),I({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),E(!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`}I({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},L=async e=>{if(e.preventDefault(),P)try{let e={label:P.label,description:P.description,color:P.color,icon:P.icon??null};await La(P.name,e),t(t=>t.map(t=>t.id===P.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),I({title:`Success`,description:`Workspace '${P.label}' details updated.`}),F(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;I({title:`Error`,description:t,variant:`destructive`})}},R=e=>{F(e)},ae=async e=>{try{await Qa(e.name),t(t=>t.filter(t=>t.id!==e.id)),I({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;I({title:`Error`,description:t,variant:`destructive`})}},oe=async e=>{try{let n=await ui(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),I({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`}I({title:`Error`,description:t,variant:`destructive`})}},se=async e=>{try{let n=await Cr(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),I({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`}I({title:`Error`,description:t,variant:`destructive`})}},ce=e=>{ee(Db(e))},{rowProps:z,handleProps:le,draggingIndex:ue,insertLineClass:de}=fx((n,r)=>{let i=ux(e,n,r);t(i),dx(i,(e,t)=>La(db(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&I({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(fb,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{variant:`outline`,onClick:()=>k(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>j(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,Z.jsx)(J,{variant:`outline`,onClick:()=>N(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!T&&(0,Z.jsxs)(J,{onClick:()=>E(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,Z.jsx)(H,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),T&&(0,Z.jsx)(vb,{title:`Create New Workspace`,onClose:()=>E(!1),children:(0,Z.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,Z.jsx)(q,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.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,Z.jsx)(c,{icon:p||`ph:stack-fill`,width:22,height:22,color:Hf(d)})}),(0,Z.jsx)(q,{id:`workspace-color`,type:`color`,value:d,onChange:e=>f(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>f(zf()),disabled:C,children:`Randomize`})]}),y&&(0,Z.jsx)(gb,{x:y.x,y:y.y,current:{icon:p??void 0,color:d},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&f(e.color)},onClose:()=>b(null)}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,Z.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,Z.jsx)(sx,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.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,Z.jsx)(ax,{selected:D.selected,onToggle:D.toggle,tree:D.tree,onTreeChange:D.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,Z.jsxs)(J,{type:`submit`,disabled:C||!o.trim(),children:[(0,Z.jsx)(H,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),O&&(0,Z.jsx)(hx,{}),M&&(0,Z.jsx)(gx,{onClose:()=>N(!1),onChanged:async()=>{try{t(lx(await Pr()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),A&&(0,Z.jsx)(mx,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),j(!1)},onClose:()=>j(!1)}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,Z.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=Hf(t.color);return(0,Z.jsxs)(`div`,{...z(n),className:`flex items-stretch rounded-lg ${de(n,e.length)||``} ${ue===n?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,...le(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,Z.jsx)(Je,{className:`h-4 w-4 ${Uf(i)}`})}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(yb,{workspace:r,onStart:oe,onStop:se,onEnter:ce,onEdit:R,onSettings:e=>{te?ne(`workspaces`,`settings`,db(e)):ee(`/workspaces/${db(e)}/settings/general`)},onDestroy:ae})})]},t.id)})})]}),P&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,P.label]}),(0,Z.jsxs)(`form`,{onSubmit:L,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-label`,value:P.label,onChange:e=>F(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`edit-description`,value:P.description||``,onChange:e=>F(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.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,Z.jsx)(c,{icon:P.icon||`ph:stack-fill`,width:22,height:22,color:Hf(P.color)})}),(0,Z.jsx)(q,{id:`edit-workspace-color`,type:`color`,value:P.color||`#FFFFFF`,onChange:e=>F(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>F(e=>e?{...e,color:zf()}:null),children:`Randomize Color`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:!P.label?.trim(),children:`Save Changes`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>F(null),children:`Cancel`})]})]}),x&&(0,Z.jsx)(gb,{x:x.x,y:x.y,current:{icon:P.icon??void 0,color:P.color??void 0},onChange:e=>{F(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 mx({onImported:e,onClose:t}){let{showToast:n}=po(),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``);return(0,Z.jsx)(vb,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,Z.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}c(!0),u(`Starting…`);try{let t=await Ma(i,a.trim(),e=>{u(ga[e.phase]||e.phase)});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{c(!1),u(``)}},className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:s}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:s}),(0,Z.jsx)(J,{type:`submit`,disabled:s||!r.trim()||!a.trim(),children:s?`Importing…`:`Import Workspace`})]}),s&&l&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:l}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,Z.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 hx(){let{showToast:e}=po(),[t,n]=(0,X.useState)(``),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,Z.jsx)(q,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,Z.jsx)(J,{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,Z.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 gx({onClose:e,onChanged:t}){let{showToast:n}=po(),r=Zc(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)([]),f=(0,X.useCallback)(async()=>{try{d(await ha())}catch{d([])}},[]);(0,X.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 ya(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 fi(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,Z.jsxs)(vb,{title:`Open a remote Workspace`,onClose:e,children:[(0,Z.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,Z.jsx)(J,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,Z.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,Z.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,Z.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,Z.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}function _x({workspaceName:e,children:t}){let n=e,[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a,s=async()=>{let s=++r;try{let c=await wi(e);!t&&s===r&&(a=c.id,i({identity:n,active:c.status===`active`}),o(``))}catch(e){!t&&s===r&&(i({identity:n,active:!1}),o(e instanceof Error?e.message:`Unable to check workspace status`))}},c=t=>{let o=t.detail?.refs;!o?.includes(e)&&!(a&&o?.includes(a))||(r++,i({identity:n,active:!1}))};s(),window.addEventListener(`workspaces:refresh`,s),window.addEventListener(`workspace:stopped`,c),window.addEventListener(`focus`,s);let l=window.setInterval(s,5e3);return()=>{t=!0,window.clearInterval(l),window.removeEventListener(`workspaces:refresh`,s),window.removeEventListener(`workspace:stopped`,c),window.removeEventListener(`focus`,s)}},[e,n,l]),r?.identity===n?r.active?t:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:`Workspace stopped`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to view its content.`}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(J,{disabled:s,onClick:async()=>{c(!0),o(``);try{await ui(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?`Starting…`:`Start workspace`}),(0,Z.jsx)(mu,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]}):(0,Z.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`})}function vx({workspaceId:e,workspaceName:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,X.useEffect)(()=>{let t=!1,n=!1,i=!1,a=async()=>{if(n){i=!0;return}n=!0;try{let n=await wa(e);t||r(n.filter(e=>e.resyncing))}catch{}finally{n=!1,i&&!t&&(i=!1,a())}},o=t=>{t.workspaceId===e&&a()};a();let s=setInterval(()=>{a()},3e3);return Xu.on(`backend.resync.changed`,o),()=>{t=!0,clearInterval(s),Xu.off(`backend.resync.changed`,o)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,Z.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,Z.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Mt,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,Z.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,Z.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,Z.jsx)(G,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,Z.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,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:i}),(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,Z.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,Z.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 yx(){let{openAddPicker:e}=xs();return(0,Z.jsx)(`button`,{type:`button`,onClick:e,title:`Add here`,"aria-label":`Add`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-full bg-foreground text-background hover:opacity-90 transition-opacity`,children:(0,Z.jsx)(H,{className:`w-4 h-4`})})}function bx({count:e}){return e<=0?null:(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>window.dispatchEvent(new CustomEvent(`workspace:documents:link-selection`)),title:`Link ${e} selected document(s) to…`,"aria-label":`Link selection`,className:`shrink-0 flex items-center justify-center gap-1 h-7 min-w-7 rounded-full bg-info px-1.5 text-info-foreground hover:bg-info transition-colors touch-target`,children:[(0,Z.jsx)(Gt,{className:`w-3.5 h-3.5`}),(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold leading-none`,children:e})]})}function xx({urlType:e,urlDisplay:t,onUrlClick:n,onUrlSubmit:r}){let i=t.match(/^(.*?:\/\/)(.*)$/),a=i?.[1]??``,o=i?.[2]??t,s=(0,X.useRef)(null);(0,X.useEffect)(()=>{s.current&&(s.current.value=o)},[o]);let c=(0,Z.jsxs)(`span`,{className:`font-mono text-xs px-1.5 py-0.5 rounded bg-muted border text-muted-foreground shrink-0`,children:[`[`,e.replace(`-`,`:`),`]`]}),l=n?(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:`Browse tree`,"aria-label":`Browse tree`,className:`shrink-0 flex items-center gap-1 rounded hover:opacity-80 transition-opacity`,children:[(0,Z.jsx)(Mn,{className:`w-3.5 h-3.5 text-muted-foreground`}),c]}):c;return r?(0,Z.jsxs)(`div`,{className:`flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full border border-transparent bg-muted/60 px-3 transition-colors hover:bg-muted focus-within:border-border focus-within:bg-background focus-within:shadow-elevation-1`,children:[l,(0,Z.jsxs)(`form`,{className:`flex flex-1 min-w-0 items-center`,onSubmit:e=>{e.preventDefault(),r(s.current?.value??o)},children:[a&&(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-sm text-muted-foreground select-none`,children:a}),(0,Z.jsx)(`input`,{ref:s,type:`text`,defaultValue:o,onKeyDown:e=>{e.key===`Escape`&&s.current&&(s.current.value=o)},spellCheck:!1,autoComplete:`off`,title:`Edit path; press Enter to go`,className:`w-full min-w-0 flex-1 truncate bg-transparent px-1 py-1 font-mono text-sm text-foreground focus:outline-none`})]})]}):(0,Z.jsxs)(`div`,{className:`flex h-9 min-w-0 flex-1 items-center gap-2 rounded-full bg-muted/60 px-3`,children:[l,n?(0,Z.jsx)(`button`,{type:`button`,onClick:n,title:`Browse tree`,className:`flex-1 truncate rounded px-1 -mx-1 text-left text-sm text-foreground transition-colors hover:bg-accent active:bg-accent`,children:t}):(0,Z.jsx)(`span`,{className:`text-sm text-foreground truncate flex-1`,children:t})]})}function Sx({urlType:e,urlDisplay:t,contextPath:n,treeName:r,workspaceId:i,documents:a,isLoading:o,totalCount:s,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,canvasInfo:E,isCanvasPinned:D,onTogglePinCanvas:O,onSaveAsCanvas:A,onShareCanvas:j,onUnshareCanvas:M,onDeleteCanvas:N,isSharingCanvas:P,isDeletingCanvas:F,isCanvasShared:I,isCanvasLocked:ee,backendSearchQueries:te,onBackendSearch:re,onRemoveBackendQuery:ie,serverSort:L,onServerSortChange:R,scope:ae,onScopeChange:oe,canSaveChanges:se,isSavingChanges:ce,onSaveChanges:z,onUrlClick:le,onUrlSubmit:de,linkTree:fe,selectedCount:pe=0,children:me,contentBanner:ge,folders:_e,onOpenFolder:ve}){let ye=e===`canvas`;return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0 bg-background`,children:[ye&&E?(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[E.color&&(0,Z.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:E.color}}),(0,Z.jsx)($n,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:E.label||t.split(`://`)[1]||`Canvas`}),E.description&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:E.description})]}),se&&z&&(0,Z.jsxs)(`button`,{type:`button`,onClick:z,disabled:ce,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,Z.jsx)(k,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:ce?`Saving...`:`Save filters`})]}),O&&(0,Z.jsxs)(`button`,{type:`button`,onClick:O,"aria-pressed":!!D,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:D?`Unpin from home`:`Pin to home`,children:[D?(0,Z.jsx)(ue,{className:`w-3 h-3`}):(0,Z.jsx)(ne,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:D?`Unpin`:`Pin`})]}),j&&(0,Z.jsxs)(`button`,{type:`button`,onClick:j,disabled:P||F,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:I?`Copy public link`:`Share canvas`,children:[(0,Z.jsx)(_n,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:P?`Sharing...`:I?`Copy link`:`Share`})]}),I&&M&&(0,Z.jsxs)(`button`,{type:`button`,onClick:M,disabled:P||F,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,Z.jsx)(he,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),N&&(0,Z.jsxs)(`button`,{type:`button`,onClick:N,disabled:F||ee&&!I,title:ee&&!I?`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,Z.jsx)(lt,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:F?`Deleting…`:`Delete`})]}),(0,Z.jsx)(bx,{count:pe}),(0,Z.jsx)(yx,{})]}):(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-4 py-2.5 border-b bg-muted/20 shrink-0`,children:[(0,Z.jsx)(xx,{urlType:e,urlDisplay:t,onUrlClick:le,onUrlSubmit:de}),A&&(0,Z.jsxs)(`button`,{type:`button`,onClick:A,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:`Save as canvas`,children:[(0,Z.jsx)(vn,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Save as canvas`})]}),(0,Z.jsx)(bx,{count:pe}),(0,Z.jsx)(yx,{})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[ge,me||(0,Z.jsx)(N_,{documents:a,isLoading:o,folders:_e,onOpenFolder:ve,contextPath:n,treeName:r,workspaceId:i,totalCount:s,viewMode:`table`,allowViewToggle:!0,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,backendSearchQueries:te,onBackendSearch:re,serverSort:L,onServerSortChange:R,onRemoveBackendQuery:ie,scope:ae,onScopeChange:oe,canSaveChanges:!ye&&se,isSavingChanges:ce,onSaveChanges:z,linkTree:fe})]})]})}var Cx=[{id:`todos`,label:`Todos`},{id:`notes`,label:`Notes`}],wx={id:`default`,name:`All`,kind:`documents`};function Tx(){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 Ex(e){let t=e?.views;if(!Array.isArray(t))return[wx];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`&&Cx.some(e=>e.id===t.app)});return n.length>0?n:[wx]}function Dx({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let c=o?(Bf(o)??0)>.5?`text-black`:`text-white`:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),y=()=>{g(null),v(null)},b=()=>{if(h&&_&&h!==_.id){let t=e.find(e=>e.id===h),n=e.filter(e=>e.id!==h),i=n.findIndex(e=>e.id===_.id);t&&i>=0&&(n.splice(_.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!l)return;let t=d.trim();t&&r(e.map(e=>e.id===l?{...e,name:t}:e)),u(null)},S=(t,n)=>{m(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?Cx.find(e=>e.id===n)?.label??`App`:`View ${e.length+1}`,o=t===`columns`?{id:i,name:a,kind:t,columns:Tx()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),u(i),f(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[wx],n===t?i[0]?.id??wx.id:void 0)};return(0,Z.jsxs)(`div`,{className:K(`flex min-w-0 items-end`,a),children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 items-end gap-0.5 overflow-x-auto pt-1`,children:e.map(r=>{let a=r.id===t;return l===r.id?(0,Z.jsx)(`input`,{autoFocus:!0,value:d,onChange:e=>f(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&u(null)},className:`relative z-[1] h-8 w-28 rounded-t-md border border-b-0 border-input bg-background px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`},r.id):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(r.id),onDoubleClick:()=>{i||(u(r.id),f(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`,g(r.id)},onDragOver:e=>{if(!h||h===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;v(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:K(`group flex h-8 shrink-0 items-center gap-1.5 rounded-t-md px-3 text-xs transition-colors`,a?K(`relative z-[1] border border-b-0 font-medium`,o?c:`border-border bg-background text-foreground`):`mb-[3px] border border-b-0 border-transparent bg-muted/40 text-muted-foreground hover:bg-accent/60 hover:text-foreground`,h===r.id&&`opacity-50`,_?.id===r.id&&(_.before?`border-l-2 border-l-primary`:`border-r-2 border-r-primary`)),style:a&&o?{backgroundColor:o,..._?.id===r.id?{}:{borderColor:o}}:void 0,children:[r.kind===`columns`?(0,Z.jsx)(P,{className:`h-3 w-3 shrink-0`}):r.kind===`app`?r.app===`todos`?(0,Z.jsx)(On,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(xn,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(ht,{className:`h-3 w-3 shrink-0`}),(0,Z.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,Z.jsx)(ce,{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,Z.jsx)(G,{className:K(`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&&(p?(0,Z.jsxs)(`span`,{className:`relative z-[1] mb-1.5 ml-1 flex shrink-0 items-center gap-1`,children:[!e.some(e=>e.id===wx.id)&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{m(!1),r([{...wx},...e],wx.id)},className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(ht,{className:`h-3 w-3`}),` All`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(ht,{className:`h-3 w-3`}),` List`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(P,{className:`h-3 w-3`}),` Board`]}),Cx.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[e.id===`todos`?(0,Z.jsx)(On,{className:`h-3 w-3`}):(0,Z.jsx)(xn,{className:`h-3 w-3`}),` `,e.label]},e.id)),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,Z.jsx)(G,{className:`h-3 w-3`})})]}):(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!0),title:`Add view`,"aria-label":`Add view`,className:`relative z-[1] mb-1.5 ml-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,Z.jsx)(H,{className:`h-3.5 w-3.5`})}))]})}var Ox=`data/schema/note`;function kx(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null);(0,X.useEffect)(()=>{let o=!1;return Si(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,X.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,X.useCallback)(()=>s(e=>e+1),[])}}function Ax({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=kx(e,t,n,uo,`tasks`),[o,s]=(0,X.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,Z.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,Z.jsx)(ov,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function jx({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i}=kx(e,t,n,Ox);return(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto p-4`,children:(0,Z.jsx)(N_,{documents:r,isLoading:i,contextPath:n,treeName:t,workspaceId:e,totalCount:r.length,viewMode:`card`})})}function Mx({app:e,...t}){return e===`todos`?(0,Z.jsx)(Ax,{...t}):(0,Z.jsx)(jx,{...t})}var Nx=[{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 Px(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function Fx({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)({}),p=(0,X.useRef)(null),[m,h]=(0,X.useState)(!1),g=(0,X.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,X.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=Nx.filter(e=>!n.some(t=>t.id===e.id));return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.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=>Px(e,t.schemas)).filter(e=>{if(!a)return!0;let t=bo(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,Z.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-lg 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,Z.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,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,Z.jsx)(`span`,{className:`flex-1`}),!i&&(0,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`div`,{className:`px-3 pb-2`,children:(0,Z.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,Z.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=bo(e);return(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(ep,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,Z.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,Z.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,Z.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,Z.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,Z.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,Z.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,Z.jsx)(H,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,Z.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,Z.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,Z.jsx)(Ye,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,Z.jsx)(Xg,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var Ix=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function Lx(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function Rx(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>Rx(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:Lx(e)}];let r=Ix(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:Lx(e)}))}function zx(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 Bx(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 Vx(e,t,n=new Map){let r=Ix(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:Lx(n)}],ids:zx(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...Rx(r.context,`context`,n),...Rx(r.directory,`directory`,n)],a=Ix(r.changed);a&&i.push(...Rx(a.context,`context`,n),...Rx(a.directory,`directory`,n));let o=zx(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 Hx(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function Ux(e,t){return e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree?!1:Hx(e.path,t.path)}function Wx(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>Ux(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 Gx=(0,X.createContext)(null);function Kx(){let e=(0,X.useContext)(Gx);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function qx(e,t,n={}){return Xu.request(Iu,{workspace:e,specs:t,opts:n})}function Jx(e,t,n){return Xu.request(Lu,{sessionId:e,label:t,spec:n})}function Yx(e){return Xu.request(Ru,{sessionId:e})}function Xx(e,t={}){return Xu.request(zu,{sessionId:e,...t})}function Zx(e){return Xu.request(Bu,{sessionId:e})}function Qx(e){return Xu.on(Vu,e)}var $x=100;function eS({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),f=(0,X.useRef)([]),p=(0,X.useRef)(new Map),m=(0,X.useRef)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(null),_=(0,X.useRef)({}),v=(0,X.useRef)(null),y=(0,X.useMemo)(()=>JSON.stringify(t),[t]),b=(0,X.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,X.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,X.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=$x){let i=e.slice(r,r+$x),a=await Ki(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,X.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]),w=(0,X.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,X.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await qx(e,JSON.parse(y),JSON.parse(b));if(t){Zx(r.sessionId).catch(()=>{});return}n=r.sessionId,m.current=r.sessionId,l(r.sessionId),d(null),f.current=[],p.current=new Map,await w(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=Xu.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&Zx(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,X.useEffect)(()=>{if(!c)return;let e=Qx(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):w(e.ids,e.count)}});return()=>{e?.()}},[c,C,w]);let T=(0,X.useCallback)(async()=>{let e=m.current;if(e)try{let t=await Yx(e);await w(t.ids,t.count)}catch{}},[w]),E=(0,X.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await Jx(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await w(r.ids,r.count)},[w]),D=(0,X.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 T();return}let r=await Xx(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,T]);(0,X.useEffect)(()=>{v.current=D},[D]);let O=(0,X.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await Xx(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 Jx(r,e,{ids:i.ids});return await w(a.ids,a.count),i.ids},[w]);return{documents:i,count:o,ready:c!==null,error:u,setCue:E,resync:T,rank:D,rankAndPin:O}}var tS=`canvas:query-debug`,nS=`canvas:query-debug-changed`;function rS(){try{return localStorage.getItem(tS)===`1`}catch{return!1}}function iS(e){try{e?localStorage.setItem(tS,`1`):localStorage.removeItem(tS)}catch{}window.dispatchEvent(new CustomEvent(nS,{detail:e}))}function aS(){let[e,t]=(0,X.useState)(rS);return(0,X.useEffect)(()=>{let e=()=>t(rS());return window.addEventListener(nS,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(nS,e),window.removeEventListener(`storage`,e)}},[]),e}function oS({data:e,className:t}){let[n,r]=(0,X.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,X.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,Z.jsxs)(`div`,{className:K(`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,Z.jsxs)(`div`,{className:K(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,Z.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,Z.jsx)(Ge,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5`}),`Query debug`,(0,Z.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,Z.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,Z.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,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.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,Z.jsxs)(Z.Fragment,{children:[` A jump at `,(0,Z.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,Z.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,Z.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,Z.jsx)(`tbody`,{children:i.map((e,t)=>(0,Z.jsxs)(`tr`,{className:K(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,Z.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,Z.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,Z.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,Z.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,Z.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 sS(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 cS=new Map;function lS(e,t,n){return`${e}\0${t}\0${n}`}function uS(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${lS(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function dS(e,t,n){let r=lS(e,t,n);for(let e of cS.keys())e.startsWith(r)&&cS.delete(e)}function fS(e,t){let n=`${e}\0`;for(let[e,r]of cS){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);Wx(t,{tree:i,kind:ba(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&cS.delete(e)}}function pS(e,t){if(!t?.treeName)return;let n=t.workspaceName??e,r=t.path?lS(n,t.treeName,t.path):`${n}\0${t.treeName}\0`;for(let e of cS.keys())e.startsWith(r)&&cS.delete(e)}function mS(){let{workspaceName:e}=tl();return e?(0,Z.jsx)(_x,{workspaceName:e,children:(0,Z.jsx)(hS,{})}):null}function hS(){let{workspaceName:e,treeName:t}=tl(),n=Jc(),r=Zc(),{showToast:i}=po(),a=new URLSearchParams(n.search),o=(()=>{let e=a.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(a.get(`search`)||``).trim();return t?[t]:[]})(),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!0),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(0),v=aS(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(v);x!==v&&(S(v),v||b(null));let[C,w]=(0,X.useState)(`path`),[T,E]=(0,X.useState)(!1),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(``),[N,P]=(0,X.useState)(!1),[F,I]=(0,X.useState)(!1),[ee,te]=(0,X.useState)(!1),[ne,re]=(0,X.useState)(null),[ie,L]=(0,X.useState)(1),[R,ae]=(0,X.useState)(50),[oe,se]=(0,X.useState)(o),[ce,z]=(0,X.useState)(null),{state:le,saveFilters:ue,toggleView:de,setSort:fe,setAccentColor:pe,setMapDocuments:me,hasActiveFilters:he}=xs(),ge=le.filters.features.allOf,_e=le.filters.features.anyOf,ve=le.filters.features.noneOf,ye=Oy(le.filters.timeline),B=Ty(le.filters.geo),be=Ey(le.filters.lens,le.filters.geo.includeUnlocated),V=le.filters.lens.ids,xe=[...ye,...B,...be],H=le.filters.sort??Cy,Se=JSON.stringify({a:ge,b:_e,c:ve,d:xe,i:V,s:H}),Ce=JSON.stringify({a:ge,b:_e,c:ve,d:xe,s:H}),U=uv(n.pathname).path,W=t??`context`,we=W===`backends`,[Te,Ee]=(0,X.useState)([]);(0,X.useEffect)(()=>{!we||!e||wa(e).then(Ee).catch(()=>Ee([]))},[we,e]);let De=we?Aa(U,Te):null,[Oe,ke]=(0,X.useState)(!1),Ae=`${W}\0${U}`,[je,Me]=(0,X.useState)(Ae);je!==Ae&&(Me(Ae),ke(!1));let G=a.get(`layer`)===`1`,Ne=a.get(`layerId`)||null,[Pe,Fe]=(0,X.useState)(null),[Ie,Le]=(0,X.useState)(null),Re=(0,X.useRef)(null);(0,X.useEffect)(()=>{Re.current=Ie},[Ie]);let[ze,Be]=(0,X.useState)(`left`),[Ve,He]=(0,X.useState)([]),{openM2Drawer:Ue}=Qb(),We=km(),[Ge,Ke]=(0,X.useState)([]),qe=(0,X.useMemo)(()=>{if(!Pe||U===`/`||G)return null;let e=U.split(`/`).filter(Boolean),t=Pe;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Pe,U,G]),Je=qe?.type===`canvas`?`canvas`:null,Ye=(0,X.useRef)(null);(0,X.useEffect)(()=>{!e||!Pe||G||Ye.current===`${e}/${W}`&&(U!==`/`&&!qe||Tb(e,W,U))},[e,Pe,G,U,qe,W]);let Xe=(0,X.useMemo)(()=>G||C===`workspace`||oe.length>0||ba(W)!==`directory`?[]:sS(Pe,U),[Pe,U,W,G,C,oe]),Ze=G?null:U===`/`?Pe:qe,$e=`${W}\0${U}`,[et,tt]=(0,X.useState)(null),nt=et?.key===$e?et.views:Ex(Ze?.metadata),rt=et?.key===$e?et.activeId:nt[0]?.id??wx.id,it=nt.find(e=>e.id===rt)??nt[0]??wx,at=e=>tt({key:$e,views:nt,activeId:e}),ot=(t,n)=>{tt({key:$e,views:t,activeId:n??rt}),Ca(e,U,{metadata:{...Ze?.metadata??{},views:t}},W).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},st=Je===`canvas`&&typeof qe?.querySpec?.query==`string`?qe.querySpec.query:``,ct=Je===`canvas`?{label:qe?.label,description:qe?.description,color:qe?.color}:null,{isPinned:lt,pin:ut,unpin:dt,pins:ft}=Kx(),pt=s?.name,mt=(0,X.useMemo)(()=>pt&&Je===`canvas`&&!G?{workspaceName:pt,treeName:W,path:U}:null,[pt,Je,G,W,U]),ht=mt?lt(mt):!1,gt=qe?.id,_t=qe?.label,vt=(0,X.useCallback)(async()=>{if(mt)try{let e=ft.find(e=>e.workspaceName===mt.workspaceName&&e.treeName===mt.treeName&&e.path===mt.path);e?await dt(e.id):await ut({...mt,layerId:gt,label:_t})}catch(e){console.error(`Failed to update home pins:`,e)}},[mt,ft,ut,dt,gt,_t]),yt=e?`${e}://${U===`/`?``:U.replace(/^\//,``)}`:``,bt=Hf(s?.color)||null;(0,X.useEffect)(()=>(pe(bt),()=>pe(null)),[bt,pe]);let xt=(0,X.useCallback)(async t=>{let n=V;if(t?.anyOf?.length&&_e.length&&(n=((await Si(e,U,W,{limit:0,anyOf:_e,ids:V,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await Si(e,U,W,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...ge,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:_e,noneOf:ve,filters:xe,ids:n,queries:[...oe,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,U,W,Se,oe]);(0,X.useEffect)(()=>{e&&(async()=>{d(!0);try{let t=await Y.get(`${Qr.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,X.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 St=(V?.length??0)>0&&!G&&!(Oe&&De)&&oe.length<=1,{documents:Ct,count:wt,ready:Tt,setCue:Et,resync:Dt,rank:Ot}=eS({workspaceRef:e,specs:(0,X.useMemo)(()=>{let e={features:{allOf:ge,anyOf:_e,noneOf:ve},filters:xe};return C!==`workspace`&&(ba(W)===`directory`?e.directory={tree:W,path:U}:e.context=U),[{label:`scope`,spec:e}]},[Ce,U,W,C]),opts:(0,X.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:St}),kt=St&&Tt,At=(0,X.useRef)(!1);(0,X.useEffect)(()=>{At.current=kt},[kt]);let jt=oe.length===1?oe[0].trim():``;(0,X.useEffect)(()=>{Tt&&Ot(jt?{text:jt}:null,{limit:R,offset:(ie-1)*R}).catch(()=>{})},[Tt,jt,R,ie,Ot]);let Mt=(V??[]).join(`,`);(0,X.useEffect)(()=>{Tt&&Et(`lens`,{ids:V??[]}).catch(()=>{})},[Tt,Mt,Et,V]);let Nt=kt?Ct:f,Pt=kt?wt:g,Ft=(0,X.useRef)(new Set);(0,X.useEffect)(()=>{Ft.current=new Set(Nt.map(e=>Number(e.id)))},[Nt]);let It=le.geoSelection;(0,X.useEffect)(()=>{me(Nt,s?.name??null)},[Nt,s?.name,me]),(0,X.useEffect)(()=>()=>me([]),[me]);let Lt=(0,X.useMemo)(()=>It?Nt.filter(e=>Gg(e,It,le.filters.geo.includeUnlocated)):Nt,[Nt,It,le.filters.geo.includeUnlocated]),Rt=(0,X.useRef)(0),zt=(0,X.useRef)(``),Bt=(0,X.useCallback)(async t=>{if(!e||At.current)return;let n=++Rt.current,r=Oe&&De?`${C}:unfiled`:C,a=(V?.length??0)>0,o=uS(e,W,U,ie,R,oe.join(`␟`),Ce,G&&Ne?Ne:``,r),s=a&&o===zt.current;zt.current=o;let c=uS(e,W,U,ie,R,oe.join(`␟`),Se,G&&Ne?Ne:``,r),l=a||v?void 0:cS.get(c);if(l){p(l.documents),_(l.totalCount),h(!1);return}(t?.silent??s)||h(!0);try{let t;t=Oe&&De?await Wi(e,De.driver,De.address,{linked:!1,limit:R,offset:(ie-1)*R}):G&&Ne&&C!==`workspace`?await Fa(e,W,Ne,{limit:R,page:ie,queries:oe,allOf:ge,anyOf:_e,noneOf:ve,filters:xe,ids:V,sortBy:H.sortBy||void 0,order:H.order}):await Ki(e,U,ge,{limit:R,page:ie,treeName:W,treeType:W===`directory`||W===`backends`?`directory`:`context`,queries:oe,anyOf:_e,noneOf:ve,filters:xe,ids:V,sortBy:H.sortBy||void 0,order:H.order,scope:C,debug:v&&oe.length>0,debugLimit:200});let r=t.payload||[],i=t.totalCount||t.count||0;if(a||cS.set(c,{documents:r,totalCount:i}),n!==Rt.current)return;let o=t.debug,l=o?.imageDistances??o?.distances??null;b(l?{query:oe[oe.length-1]??``,distances:l}:null),p(s?e=>e.length===r.length&&e.every((e,t)=>e.id===r[t].id)?e:r:r),_(i)}catch(e){if(n!==Rt.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),p([]),_(0)}finally{n===Rt.current&&h(!1)}},[e,U,W,Ne,G,ie,R,s?.status,oe,Se,C,Oe,v]);(0,X.useEffect)(()=>{Bt()},[Bt]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Le({treeName:n.treeName||`context`,path:cv(n.path||`/`)}),Be(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,W,U]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(e&&pS(e,n),!(n?.treeName&&n.treeName!==W)&&(n?.path&&n.path!==U||(e&&dS(e,W,U),Bt({silent:!0}))))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[Bt,e,U,W]);let Vt=s?.name,Ht=s?.id;(0,X.useEffect)(()=>{if(!e||!Vt&&!Ht)return;let t=[Vt,Ht].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>Xu.emit(`subscribe`,{channel:e}));n();let r=Xu.on(`connect`,n),i=new Map,a=!1,o=()=>{Lr(e).then(e=>{a||(i=Bx(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,At.current){Dt();return}Bt({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=Vx(t,n,i);fS(e,r);let a={tree:W,kind:ba(W),path:U,wholeWorkspace:C===`workspace`},f=Re.current;f&&Wx(r,{tree:f.treeName,kind:ba(f.treeName),path:f.path})&&(u=f),Wx(r,a,Ft.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`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])=>Xu.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>Xu.off(e,t))}},[e,Ht,Vt,W,U,C,Bt,Dt]);let Ut=`${U}\0${W}\0${Ne??``}\0${C}`,[Wt,Gt]=(0,X.useState)(Ut);Wt!==Ut&&(Gt(Ut),L(1),z(null));let Kt=`${U}\0${W}\0${Ne??``}`,[qt,Jt]=(0,X.useState)(Kt);qt!==Kt&&(Jt(Kt),w(`path`));let Yt=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;M(n),A({parentPath:e,captureView:t})},Xt=a.get(`createCanvas`)===`1`,[Zt,Qt]=(0,X.useState)(!1);Zt!==Xt&&(Qt(Xt),Xt&&Yt(U,!1)),(0,X.useEffect)(()=>{if(!Xt)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}`,{replace:!0})},[Xt,U]);let $t=(0,X.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.pathname,n.search,r]),en=o.join(`␟`),[tn,nn]=(0,X.useState)(en);tn!==en&&(nn(en),se(o),L(1));let rn=`${en}\0${Je??``}\0${st}\0${U}\0${ce??``}`,[an,on]=(0,X.useState)(rn);an!==rn&&(on(rn),o.length>0||Je!==`canvas`||ce===U||(se(st?[st]:[]),L(1)));let sn=(0,X.useCallback)(e=>{let t=e.trim();t&&(z(null),se(e=>{if(e.includes(t))return e;let n=[...e,t];return $t(n),L(1),n}))},[$t,z,se,L]),cn=(0,X.useCallback)(e=>{se(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&z(U),$t(n),L(1),n})},[$t,U,z,se,L]),ln=oe.join(` `).trim(),un=!!le.activeContextType&&(le.isDirty||ln!==(Je===`canvas`?st:le.savedSearchQuery||``));!e&&Pe!==null&&Fe(null),(0,X.useEffect)(()=>{let t=!1;if(!e)return;let n=(n=!1)=>{n&&fa(e,W),vi(e,W,{force:n}).then(n=>{t||(Ye.current=`${e}/${W}`,Fe(n))}).catch(()=>{t||Fe(null)})};n(!1);let r=t=>{let r=t.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==W||n(!0)};window.addEventListener(`workspace:tree:refresh`,r);let i=null,a=()=>{i&&clearTimeout(i),i=setTimeout(()=>{window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}}))},200)},o=[`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.layer.updated`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`];return o.forEach(e=>Xu.on(e,a)),()=>{t=!0,i&&clearTimeout(i),window.removeEventListener(`workspace:tree:refresh`,r),o.forEach(e=>Xu.off(e,a))}},[e,W]),!(e&&Je===`canvas`&&!G)&&ne!==null&&re(null),(0,X.useEffect)(()=>{let t=!1;if(!(!e||Je!==`canvas`||G))return Gr(e,U,W).then(e=>{t||re(e)}).catch(()=>{t||re(null)}),()=>{t=!0}},[e,U,W,Je,G]);let dn=async()=>{if(s){E(!0);try{let t=await ui(e||s.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{E(!1)}}},fn=async t=>{if(s)try{await Or(e||s.id,[t],U,[],W,bn,{trashIfOrphaned:!0}),dS(e||s.id,W,U),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document removed from workspace path.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},pn=async t=>{if(s)try{await Ha(e||s.id,[t],U,[],W,bn),dS(e||s.id,W,U),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},mn=async t=>{if(s)try{await Or(e||s.id,t,U,[],W,bn,{trashIfOrphaned:!0}),dS(e||s.id,W,U),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},hn=async t=>{if(s)try{await Ha(e||s.id,t,U,[],W,bn),dS(e||s.id,W,U),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},gn=async t=>{if(s)try{let n=await Mr(e||s.id,[t]);if(n.failed?.length){i({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),i({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},_n=async t=>{if(s)try{let n=await Mr(e||s.id,t),r=new Set(n.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);p(e=>e.filter(e=>!r.has(e.id))),_(e=>Math.max(0,e-r.size));let a=[n.successful?.length?`${n.successful.length} destroyed`:null,n.failed?.length?`${n.failed.length} failed`:null].filter(Boolean).join(`, `);i({title:`Done`,description:a||`No documents destroyed`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},vn=e=>{O({documentIds:e,operation:`copy`,sourcePath:U,sourceTreeName:W}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},yn=e=>{O({documentIds:e,operation:`cut`,sourcePath:U,sourceTreeName:W}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},bn=ba(W),xn=async(t,n,r={})=>{if(!e)return!1;let a=r.targetTreeName??W,o=r.targetTreeType??bn;try{let s=await $r(e,t,n,a,o);if(s){dS(e,a,t);let o=r.sourceTreeName||D?.sourceTreeName,s=r.sourcePath||D?.sourcePath;if((r.move||D?.operation===`cut`)&&s&&o){let t=ba(o);await Or(e,n,s,[],o,t),dS(e,o,s),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:s,treeName:o}}))}await Bt(),O(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:a}})),i({title:`Success`,description:`${n.length} document(s) ${r.move||D?.operation===`cut`?`moved`:`pasted`} to "${t}"`})}return s}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Sn=async(t,n)=>{if(!e)return!1;try{let r=(await Fi(e,n,t,W,bn)).length>0;return r&&(window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:W}})),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}},Cn=async()=>{if(!(!s||g===0)&&window.prompt(`Type PURGE to permanently delete all ${g} matching documents.`)===`PURGE`)try{let t=await ci(e||s.id,U,[],[],{},W);await Bt(),i({title:`Success`,description:`${t.deleted} document(s) purged.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}},wn=()=>Yt(U,!0),Tn=async()=>{if(!(!e||!k||!j.trim())){P(!0);try{let t=j.trim(),n=k.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`;await Ja(e,i,W,k.captureView?{metadata:{toolbox:le.filters},querySpec:{features:le.filters.features,filters:[...Oy(le.filters.timeline),...Ty(le.filters.geo)],query:ln||void 0,sort:le.filters.sort?.sortBy?le.filters.sort:null}}:{}),A(null),fa(e,W);try{let t=await vi(e,W,{force:!0});Fe(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(dv(e,i,W))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{P(!1)}}},En=async()=>{if(!(!e||Je!==`canvas`)){I(!0);try{let t=ne||await Ai(e,U,W);re(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)}}},Dn=async()=>{if(ne){I(!0);try{await Ga(ne.code),re(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:W}})),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)}}},On=async()=>{if(!e||Je!==`canvas`||U===`/`)return;let t=ct?.label||U.split(`/`).pop()||`canvas`,n=ne?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){te(!0);try{if(ne)await Ga(ne.code),re(null);else if(qe?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await xi(e,U,!1,W);let n=U.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:W}})),r(dv(e,a,W)),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{te(!1)}}},kn=(0,X.useCallback)(async t=>{if(!e||!Ie)return;let n={treeName:W,path:U},r=ze===`left`?n:Ie,a=ze===`left`?Ie:n,o=ze===`left`?Ve:Ge;if(o.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let s=ba(a.treeName);try{if(!await $r(e,a.path,o,a.treeName,s))return;if(dS(e,a.treeName,a.path),t){let t=ba(r.treeName);await Or(e,o,r.path,[],r.treeName,t),dS(e,r.treeName,r.path)}[r,a].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),i({title:t?`Moved`:`Copied`,description:`${o.length} document(s) → "${a.path}"`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,Ie,ze,W,U,Ve,Ge,i]);if((0,X.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(),kn(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Ie,kn]),u)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!s)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let An=Je===`canvas`&&!G&&!!qe,jn=(0,Z.jsx)(Sx,{urlType:G?ba(W)===`directory`?`${W}-layer`:`context-layer`:Je===`canvas`?`canvas`:ba(W)===`directory`?W:`context`,urlDisplay:yt,contextPath:U,treeName:W,workspaceId:e||s.id,documents:Lt,isLoading:m,totalCount:Pt,currentPage:ie,pageSize:R,onPageChange:L,onPageSizeChange:e=>{ae(e),L(1)},onRemoveDocument:U===`/`?void 0:fn,onDeleteDocument:pn,onDestroyDocument:gn,onRemoveDocuments:U===`/`?void 0:mn,onDeleteDocuments:hn,onDestroyDocuments:_n,onCopyDocuments:vn,onCutDocuments:yn,onPasteDocuments:we?void 0:xn,onImportDocuments:we?void 0:Sn,onSelectionChange:He,selectedCount:Ve.length,onUrlClick:()=>Ue(`workspaces`,`detail`,e??null),onUrlSubmit:t=>r(dv(e,cv(`/`+t),W)),folders:Xe,onOpenFolder:t=>r(dv(e,cv(t),W)),scope:C,onScopeChange:w,pastedDocumentIds:D?.documentIds,linkTree:Pe,onPurgeDocuments:we?void 0:Cn,disablePurgeDocuments:!1,canvasInfo:ct??void 0,isCanvasPinned:ht,onTogglePinCanvas:mt?vt:void 0,onSaveAsCanvas:Pe&&Je!==`canvas`&&!G&&!we?wn:void 0,onShareCanvas:Je===`canvas`&&!G?En:void 0,onUnshareCanvas:ne?Dn:void 0,onDeleteCanvas:Je===`canvas`&&!G?On:void 0,isSharingCanvas:F,isDeletingCanvas:ee,isCanvasShared:!!ne,isCanvasLocked:!!qe?.locked,backendSearchQueries:oe,onBackendSearch:sn,serverSort:le.filters.sort,onServerSortChange:fe,onRemoveBackendQuery:cn,canSaveChanges:un,isSavingChanges:le.isSaving,onSaveChanges:ue,contentBanner:v&&y?(0,Z.jsx)(oS,{data:y,className:`mb-3`}):null,children:An&&qe?(0,Z.jsx)(Pv,{workspaceId:e||s.id,treeName:W,path:U,layerId:qe.id,querySpec:qe.querySpec,metadata:qe.metadata,isLocked:!!qe.locked,fetchDocuments:le.isDirty?xt:void 0}):!we&&it.kind===`columns`?(0,Z.jsx)(Fx,{documents:Lt,workspaceId:e||s.id,columns:it.columns??[],onColumnsChange:e=>ot(nt.map(t=>t.id===it.id?{...t,columns:e}:t))}):!we&&it.kind===`app`&&it.app?(0,Z.jsx)(Mx,{app:it.app,workspaceId:e||s.id,treeName:W,path:U}):null});return(0,Z.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0`,children:[(0,Z.jsx)(vx,{workspaceId:s.id,workspaceName:s.label||s.name},s.id),(0,Z.jsxs)(`div`,{className:`relative shrink-0 max-sm:border-b`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border max-sm:hidden`,style:Hf(s.color)?{backgroundColor:Hf(s.color)}:void 0}),!An&&!we&&Ze&&(0,Z.jsxs)(`div`,{className:`relative px-2 pt-1.5 sm:hidden`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border`,style:Hf(s.color)?{backgroundColor:Hf(s.color)}:void 0}),(0,Z.jsx)(Dx,{accentColor:Hf(s.color),views:nt,activeId:rt,onSelect:at,onSave:ot,readOnly:!1})]}),(0,Z.jsxs)(`div`,{className:`flex h-12 items-center gap-3 px-4`,children:[(0,Z.jsx)(mb,{title:We?`Back to workspace tree`:`Back to workspaces`,onBack:()=>We?Ue(`workspaces`,`detail`,e||s.id):r(`/workspaces`)}),(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0 ${s.status===`active`?`bg-success`:s.status===`error`?`bg-destructive`:`bg-muted-foreground`}`,title:s.status}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>Ue(`workspaces`,`detail`,e||s.id),title:`Browse workspace tree`,className:`flex min-w-0 items-center gap-1.5 truncate rounded px-1 -mx-1 text-left text-sm font-medium transition-colors hover:bg-accent`,children:[(0,Z.jsx)(c,{icon:s.icon||`ph:stack-fill`,width:16,height:16,color:Hf(s.color),className:K(`shrink-0`,!Hf(s.color)&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`truncate`,children:s.label||s.name})]}),!An&&!we&&Ze?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Dx,{className:`min-w-0 flex-1 self-stretch max-sm:hidden`,accentColor:Hf(s.color),views:nt,activeId:rt,onSelect:at,onSave:ot,onOpenToSide:e=>{Le({treeName:W,path:U,viewId:e}),Be(`right`)},readOnly:!1}),(0,Z.jsx)(`div`,{className:`flex-1 sm:hidden`})]}):(0,Z.jsx)(`div`,{className:`flex-1`}),De&&(0,Z.jsx)(`button`,{onClick:()=>{ke(!Oe),L(1)},className:K(`flex items-center gap-1.5 px-3 py-1 text-xs border rounded-md transition-colors`,Oe?`bg-warning/15 border-warning/40 text-warning`:`hover:bg-accent text-muted-foreground hover:text-foreground`),title:`Show only documents not filed into any context/directory tree (safe to purge from the backend)`,children:`Unfiled only`}),s.status===`active`?(0,Z.jsx)(`button`,{onClick:()=>de(`tools`),className:K(`flex h-7 w-7 items-center justify-center border rounded-md transition-colors touch-target`,he?`border-info bg-info text-info-foreground hover:bg-info/90`:le.t1Open&&le.t1View===`tools`?`bg-accent text-foreground`:`hover:bg-accent text-muted-foreground hover:text-foreground`),"aria-label":`Filters`,title:he?`Toolbox filters are active and narrow this view`:`Open the toolbox filters`,children:(0,Z.jsx)(Qe,{className:`h-3.5 w-3.5`})}):(0,Z.jsx)(`button`,{onClick:dn,disabled:T,className:`px-3 py-1 text-xs border rounded-md hover:bg-accent disabled:opacity-50 touch-target`,children:T?`Starting…`:`Start`}),(0,Z.jsx)(pb,{})]})]}),k&&(0,Z.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,Z.jsx)(vb,{title:`New canvas`,onClose:()=>A(null),children:(0,Z.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Tn()},className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,Z.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:j,onChange:e=>M(e.target.value),onKeyDown:e=>{e.key===`Escape`&&A(null)},autoFocus:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,Z.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:k.parentPath===`/`?`/`:k.parentPath})]})]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:k.captureView,onChange:e=>A({...k,captureView:e.target.checked})}),(0,Z.jsxs)(`span`,{children:[`Capture the current view`,(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,disabled:!j.trim()||N,children:N?`Creating…`:`Create canvas`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})})}),(0,Z.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2 p-2 bg-muted/20`,children:[(0,Z.jsx)(`div`,{"data-canvas-pane":!0,className:K(`flex-1 min-w-0 rounded-lg border 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:jn}),Ie&&e&&(0,Z.jsx)(_S,{workspaceName:e,pane:Ie,isFocused:ze===`right`,clipboard:D,setClipboard:O,onFocus:()=>Be(`right`),onSelectionChange:Ke,onNavigate:e=>Le(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Le(null),Be(`left`),Ke([])}})]})]})}function gS(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 _S({workspaceName:e,pane:t,isFocused:n=!1,clipboard:r,setClipboard:i,onFocus:a,onSelectionChange:o,onNavigate:s,onClose:c}){let{showToast:l}=po(),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(0),[v,y]=(0,X.useState)(1),[b,x]=(0,X.useState)(50),S=ba(t.treeName),C=gS(u,t.path),w=C?.type===`canvas`,T=(0,X.useMemo)(()=>S===`directory`?sS(u,t.path):[],[u,t.path,S]),E=t.viewId?Ex(C?.metadata).find(e=>e.id===t.viewId)??null:null,D=`${e}://${t.path===`/`?``:t.path.replace(/^\//,``)}`,O=(0,X.useCallback)(async()=>{let n=uS(e,t.treeName,t.path,v,b,``,``),r=cS.get(n);if(r){p(r.documents),_(r.totalCount);return}h(!0);try{let r=await Ki(e,t.path,[],{limit:b,page:v,treeName:t.treeName,treeType:S}),i=r.payload||[],a=r.totalCount||r.count||0;p(i),_(a),cS.set(n,{documents:i,totalCount:a})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),p([]),_(0)}finally{h(!1)}},[e,t.path,t.treeName,S,b,v,l]);(0,X.useEffect)(()=>{let n=!1,r=(r=!1)=>{r&&fa(e,t.treeName),vi(e,t.treeName,{force:r}).then(e=>{n||d(e)}).catch(()=>{n||d(null)})};r(!1);let i=n=>{let i=n.detail;i?.workspaceName&&i.workspaceName!==e||i?.treeName&&i.treeName!==t.treeName||r(!0)};return window.addEventListener(`workspace:tree:refresh`,i),()=>{n=!0,window.removeEventListener(`workspace:tree:refresh`,i)}},[e,t.treeName]),(0,X.useEffect)(()=>{O()},[O]),(0,X.useEffect)(()=>{let n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||(pS(e,r),!(r?.treeName&&r.treeName!==t.treeName)&&(r?.path&&r.path!==t.path||(dS(e,t.treeName,t.path),O())))};return window.addEventListener(`workspace:documents:refresh`,n),()=>window.removeEventListener(`workspace:documents:refresh`,n)},[O,e,t.treeName,t.path]);let k=(0,X.useCallback)(async(n,a,o={})=>{let s=o.targetTreeName??t.treeName,c=o.targetTreeType??S;try{let t=await $r(e,n,a,s,c);if(t){dS(e,s,n);let t=o.sourcePath||r?.sourcePath,c=o.sourceTreeName||r?.sourceTreeName;if((o.move||r?.operation===`cut`)&&t&&c){let n=ba(c);await Or(e,a,t,[],c,n),dS(e,c,t),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:c}}))}i(null),await O(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:s}}))}return t}catch(e){return l({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,t.treeName,S,O,l,r,i]),A=(0,X.useCallback)(()=>{dS(e,t.treeName,t.path),O()},[e,t.treeName,t.path,O]),j=(0,X.useCallback)(async n=>{try{await Or(e,n,t.path,[],t.treeName,S),A(),l({title:`Removed`,description:`${n.length} document(s) removed from "${t.path}"`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,t.path,t.treeName,S,A,l]),M=(0,X.useCallback)(async n=>{try{await Ha(e,n,t.path,[],t.treeName,S),A(),l({title:`Deleted`,description:`${n.length} document(s) deleted.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,t.path,t.treeName,S,A,l]),N=(0,X.useCallback)(async t=>{try{let n=await Mr(e,t);if(n.failed?.length&&!n.successful?.length){l({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}A(),l({title:`Destroyed`,description:`${n.successful?.length??t.length} document(s) removed from all backends.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,A,l]);return(0,Z.jsxs)(`div`,{className:K(`relative flex-1 min-w-0 rounded-lg border bg-background overflow-hidden`,n?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||a()},children:[c&&(0,Z.jsx)(`button`,{type:`button`,onClick:c,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`}),(0,Z.jsx)(Sx,{urlType:w?`canvas`:S===`directory`?t.treeName:`context`,urlDisplay:D,contextPath:t.path,treeName:t.treeName,workspaceId:e,documents:f,isLoading:m,totalCount:g,currentPage:v,pageSize:b,onPageChange:y,onPageSizeChange:e=>{x(e),y(1)},onRemoveDocument:t.path===`/`?void 0:e=>j([e]),onRemoveDocuments:t.path===`/`?void 0:j,onDeleteDocument:e=>M([e]),onDeleteDocuments:M,onDestroyDocument:e=>N([e]),onDestroyDocuments:N,onCopyDocuments:e=>{i({documentIds:e,operation:`copy`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{i({documentIds:e,operation:`cut`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:t.treeName===`backends`?void 0:k,onSelectionChange:o,pastedDocumentIds:r?.documentIds,linkTree:u,folders:T,onOpenFolder:s,canvasInfo:w?{label:C?.label,description:C?.description,color:C?.color}:void 0,children:E?.kind===`columns`?(0,Z.jsx)(Fx,{documents:f,workspaceId:e,columns:E.columns??[],onColumnsChange:()=>{},readOnly:!0}):E?.kind===`app`&&E.app?(0,Z.jsx)(Mx,{app:E.app,workspaceId:e,treeName:t.treeName,path:t.path}):null})]})}function vS(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 yS={id:`sketch`,label:`Sketch`,icon:rt,schemas:[lo],canCreate:!0,canEdit:e=>e.schema===lo,createUrl(e){let t=vS(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=vS(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},bS=[{kind:`message`,label:`New Message`,icon:It},{kind:`note`,label:`Note`,icon:xn},{kind:`link`,label:`Link`,icon:Xt},{kind:`todo`,label:`Todo`,icon:On},{kind:`identity`,label:`Identity`,icon:Ze},{kind:`sketch`,label:`Sketch`,icon:rt},{kind:`file`,label:`File`,icon:re},{kind:`photo`,label:`Photo/Video`,icon:L},{kind:`existing`,label:`Existing document`,icon:Ot},{kind:`folder`,label:`Folder`,icon:ut}];function xS(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?bS:bS.filter(e=>e.kind!==`photo`)}function SS({onSelect:e,variant:t=`list`,omit:n}){let r=xS().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,Z.jsx)(Z.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,Z.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,Z.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,Z.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,Z.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,Z.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}var CS=`data/schema/note`,wS=`2.0`;function TS(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!1),u=ih(),d=n.trim().length>0&&!c;async function f(t){l(!0);try{let r=await u.capture(),a={schema:CS,schemaVersion:wS,...i.trim()?{comment:i.trim()}:{},data:{...e.trim()?{title:e.trim()}:{},content:n},metadata:{features:_p(o),...r?{geo:r}:{}}};return await ts(t,[a])}finally{l(!1)}}return{title:e,setTitle:t,content:n,setContent:r,comment:i,setComment:a,tags:o,setTags:s,saving:c,canSave:d,save:f,geotag:u}}function ES(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 DS({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,X.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.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:K(`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,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,Z.jsx)(Mt,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,Z.jsx)(yt,{className:K(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,Z.jsx)(`div`,{className:K(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,Z.jsx)(`div`,{className:K(`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,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.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,Z.jsx)(en,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,Z.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,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`p`,{id:`${t}-hint`,className:K(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:ES(e)}),n&&(0,Z.jsx)(Dp,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}function OS(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 kS({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}){let h=Zc(),[g,_]=(0,X.useState)(`portrait`),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),E=o||w;Sf(()=>x(!1),b&&!E),Sf(()=>y(!1),v&&!b);let D=(0,X.useRef)(null),O=km(),{showSuccessToast:k,showErrorToast:A}=to(),j=O&&!u&&!v,[M,N]=(0,X.useState)(!1),P=!u&&!v&&!p&&!M;(0,X.useEffect)(()=>{b&&D.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[b]);let F=async(e,t)=>{if(!(!r||E)){T(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>$r(t.workspaceName,e,a,t.treeName,t.treeType))),k(c),n(),i&&h(OS({...t,path:e[0]}),{replace:!0})}catch(e){A(e instanceof Error?e.message:`Failed to save`)}finally{T(!1)}}},I=async e=>{if(!(!f||!l||e.targetIds.length===0)){C(!0);try{await Xi(l,f,e.predicate,e.targetIds,e.direction),k(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Qp(),x(!1)}catch(e){A(e instanceof Error?e.message:`Failed to create relations`)}finally{C(!1)}}},ee=v?b?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:j?void 0:g===`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},te=!!(f&&l),ne=r&&b&&(0,Z.jsx)(dp,{onClose:()=>x(!1),onConfirm:F,fixedWorkspaceName:l,saving:E||S,savingContent:s,tabs:te?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:te?I:void 0,relationWorkspaceName:l,relationExcludeIds:te?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}),re=(0,Z.jsxs)(`div`,{style:p&&!v?{width:`100%`,height:`100%`,minWidth:0}:ee,onAnimationEnd:e=>{P&&e.target===e.currentTarget&&N(!0)},className:K(`flex flex-col overflow-hidden`,p&&!v?`strip-document-card`:`rounded-2xl border bg-card shadow-elevation-4 transition-[width,height]`,u&&!v&&!p&&`w-full md:w-[var(--document-card-width,min(560px,90vw))]`,j&&`fixed inset-2 z-40 shadow-elevation-5`,P&&`animate-card-in`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,Z.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(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,Z.jsx)(ar,{className:`h-4 w-4`})}),r&&(0,Z.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>x(!0),disabled:!a||E,children:E?`Saving…`:`Save / Link to…`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p&&!v?p.onToggleExpanded():y(e=>!e),className:K(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,!v&&!p&&`max-md:hidden`),"aria-label":p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,title:p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,children:v||p?.expanded?(0,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,disabled:E,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":`Close`,children:(0,Z.jsx)(G,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)($p.Provider,{value:()=>y(e=>!e),children:(0,Z.jsx)(`div`,{className:K(`min-h-0 flex-1 overflow-y-auto`,v&&!d&&`mx-auto w-full max-w-3xl`),children:p&&ne?ne:m})})]});return v?(0,yf.createPortal)((0,Z.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[re,ne&&(0,Z.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:ne})]}),document.body):(0,Z.jsxs)(Z.Fragment,{children:[re,!p&&ne&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!E&&x(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{ref:D,className:`relative shrink-0 md:z-panel md:ml-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:ne})]})]})}function AS({onClose:e,initialData:t}){let n=TS();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setContent(t.content)},[]),(0,Z.jsx)(kS,{title:`New Note`,icon:xn,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Note created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-note-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(Eu,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(To,{kind:`markdown`,value:n.content,onChange:n.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(DS,{geotag:n.geotag,idPrefix:`qa-note-geotag`})]})})}var jS=`data/schema/tab`,MS=`2.0`;function NS(e){try{return new URL(e),!0}catch{return!1}}function PS(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),c=ih(),l=e.trim(),u=NS(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:jS,schemaVersion:MS,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:_p(i),...t?{geo:t}:{}}};return await ts(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 FS({onClose:e,initialData:t}){let n=PS();return(0,X.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,Z.jsx)(kS,{title:`New Link`,icon:Xt,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(DS,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function IS({onClose:e,initialData:t}){let n=mh();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,Z.jsx)(kS,{title:`New Todo`,icon:On,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(eg,{...n,idPrefix:`qa-todo`}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,Z.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,Z.jsx)(DS,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function LS({onClose:e,initialData:t}){let n=lg();return(0,X.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,Z.jsx)(kS,{title:`New Identity`,icon:Ze,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(mg,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,Z.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 RS=3;function zS(e){return`${e.name}:${e.size}:${e.lastModified}`}function BS(e=[]){let[t,n]=(0,X.useState)(()=>e.map(e=>({id:zS(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(t),o=(0,X.useRef)(null),s=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,X.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,X.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,X.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(zS(e))).map(e=>({id:zS(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,X.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,X.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,X.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,X.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await ms(e),d=r===`backends`?await ds(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(RS,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 co(n,{...d,key:Zo(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`);l(e.id,{status:`hashing`});try{let t=await hs(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 fo(n,[...new Set(r.values())])}catch{i={}}let a=m.filter(e=>r.has(e.id)),o=0;await Promise.all(Array.from({length:Math.min(RS,a.length)},async()=>{for(;o<a.length;){if(p.signal.aborted)return;let s=a[o++],c=r.get(s.id);try{let r=i[c]??null;r?l(s.id,{status:`linking`,progress:1,resumed:!0}):(l(s.id,{status:`uploading`,progress:0}),r=await ao(n,s.file,{signal:p.signal,onProgress:(e,t)=>l(s.id,{progress:t?e/t:0})}),l(s.id,{status:`linking`,progress:1}));let a=await ts(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`)&&$o(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 VS(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function HS(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 VS(e.file.size)}}function US({item:e}){switch(e.status){case`done`:return(0,Z.jsx)($e,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,Z.jsx)(B,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,Z.jsx)(bt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function WS({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,Z.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:K(`h-full rounded-full transition-[width] duration-200`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function GS({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,Z.jsx)(Z.Fragment,{children:e.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(Eu,{children:[e.length,` file(s)`,r>0&&(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,Z.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(US,{item:e}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,Z.jsx)(`span`,{className:K(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:HS(e)}),!t&&e.status!==`done`&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(WS,{item:e})]},e.id))})]})})}function KS({items:e,running:t,onCancel:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,Z.jsx)(GS,{items:e,running:!0,onRemove:()=>{}}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function qS(e){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return jr(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var JS=`data/schema/file`,YS=`3.0`;function XS(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:qS(e),geotag:ih()}}function ZS(e,t,n={}){let r=_p(n.tags??[]),i=n.comment?.trim();return{schema:JS,schemaVersion:YS,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 QS=`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 $S({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{children:`Tags`}),(0,Z.jsx)(gp,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Eu,{htmlFor:`${t}-comment`,children:`Comment`}),(0,Z.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:QS}),n&&e.tags.length+e.comment.trim().length>0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,Z.jsx)(DS,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var eC={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 tC(e){return/^(image|video)\//.test(e.type)}async function nC(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
|
|
11
11
|
|
|
12
12
|
`)r=`image/png`;else if([`GIF87a`,`GIF89a`].includes(n(0,6)))r=`image/gif`;else if(n(0,4)===`RIFF`&&n(8,4)===`WEBP`)r=`image/webp`;else if(n(0,5)===`%PDF-`)r=`application/pdf`;else if(n(0,4)===`PK`)r=`application/zip`;else if(n(4,4)===`ftyp`){let e=[n(8,4)],i=new DataView(t.buffer).getUint32(0);for(let r=16;r+4<=Math.min(t.length,i);r+=4)e.push(n(r,4));e.some(e=>[`avif`,`avis`].includes(e))?r=`image/avif`:e.some(e=>[`heic`,`heix`,`hevc`,`hevx`].includes(e))?r=`image/heic`:e.some(e=>[`mif1`,`msf1`].includes(e))?r=`image/heif`:e.includes(`qt `)?r=`video/quicktime`:e.some(e=>[`isom`,`iso2`,`mp41`,`mp42`,`avc1`,`M4V `].includes(e))&&(r=`video/mp4`)}let i=e.type.toLowerCase().split(`;`)[0].trim(),a=!i||[`application/octet-stream`,`binary/octet-stream`,`*/*`].includes(i),o=e.name.split(`.`).pop()?.toLowerCase()??``,s=r||a&&eC[o]||i;return s===e.type?e:new File([e],e.name,{type:s,lastModified:e.lastModified})}));return{kind:t.length>0&&t.every(tC)?`photo`:`file`,files:t}}function rC({file:e}){let t=(0,X.useRef)(null),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let n=t.current;if(!n)return;let r=URL.createObjectURL(e);return n.src=r,()=>{n.removeAttribute(`src`),URL.revokeObjectURL(r)}},[e]),(0,Z.jsx)(`div`,{className:`flex min-h-24 items-center justify-center overflow-hidden rounded-md border border-input bg-muted/30`,children:n?(0,Z.jsxs)(`p`,{className:`p-4 text-center text-sm text-muted-foreground`,children:[`Preview unavailable for `,e.name,`. You can still save the original.`]}):e.type.startsWith(`video/`)?(0,Z.jsx)(`video`,{ref:t,controls:!0,preload:`metadata`,"aria-label":e.name,onError:()=>r(!0),className:`max-h-64 max-w-full`}):(0,Z.jsx)(`img`,{ref:t,alt:e.name,onError:()=>r(!0),className:`max-h-64 max-w-full object-contain`})})}function iC({onClose:e,initialData:t}){let n=(0,X.useRef)(null),r=BS(t?.files),i=r.items.map(e=>e.file),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(!1),{state:l}=xs(),u=XS(l.activeWorkspaceName),d=e=>{e&&(s||r.addFiles(Array.from(e)))},f=e=>{e.preventDefault(),o(!1),d(e.dataTransfer.files)},p=i.length>0;return(0,Z.jsx)(kS,{title:`Upload File`,icon:re,onClose:e,onSave:async e=>{c(!0);try{let t={mode:`workspace`,...e},n=await u.geotag.capture(),i=await r.start(t,(e,t)=>ZS(e,t,{tags:u.tags,comment:u.comment,geo:n}));if(i.failed)throw Error(`${i.failed} file(s) failed or cancelled. Retry keeps completed uploads.`);return i.docIds}finally{c(!1)}},navigateAfterSave:!0,canSave:p,saving:s,saveProgress:(0,Z.jsx)(KS,{items:r.items,running:r.running,onCancel:r.cancel}),successMessage:`File(s) uploaded`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:f,onClick:()=>n.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,a?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(re,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`or click to browse`}),(0,Z.jsx)(`input`,{ref:n,type:`file`,multiple:!0,disabled:s,className:`hidden`,onChange:e=>{d(e.target.files),e.target.value=``}})]}),r.items.filter(e=>tC(e.file)).map(e=>(0,Z.jsx)(rC,{file:e.file},e.id)),(0,Z.jsx)(GS,{items:r.items,running:s,onRemove:r.removeItem}),(0,Z.jsx)($S,{fields:u,idPrefix:`qa-file`,multiple:i.length>1})]})})}function aC({onClose:e,initialData:t}){let n=BS(t?.files),r=(0,X.useRef)(null),i=n.items.length>0,[a,o]=(0,X.useState)(!1),{state:s}=xs(),c=XS(s.activeWorkspaceName),l=e=>{!a&&e&&n.addFiles([e])};return(0,Z.jsx)(kS,{title:`Photo/Video`,icon:L,onClose:e,onSave:async e=>{if(!i)return[];o(!0);try{let t=await c.geotag.capture(),r={mode:`workspace`,...e},i=await n.start(r,(e,n)=>ZS(e,n,{tags:c.tags,comment:c.comment,geo:t}));if(i.failed)throw Error(`Upload failed or cancelled. You can retry.`);return i.docIds}finally{o(!1)}},navigateAfterSave:!0,canSave:i,saving:a,saveProgress:(0,Z.jsx)(KS,{items:n.items,running:n.running,onCancel:n.cancel}),successMessage:`Upload saved`,children:(0,Z.jsxs)(`div`,{className:K(`flex h-full flex-col gap-4 p-4`,!i&&`items-center justify-center`),children:[i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex min-h-0 w-full flex-1 flex-col gap-3 overflow-y-auto`,children:n.items.map(({id:e,file:t,status:r})=>(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(rC,{file:t}),(0,Z.jsxs)(`div`,{className:`flex w-full items-center gap-2 rounded border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(bt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:t.name}),(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[(t.size/1024/1024).toFixed(1),` MB`]}),(0,Z.jsx)(`button`,{type:`button`,disabled:a||r===`done`,onClick:()=>n.removeItem(e),"aria-label":`Remove ${t.name}`,className:`text-muted-foreground hover:text-foreground disabled:opacity-40`,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e))}),(0,Z.jsx)(`div`,{className:`w-full shrink-0 space-y-4`,children:(0,Z.jsx)($S,{fields:c,idPrefix:`qa-photo`,multiple:n.items.length>1})})]}):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r.current?.click(),className:`flex flex-col items-center gap-2 rounded-md border border-dashed border-input px-6 py-10 text-center transition-colors hover:bg-muted/40`,children:[(0,Z.jsx)(L,{className:`h-8 w-8 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm`,children:`Open camera`})]}),(0,Z.jsx)(`input`,{ref:r,type:`file`,accept:`image/*,video/*`,capture:`environment`,className:`hidden`,disabled:a,onChange:e=>{l(e.target.files?.[0]??null),e.target.value=``}})]})})}var oC=`shrink-0 h-viewport-card w-[min(380px,90vw)] max-md:fixed max-md:inset-2 max-md:z-40 max-md:h-auto max-md:w-auto max-md:shadow-elevation-5`;function sC({onClose:e}){let{showSuccessToast:t,showErrorToast:n}=to(),[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(!1);return r?(0,Z.jsx)(dp,{sizeClassName:oC,documentCount:r.length,saving:a,onClose:e,onConfirm:async(i,a)=>{o(!0);try{await Promise.all(i.map(e=>$r(a.workspaceName,e,r,a.treeName,a.treeType))),t(`${r.length} document${r.length===1?``:`s`} linked`),e()}catch(e){n(e instanceof Error?e.message:`Failed to link documents`)}finally{o(!1)}}}):(0,Z.jsx)(Lp,{sizeClassName:oC,onConfirm:e=>{e.length&&i(e)},onClose:e})}var cC=0;function lC(){return cC+=1,`card-${cC}`}function uC({initialKind:e,initialData:t,onInitialCardClose:n,onCardsOpenChange:r}){let[i,a]=(0,X.useState)(!1),o=km(),s=Io(),c=!!(s?.state.t1Open||s?.state.addOpen),[l,u]=(0,X.useState)(()=>e?[{id:`initial`,kind:e,initialData:t}]:[]),d=l.length>0,f=(0,X.useRef)(r);(0,X.useEffect)(()=>{f.current=r},[r]),(0,X.useEffect)(()=>{f.current?.(d)},[d]),c&&i&&a(!1);let p=Zc(),m=e=>{if(e===`sketch`){a(!1),p(yS.createUrl(null));return}u(t=>[...t,{id:lC(),kind:e}]),a(!1)},h=e=>{u(t=>t.filter(t=>t.id!==e)),e===`initial`&&n?.()},g=(0,Z.jsxs)(`div`,{className:K(`pointer-events-none fixed right-6 z-40 flex flex-col items-end gap-2`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`,l.length>0&&`max-md:hidden`,c&&`hidden`),children:[(0,Z.jsx)(`div`,{className:K(`flex flex-col items-end gap-2 transition-all duration-150`,i?`pointer-events-auto opacity-100`:`pointer-events-none translate-y-2 opacity-0`),children:(0,Z.jsx)(SS,{variant:`stack`,omit:[`folder`,`message`],onSelect:m})}),(0,Z.jsx)(`div`,{className:`pointer-events-none flex w-16 justify-center`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-label":i?`Close quick add`:`Quick add`,className:`pointer-events-auto flex h-11 w-11 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-elevation-3 transition-transform hover:scale-105`,children:i?(0,Z.jsx)(G,{className:`h-5 w-5`}):(0,Z.jsx)(H,{className:`h-5 w-5`})})})]});return(0,Z.jsxs)(`div`,{className:`relative flex h-full w-full flex-col`,children:[l.length>0&&(0,Z.jsx)(`div`,{className:`pointer-events-auto flex flex-1 items-center gap-4 overflow-x-auto p-6 md:pr-28`,children:l.map(e=>{let t=()=>h(e.id);switch(e.kind){case`note`:return(0,Z.jsx)(AS,{onClose:t,initialData:e.initialData},e.id);case`link`:return(0,Z.jsx)(FS,{onClose:t,initialData:e.initialData},e.id);case`todo`:return(0,Z.jsx)(IS,{onClose:t,initialData:e.initialData},e.id);case`identity`:return(0,Z.jsx)(LS,{onClose:t,initialData:e.initialData},e.id);case`file`:return(0,Z.jsx)(iC,{onClose:t,initialData:e.initialData},e.id);case`photo`:return(0,Z.jsx)(aC,{onClose:t,initialData:e.initialData},e.id);case`existing`:return(0,Z.jsx)(sC,{onClose:t},e.id);case`sketch`:return null;case`folder`:case`message`:return null}})}),o?(0,yf.createPortal)(g,document.body):g]})}function dC(e){let t=`${e.workspaceName}\0${e.treeName}\0${e.path}`,[n,r]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let n=!1;return ka(e.workspaceName,e.treeName).then(i=>{n||r({key:t,node:Dr(i,e.path)})}).catch(()=>{n||r({key:t,node:null})}),()=>{n=!0}},[t,e.workspaceName,e.treeName,e.path]),!n||n.key!==t?{state:`loading`}:n.node?{state:`ready`,node:n.node}:{state:`missing`}}function fC(e){let t=`/workspaces/${encodeURIComponent(e.workspaceName)}`,n=e.path.replace(/^\//,``);return e.treeName===`context`?`${t}/path/${n}`:`${t}/trees/${encodeURIComponent(e.treeName)}/path/${n}`}var pC=`application/x-canvas-pin`;function mC({pin:e,onUnpin:t,onMinimize:n,onDropPin:r}){let i=dC(e),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=!!r&&!a,u=e=>{let t=e.currentTarget.getBoundingClientRect();return e.clientX>t.left+t.width/2?`after`:`before`},d=l?{onDragOver:e=>{e.dataTransfer.types.includes(`application/x-canvas-pin`)&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,c(u(e)))},onDragLeave:()=>c(null),onDrop:t=>{let n=t.dataTransfer.getData(pC);c(null),!(!n||n===e.id)&&(t.preventDefault(),r?.(n,u(t)===`after`))}}:{},f=i.state===`ready`?i.node:null,p=f?.label||e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`,m=f?.color;return(0,X.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]),(0,Z.jsxs)(`section`,{...d,className:a?`fixed inset-0 z-picker flex flex-col bg-background`:`flex flex-col rounded-lg border bg-background overflow-hidden min-h-0 min-w-0 ${s?`ring-2 ring-primary/60`:``}`,children:[(0,Z.jsxs)(`header`,{draggable:l,onDragStart:l?t=>{t.dataTransfer.setData(pC,e.id),t.dataTransfer.effectAllowed=`move`}:void 0,className:`flex items-center gap-2 px-3 py-2 border-b bg-muted/20 shrink-0 min-w-0 ${l?`cursor-grab active:cursor-grabbing`:``}`,children:[l&&(0,Z.jsx)(Je,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-hidden":!0}),m&&(0,Z.jsx)(`div`,{className:`w-1 h-5 rounded-full shrink-0`,style:{backgroundColor:m}}),(0,Z.jsx)($n,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:p}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono`,children:[e.workspaceName,`://`,e.path.replace(/^\//,``)]})]}),n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,title:`Minimize to tab bar`,"aria-label":`Minimize to tab bar`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(ct,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(e=>!e),"aria-pressed":a,title:a?`Restore tile (Esc)`:`Fill view area`,"aria-label":a?`Restore tile`:`Fill view area`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:a?(0,Z.jsx)(it,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(Fn,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(mu,{to:fC(e),title:`Open in workspace`,"aria-label":`Open in workspace`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-accent hover:text-foreground transition-colors`,children:(0,Z.jsx)(gn,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,title:`Unpin from home`,"aria-label":`Unpin from home`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-md text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,Z.jsx)(ue,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0`,children:[i.state===`loading`&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}),i.state===`missing`&&(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 px-4 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This canvas is no longer available.`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`It may have been renamed, moved or deleted.`}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`mt-1 px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:`Remove pin`})]}),i.state===`ready`&&(0,Z.jsx)(Pv,{workspaceId:e.workspaceName,treeName:e.treeName,path:e.path,layerId:i.node.id,querySpec:i.node.querySpec,metadata:i.node.metadata,readOnly:!0})]})]})}function hC(e,t,n){let r=Promise.resolve();return i=>{let a=r.then(async()=>{let r=await e(),a=i(r.home?.pinnedCanvases??[]);n(await t({...r,home:{...r.home,pinnedCanvases:a}}))});return r=a.catch(()=>{}),a}}function gC(e,t){return e.minimized===!0||t.has(e.id)}function _C(e){return e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`}function vC({pins:e,onRestore:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(e.length);return i!==e.length&&(a(e.length),e.length===0&&r(!1)),e.length===0?null:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute bottom-0 left-0 right-0 z-40 max-md:hidden`,children:(0,Z.jsx)(`div`,{className:`pointer-events-auto flex items-end gap-1 overflow-x-auto px-3 pr-28 pb-safe-bottom`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),title:`Restore ${_C(e)}`,className:`flex max-w-[180px] shrink-0 items-center gap-1.5 rounded-t-lg border border-b-0 bg-background px-3 py-1.5 text-xs shadow-elevation-1 hover:bg-accent`,children:[(0,Z.jsx)($n,{className:`h-3.5 w-3.5 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:_C(e)})]},e.id))})}),n&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-drawer md:hidden`,onClick:()=>r(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed bottom-rail-stack left-2 z-rail w-60 max-w-[calc(100vw-1rem)] rounded-xl border bg-card p-1.5 shadow-elevation-5 animate-fade-in md:hidden touch-target`,children:e.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm hover:bg-accent`,children:[(0,Z.jsx)($n,{className:`h-4 w-4 shrink-0 text-primary`}),(0,Z.jsx)(`span`,{className:`truncate`,children:_C(e)})]},e.id))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),"aria-label":n?`Close minimized canvases`:`Minimized canvases (${e.length})`,className:`fixed bottom-rail-inset left-16 z-nav flex h-12 w-12 items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[(0,Z.jsx)($n,{className:`h-5 w-5`}),(0,Z.jsx)(`span`,{className:`absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1 text-[10px] font-semibold`,children:e.length})]})]})}function yC(){let{pins:e,unpin:t,movePin:n,setMinimized:r,isLoading:i}=Kx(),{showErrorToast:a}=to(),[o,s]=(0,X.useState)(new Set),c=(0,X.useRef)(e);(0,X.useEffect)(()=>{c.current=e},[e]);let l=e=>{r(e,!0).catch(()=>a(`Could not save minimized state`))},u=t=>{s(e=>{let n=new Set(e);return n.delete(t),n}),e.find(e=>e.id===t)?.minimized&&r(t,!1).catch(()=>a(`Could not save restored state`))},d=(0,X.useCallback)(e=>{s(e?new Set(c.current.filter(e=>!e.minimized).map(e=>e.id)):new Set)},[]),f=e.filter(e=>!gC(e,o)),p=e.filter(e=>gC(e,o)),m=(t,r,i)=>{let a=e.findIndex(e=>e.id===r.id);if(a===-1)return;let o=i?e[a+1]?.id??null:r.id;n(t,o)};return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto`,children:i?(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsx)(`div`,{className:`grid gap-4 p-4 h-full grid-cols-[repeat(auto-fit,minmax(min(640px,100%),1fr))] auto-rows-fr ${p.length>0?`md:pb-12`:``}`,children:f.map(e=>(0,Z.jsx)(mC,{pin:e,onUnpin:()=>{t(e.id)},onMinimize:()=>l(e.id),onDropPin:(t,n)=>m(t,e,n)},e.id))})}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,children:(0,Z.jsx)(uC,{onCardsOpenChange:d})}),(0,Z.jsx)(vC,{pins:p,onRestore:u})]})}function bC(){return(0,Z.jsx)(`div`,{className:`h-full w-full`,"aria-hidden":!0})}var xC=`share-target-inbox`,SC={"too-large":`Android shares are limited to 100 MiB in total for temporary device storage. Nothing was uploaded. Use Add File to upload larger files directly.`,"stash-failed":`Canvas couldn't hold on to the shared file — device storage may be full. Try again, or upload it from the app.`,"empty-share":`Canvas received no files or text from the sharing app. Try again, or use Add File to select the photo directly.`,"empty-file":`The sharing app delivered an empty file. Try again, or use Add File to select the original directly.`,expired:`Nothing shared, or the share expired.`};async function CC(e){let t=await caches.open(xC),n=null,r=Date.now()+3e5;for(;Date.now()<r;){let r=await t.match(`/share-target-inbox/${e}/meta`);if(!r)return null;if(n=await r.json(),n?.status===`error`)throw Error(n.error||`stash-failed`);if(n?.status!==`receiving`)break;await new Promise(e=>setTimeout(e,300))}if(!n||n.status===`receiving`)throw Error(`stash-failed`);let i=[];for(let r=0;r<n.fileNames.length;r++){let a=await t.match(`/share-target-inbox/${e}/file-${r}`);if(!a)throw Error(`stash-failed`);let o=await a.blob();i.push(new File([o],n.fileNames[r],{type:o.type}))}let a=i.length?await nC(i):null;if(await Promise.all(n.fileNames.map((n,r)=>t.delete(`/share-target-inbox/${e}/file-${r}`))),await t.delete(`/share-target-inbox/${e}/meta`),a)return{kind:a.kind,data:{files:a.files}};if(![n.title,n.text,n.url].some(e=>e.trim()))throw Error(`empty-share`);let o=n.text.trim(),s=n.url||(EC(o)?o:``);return s?{kind:`link`,data:{url:s,title:n.title}}:{kind:`note`,data:{title:n.title,content:n.text}}}var wC=new Map;function TC(e){let t=wC.get(e);return t||(t=CC(e),wC.set(e,t),t.finally(()=>setTimeout(()=>wC.delete(e),6e4)).catch(()=>{})),t}function EC(e){if(!e||/\s/.test(e))return!1;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function DC(){let[e]=bu(),t=Zc(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null);(0,X.useEffect)(()=>{let t=!1;async function n(){let n=e.get(`error`);if(n){a(n);return}let i=e.get(`token`),o=i?await TC(i):null;t||(o?r(o):a(`expired`))}return n().catch(e=>{t||a(e instanceof Error?e.message:`stash-failed`)}),()=>{t=!0}},[e]);let o=()=>t(`/home`,{replace:!0});return i?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 px-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:SC[i]??SC.expired}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/apps/add/file`,{replace:!0}),className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Add File`}),(0,Z.jsx)(`button`,{type:`button`,onClick:o,className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Go to Canvas`})]}):n?(0,Z.jsx)(uC,{initialKind:n.kind,initialData:n.data,onInitialCardClose:o}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-sm text-muted-foreground`,children:`Receiving shared content on this device… No upload has started.`})}function OC(e,t=`An error occurred`){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let n=e;return n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||t}return t}function kC(e,t,n=`An error occurred`){return console.error(t,e),OC(e,n)}function AC({value:e,onChange:t,onPickTarget:n,fixedWorkspaceName:r,format:i=`url`,tabs:a=[`context`,`directory`],pickerTitle:o=`Pick a path…`,placeholder:s,id:c,disabled:l,className:u,inputClassName:d}){let[f,p]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:K(`flex gap-2`,u),children:[(0,Z.jsx)(q,{id:c,value:e,onChange:e=>t(e.target.value),placeholder:s,disabled:l,className:K(`font-mono`,d)}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`icon`,onClick:()=>p(!0),disabled:l,"aria-label":`Browse tree paths`,title:`Browse…`,className:`shrink-0`,children:(0,Z.jsx)(Mn,{className:`h-4 w-4`})}),f&&(0,Z.jsx)(pp,{onClose:()=>p(!1),children:(0,Z.jsx)(dp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:a,fixedWorkspaceName:r,title:o,confirmLabel:`Use path`,onConfirm:(e,r)=>{p(!1);let a=e[0];if(a){if(n){n(a,r);return}t(i===`url`?`${r.workspaceName}://${a.replace(/^\/+/,``)}`:a)}},onClose:()=>p(!1)})})]})}function jC(){let e=Zc(),[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(`context`),[h,g]=(0,X.useState)(`/`),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(`/`),[x,S]=(0,X.useState)(``),[C,w]=(0,X.useState)(!1),[T,E]=bb(),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),{showToast:j}=po();(0,X.useEffect)(()=>{Xu.isConnected()||(console.log(`Socket not connected, attempting to connect...`),Xu.reconnect())},[]);let M=(0,X.useCallback)(async()=>{try{o(!0);let[e,t]=await Promise.all([Yo(),Pr()]),r=e?.filter(e=>e&&typeof e==`object`&&e.id&&e.userId)||[];n(r);let a=t||[];if(i(a),a.length>0){let e=a.some(e=>e.id===x);(!x||!e)&&S(a[0].id)}else S(``);c(null)}catch(e){console.error(`Data fetch error:`,e),n([]),i([]);let t=`Failed to fetch data`;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 data`}c(t),j({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[x,j]);(0,X.useEffect)(()=>{M()},[M]),(0,X.useEffect)(()=>{let e=()=>Xu.emit(`subscribe`,{channel:`context`}),t=()=>Xu.emit(`unsubscribe`,{channel:`context`}),r=Xu.on(`connect`,e);console.log(`Subscribing to context events`),e();let i=e=>{let t=e;if(console.log(`Received context created:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:created event:`,t);return}n(e=>e.some(e=>e&&e.id===t.id&&e.userId===t.userId)?(console.log(`Context ${t.id} already exists, skipping duplicate add`),e):[...e,t])},a=e=>{let t=e;if(console.log(`Received context update:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:updated event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},o=e=>{let t=e;console.log(`Received context deletion:`,t);let r=t?.contextId??t?.id;if(!r){console.error(`Invalid context deletion data received:`,t);return}n(e=>e.filter(e=>e&&e.id!==r))},s=e=>{let t=e;if(console.log(`Received context URL change:`,t),!t||!t.id||!t.userId){console.error(`Invalid context data received in context:url:changed event:`,t);return}n(e=>e.map(e=>e&&e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},c=[[`context:created`,i],[`context.created`,i],[`context:updated`,a],[`context.updated`,a],[`context:deleted`,o],[`context.deleted`,o],[`context:url:changed`,s],[`context.url.set`,s],[`context:url:set`,s]];return c.forEach(([e,t])=>Xu.on(e,t)),()=>{console.log(`Unsubscribing from context events`),t(),r?.(),c.forEach(([e,t])=>Xu.off(e,t))}},[]);let N=async t=>{if(t.preventDefault(),!h.trim()||!x||!l.trim()){j({title:`Missing Fields`,description:`Context ID, Context URL and Workspace are required.`,variant:`destructive`});return}w(!0);try{let t={id:l,name:d.trim()||void 0,url:h,description:_||void 0,workspaceId:x,baseUrl:y||void 0,treeType:p},n=await rs(t);u(``),f(``),g(`/`),v(``),b(`/`),await M(),j({title:`Success`,description:`Context created successfully`}),E(!1),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e(`/contexts/${n.id}`)}catch(e){let t=kC(e,`Context creation error:`,`Failed to create context`);j({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}},P=async e=>{let n=t.find(t=>t.id===e);if(n&&n.url&&(n.url.endsWith(`/default`)||n.url.includes(`://default`))){j({title:`Error`,description:`Cannot delete the default context`,variant:`destructive`});return}A(e)},F=async()=>{if(k)try{await fs(k),n(e=>e.filter(e=>!Uo(e,{id:k}))),j({title:`Success`,description:`Context deleted successfully`})}catch(e){console.error(`Context deletion error:`,e);let t=`Failed to delete context`;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 delete context`}j({title:`Error`,description:t,variant:`destructive`})}finally{A(null)}},I=t=>{let n=t.isShared||t.type===`shared`;e(n?`/contexts/${t.id}?ownerId=${encodeURIComponent(t.userId)}`:`/contexts/${t.id}`)},ee=e=>{O(e)},te=async e=>{if(e.preventDefault(),D)try{n(e=>e.map(e=>e.id===D.id&&e.userId===D.userId?D:e)),j({title:`Success`,description:`Context updated successfully (mock update)`}),O(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update context`;j({title:`Error`,description:t,variant:`destructive`})}},ne=(0,X.useMemo)(()=>({type:e=>e.isShared||e.type===`shared`?`shared`:`owned`,id:e=>e.id??``,owner:e=>e.isShared||e.type===`shared`?e.ownerEmail||e.userId||``:`you`,url:e=>e.url??``,workspaceId:e=>e.workspaceId??``,baseUrl:e=>e.baseUrl??``,path:e=>e.path??``,locked:e=>+!!e.locked,created:e=>Date.parse(e.createdAt)||0,updated:e=>Date.parse(e.updatedAt)||0}),[]),{sorted:re,sort:ie,toggleSort:L}=Xp(t.filter(e=>e!=null),ne);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(fb,{title:`Contexts`,description:`Create and manage contexts in your workspaces. View contexts shared with you.`,actions:!T&&(0,Z.jsxs)(J,{onClick:()=>E(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create context`,title:`Create context`,children:[(0,Z.jsx)(H,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Context`})]})}),T&&(0,Z.jsx)(vb,{title:`Create New Context`,onClose:()=>E(!1),children:(0,Z.jsxs)(`form`,{onSubmit:N,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`workspace`,className:`block text-sm font-medium mb-1`,children:`Workspace`}),(0,Z.jsxs)(`select`,{id:`workspace`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:x,onChange:e=>S(e.target.value),disabled:C||r.length===0,children:[r.length===0&&(0,Z.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),r.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label||e.name},`${e.owner}-${e.id}`))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`newContextId`,className:`block text-sm font-medium mb-1`,children:`Context ID`}),(0,Z.jsx)(q,{id:`newContextId`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g., my-new-context`,disabled:C})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(AC,{id:`url`,value:h,onChange:g,placeholder:`e.g., /project/path/resource`,disabled:C,pickerTitle:`Context URL path…`,onPickTarget:(e,t)=>{g(e),m(t.treeType);let n=r.find(e=>e.name===t.workspaceName||e.id===t.workspaceName);n&&S(n.id)}})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`baseUrl`,className:`block text-sm font-medium mb-1`,children:`Base URL (Optional)`}),(0,Z.jsx)(AC,{id:`baseUrl`,value:y,onChange:b,format:`path`,placeholder:`e.g., /base/path`,disabled:C,pickerTitle:`Base path…`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`description`,className:`block text-sm font-medium mb-1`,children:`Description (Optional)`}),(0,Z.jsx)(q,{id:`description`,value:_,onChange:e=>v(e.target.value),placeholder:`Description`,disabled:C})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`contextName`,className:`block text-sm font-medium mb-1`,children:`Name (Optional)`}),(0,Z.jsx)(q,{id:`contextName`,value:d,onChange:e=>f(e.target.value),placeholder:`My Context`,disabled:C})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`treeType`,className:`block text-sm font-medium mb-1`,children:`Tree`}),(0,Z.jsxs)(`select`,{id:`treeType`,className:`w-full px-3 py-2 border border-border rounded-md shadow-elevation-1 focus:outline-none focus:ring-primary focus:border-primary`,value:p,onChange:e=>m(e.target.value),disabled:C,children:[(0,Z.jsx)(`option`,{value:`context`,children:`Context tree`}),(0,Z.jsx)(`option`,{value:`directory`,children:`Directory tree`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Which workspace tree this context navigates.`})]})]}),(0,Z.jsxs)(J,{type:`submit`,disabled:C||!h.trim()||!x||!l.trim(),children:[(0,Z.jsx)(H,{className:`mr-2 h-4 w-4`}),`Create Context`]})]})}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Contexts & Shared Contexts`}),a&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading contexts...`}),s&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:s})}),!a&&!s&&t.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No contexts found. Create one above.`}),t.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,Z.jsxs)(Vp,{children:[(0,Z.jsx)(Hp,{children:(0,Z.jsxs)(Gp,{children:[(0,Z.jsx)(Yp,{label:`Type`,sortKey:`type`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`ID`,sortKey:`id`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Owner`,sortKey:`owner`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Context URL`,sortKey:`url`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Workspace ID`,sortKey:`workspaceId`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Base URL`,sortKey:`baseUrl`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Path`,sortKey:`path`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Locked`,sortKey:`locked`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Created`,sortKey:`created`,sort:ie,onSort:L}),(0,Z.jsx)(Yp,{label:`Updated`,sortKey:`updated`,sort:ie,onSort:L}),(0,Z.jsx)(Kp,{className:`text-right`,children:`Actions`})]})}),(0,Z.jsx)(Up,{children:re.map(e=>{if(!e)return console.warn(`Found null/undefined context in contexts array, skipping`),null;let t=e.createdAt?new Date(e.createdAt).toLocaleDateString():`-`,n=e.updatedAt?new Date(e.updatedAt).toLocaleDateString():`-`,r=e.isShared||e.type===`shared`,i=r?e.ownerEmail||e.userId||`-`:`You`,a=r&&e.sharedVia?typeof e.sharedVia==`string`?e.sharedVia:e.sharedVia.accessLevel||`-`:`-`;return(0,Z.jsxs)(Gp,{children:[(0,Z.jsx)(qp,{children:r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 text-info`,title:`Shared with you (${a})`,children:[(0,Z.jsx)(_n,{className:`h-4 w-4`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`Shared`})]}):(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Owned`})}),(0,Z.jsx)(qp,{className:`font-mono text-sm`,children:e.id||`-`}),(0,Z.jsx)(qp,{className:`font-mono text-sm`,title:r?`Owned by: ${i}`:`You are the owner`,children:i}),(0,Z.jsx)(qp,{className:`font-mono text-sm max-w-xs truncate`,title:e.url||`-`,children:e.url||`-`}),(0,Z.jsx)(qp,{className:`font-mono text-sm`,children:e.workspaceId||`-`}),(0,Z.jsx)(qp,{className:`font-mono text-sm`,children:e.baseUrl||`-`}),(0,Z.jsx)(qp,{className:`font-mono text-sm`,children:e.path||`-`}),(0,Z.jsx)(qp,{children:e.locked?`Yes`:`No`}),(0,Z.jsx)(qp,{children:t}),(0,Z.jsx)(qp,{children:n}),(0,Z.jsx)(qp,{className:`text-right`,children:(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[!r&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>ee(e),title:`Edit Context`,children:(0,Z.jsx)(xt,{className:`h-4 w-4`})}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>I(e),title:r?`Open Shared Context`:`Open Context Details`,children:(0,Z.jsx)(fr,{className:`h-4 w-4`})}),!r&&(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>P(e.id),disabled:!!(e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))),className:`text-destructive hover:bg-destructive/10 hover:text-destructive disabled:opacity-50 disabled:cursor-not-allowed`,title:e.url&&(e.url.endsWith(`/default`)||e.url.includes(`://default`))?`Cannot delete default context`:`Delete Context`,children:(0,Z.jsx)(tt,{className:`h-4 w-4`})})]})})]},`${e.userId}-${e.id}`)})})]})})]}),D&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Edit Context`}),(0,Z.jsxs)(`form`,{onSubmit:te,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-id`,className:`block text-sm font-medium mb-1`,children:`Context ID (read-only)`}),(0,Z.jsx)(q,{id:`edit-context-id`,value:D.id,disabled:!0,className:`bg-muted`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-context-url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,Z.jsx)(AC,{id:`edit-context-url`,value:D.url,onChange:e=>O(t=>t?{...t,url:e}:null),placeholder:`workspace://path or /path`,pickerTitle:`Context URL path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Use format: workspace://path or /path for current workspace`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-base-url`,className:`block text-sm font-medium mb-1`,children:`Base URL (optional)`}),(0,Z.jsx)(AC,{id:`edit-base-url`,value:D.baseUrl||``,onChange:e=>O(t=>t?{...t,baseUrl:e||null}:null),format:`path`,placeholder:`/base/path`,pickerTitle:`Base path…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Restricts context navigation to this base path`})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(J,{type:`submit`,children:`Save Changes`}),(0,Z.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>O(null),children:`Cancel`})]})]})]}),(0,Z.jsx)(Zi,{open:k!==null,onOpenChange:e=>!e&&A(null),children:(0,Z.jsxs)(Ya,{children:[(0,Z.jsxs)(mi,{children:[(0,Z.jsx)(Ar,{children:`Delete Context`}),(0,Z.jsx)(Li,{children:`Are you sure you want to delete this context? This action cannot be undone.`})]}),(0,Z.jsxs)(Ka,{children:[(0,Z.jsx)(Ba,{children:`Cancel`}),(0,Z.jsx)(ji,{onClick:F,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:`Delete`})]})]})})]})}function MC(e,t){if(!e||!t)return`/`;let n=`${t}://`;if(!e.startsWith(n))return`/`;let r=e.slice(n.length).replace(/^\/+/,``).replace(/\/+$/,``);return r?`/${r}`:`/`}function NC(){let{contextId:e}=tl(),t=Jc(),n=Zc(),r=new URLSearchParams(t.search).get(`ownerId`)||void 0,i=(0,X.useMemo)(()=>{let e=new URLSearchParams(t.search),n=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(e.get(`search`)||``).trim();return n.length?n:r?[r]:[]},[t.search]),{showToast:a}=po(),{state:o,saveFilters:s,setSort:l,setAccentColor:u,setMapDocuments:d,toggleView:f,hasActiveFilters:p}=xs(),{openM2Drawer:m}=Qb(),h=km(),g=o.filters.features.allOf,_=o.filters.features.anyOf,v=o.filters.features.noneOf,y=[...Oy(o.filters.timeline),...Ty(o.filters.geo),...Ey(o.filters.lens,o.filters.geo.includeUnlocated)],b=JSON.stringify({a:g,b:_,c:v,d:y,ids:o.filters.lens.ids,sort:o.filters.sort,geoSelection:o.geoSelection,includeUnlocated:o.filters.geo.includeUnlocated}),x=(0,X.useMemo)(()=>JSON.parse(b),[b]),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(!0),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)([]),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(0),[P,F]=(0,X.useState)([]),[I,ee]=(0,X.useState)(1),[te,ne]=(0,X.useState)(50),[re,ie]=(0,X.useState)(i),[L,R]=(0,X.useState)(!1),ae=new URLSearchParams(t.search).get(`layer`),oe=!!r,se=S?MC(S.url,S.workspaceName):`/`,ce=ae?`context-layer`:`context`,z=!o.liveEnabled&&typeof S?.metadata?.toolboxSearchQuery==`string`?S.metadata.toolboxSearchQuery:``,le=oe?null:S?.workspaceName??null,[ue,de]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!le)return;let e=!1;return vi(le,Na).then(t=>{e||de({key:le,tree:t})}).catch(()=>{e||de({key:le,tree:null})}),()=>{e=!0}},[le]);let fe=le&&ue?.key===le?ue.tree:null,pe=!ae&&!oe&&fe?se===`/`?fe:Dr(fe,se):null,me=`${S?.workspaceName??``}\0${se}`,[he,ge]=(0,X.useState)(null),_e=he?.key===me?he.views:Ex(pe?.metadata),ve=he?.key===me?he.activeId:_e[0]?.id??wx.id,ye=_e.find(e=>e.id===ve)??_e[0]??wx,B=e=>ge({key:me,views:_e,activeId:e}),be=(e,t)=>{ge({key:me,views:e,activeId:t??ve}),S?.workspaceName&&Ca(S.workspaceName,se,{metadata:{...pe?.metadata??{},views:e}},Na).catch(()=>{a({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},V=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>V.current?.abort(),[]);let xe=(0,X.useCallback)(async()=>{if(!e)return;V.current?.abort();let t=new AbortController;V.current=t,j(!0);try{let n=await is(e,x.a,x.d,{...x.sort,geoSelection:x.geoSelection,includeUnlocated:x.includeUnlocated,ids:x.ids,signal:t.signal,limit:te,page:I,queries:re.length?re:void 0,anyOf:x.b,noneOf:x.c,applyContextSpec:!1},r);if(t.signal.aborted)return;k(n),N(n.totalCount||n.count||n.length)}catch(e){if(t.signal.aborted)return;a({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch documents`,variant:`destructive`}),k([]),N(0)}finally{t.signal.aborted||j(!1)}},[e,I,te,r,re,x,a]),H=(0,X.useCallback)(async()=>{if(e){T(!0);try{let t=oe?await as(e,r):await as(e);if(!t)throw Error(`No context data received.`);let n=t.workspace,i=t.workspaceId||(typeof n==`string`?n:n?.id)||``,a=t.workspaceName||(typeof n==`string`?n:n?.name)||``;C({id:t.id,userId:t.userId,url:t.url,baseUrl:t.baseUrl||null,path:t.path||null,pathArray:t.pathArray||[],workspaceId:i,workspaceName:a,acl:t.acl||{},createdAt:t.createdAt,updatedAt:t.updatedAt,locked:t.locked||!1,serverContextArray:t.serverContextArray||[],clientContextArray:t.clientContextArray||[],contextBitmapArray:t.contextBitmapArray||[],featureBitmapArray:t.featureBitmapArray||[],filterArray:t.filterArray||[],pendingUrl:t.pendingUrl||null,description:t.description||null,metadata:t.metadata||{},name:t.name??null,color:t.color??null,icon:t.icon??null}),D(null)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch context ${e}`;D(n),C(null),a({title:`Error`,description:n,variant:`destructive`})}T(!1)}},[e,r,oe,a]);(0,X.useEffect)(()=>{H()},[H]);let Se=Hf(S?.color)||null;(0,X.useEffect)(()=>(u(Se),()=>u(null)),[Se,u]);let Ce=o.geoSelection,U=S?.workspaceName||S?.workspaceId||null;(0,X.useEffect)(()=>{d(O,U)},[O,U,d]),(0,X.useEffect)(()=>()=>d([]),[d]);let W=(0,X.useMemo)(()=>Ce?O.filter(e=>Gg(e,Ce,o.filters.geo.includeUnlocated)):O,[O,Ce,o.filters.geo.includeUnlocated]),we=S?.id;(0,X.useEffect)(()=>{we&&xe()},[we,xe]),(0,X.useEffect)(()=>{let e=()=>xe();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[xe]);let[Te,Ee]=(0,X.useState)(b);Te!==b&&(Ee(b),ee(1));let[De,Oe]=(0,X.useState)(e);De!==e&&(Oe(e),ee(1),R(!1));let[ke,Ae]=(0,X.useState)(i);ke!==i&&(Ae(i),ie(i),ee(1));let[je,Me]=(0,X.useState)({urlSearchQueries:i,ignoreSavedSearch:L,savedContextSearchQuery:z});(je.urlSearchQueries!==i||je.ignoreSavedSearch!==L||je.savedContextSearchQuery!==z)&&(Me({urlSearchQueries:i,ignoreSavedSearch:L,savedContextSearchQuery:z}),!i.length&&!L&&(ie(z?[z]:[]),ee(1)));let G=(0,X.useCallback)(e=>{let r=new URLSearchParams(t.search);r.delete(`q`),r.delete(`search`);for(let t of e)r.append(`q`,t);let i=r.toString();n(`${t.pathname}${i?`?${i}`:``}`)},[t.pathname,t.search,n]),Ne=(0,X.useCallback)(e=>{let t=e.trim();if(!t)return;R(!1);let n=re.includes(t)?re:[...re,t];ie(n),G(n)},[re,G]),Pe=(0,X.useCallback)(e=>{let t=e<0?[]:re.filter((t,n)=>n!==e);t.length===0&&R(!0),ie(t),G(t)},[re,G]),Fe=(re[0]||``).trim(),Ie=!!o.activeContextType&&(o.isDirty||Fe!==(o.savedSearchQuery||z||``));(0,X.useEffect)(()=>{if(!e)return;let t=`context:${r?`${r}/`:``}${e}`,n=()=>Xu.emit(`subscribe`,{channel:t}),i=()=>Xu.emit(`unsubscribe`,{channel:t}),a=Xu.on(`connect`,n);n();let o=new Map,s=(t,n)=>{let r=Date.now(),i=`${t}:${n?.id||n?.contextId||e}`;return(o.get(i)||0)+1e3>r?!1:(o.set(i,r),!0)},c=t=>{let n=t,r=n?.context||n;(r?.id===e||r?.contextId===e)&&s(`ctx:updated`,r)&&(C(e=>e?{...e,...r}:null),r.url&&xe())},l=t=>{let n=t,r=n?.id||n?.contextId||n?.context?.id,i=n?.url||n?.context?.url;r===e&&typeof i==`string`&&s(`ctx:url`,n)&&(C(e=>e?{...e,url:i}:null),xe())},u=t=>{let n=t;(n?.contextId||n?.id||n?.context?.id)===e&&s(`doc:changed`,n)&&xe()},d=[[`context.updated`,c],[`context:updated`,c],[`context.url.set`,l],[`context:url:set`,l],[`document.inserted`,u],[`document.updated`,u],[`document.removed`,u],[`document.removed.batch`,u],[`document.linked`,u],[`document.unlinked`,u],[`document.linked.batch`,u],[`document.unlinked.batch`,u],[`document.deleted`,u],[`document.deleted.batch`,u]];return d.forEach(([e,t])=>Xu.on(e,t)),()=>{a(),i(),d.forEach(([e,t])=>Xu.off(e,t))}},[e,r,xe]);let Le=async e=>{if(S)try{await cs(S.id,[e],r,se),k(t=>t.filter(t=>t.id!==e)),N(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document removed from context.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},Re=async e=>{if(S)try{await us(S.id,[e],r,se),k(t=>t.filter(t=>t.id!==e)),N(e=>Math.max(0,e-1)),a({title:`Success`,description:`Document deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},ze=async e=>{if(S)try{await cs(S.id,e,r,se),k(t=>t.filter(t=>!e.includes(t.id))),N(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) removed.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Be=async e=>{if(S)try{await us(S.id,e,r,se),k(t=>t.filter(t=>!e.includes(t.id))),N(t=>Math.max(0,t-e.length)),a({title:`Success`,description:`${e.length} document(s) deleted.`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Ve=e=>{F(e),a({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},He=async(e,t)=>{if(!S)return!1;try{let n=await zo(S.id,e,t,r);return n&&(await xe(),F([]),a({title:`Success`,description:`${t.length} document(s) pasted to "${e}"`})),n}catch(e){return a({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Ue=async(e,t)=>{if(!S)return!1;try{let n=await bs(S.workspaceId,t,e);return n&&(await xe(),a({title:`Success`,description:`Imported ${e.length} document(s) to "${t}"`})),n}catch(e){return a({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}};if(w)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading context...`})]})});if(E&&!S)return(0,Z.jsxs)(`div`,{className:`flex items-center justify-center h-full text-destructive`,children:[`Error: `,E]});if(!S)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Context not found.`});let We=Hf(S.color);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0 max-sm:border-b`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border max-sm:hidden`,style:We?{backgroundColor:We}:void 0}),pe&&(0,Z.jsxs)(`div`,{className:`relative px-2 pt-1.5 sm:hidden`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border`,style:We?{backgroundColor:We}:void 0}),(0,Z.jsx)(Dx,{accentColor:We,views:_e,activeId:ve,onSelect:B,onSave:be,readOnly:!1})]}),(0,Z.jsxs)(`div`,{className:`flex h-12 items-center gap-2 px-4`,children:[(0,Z.jsx)(mb,{title:h?`Back to context menu`:`Back to contexts`,onBack:()=>h?m(`contexts`,`detail`,S.id):n(`/contexts`)}),(0,Z.jsx)(c,{icon:S.icon||`ph:stack-fill`,width:16,height:16,color:We,className:K(`shrink-0`,!We&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-sm font-medium`,children:S.name||S.id}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[`@ `,S.workspaceName||S.workspaceId]}),pe?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Dx,{className:`min-w-0 flex-1 self-stretch max-sm:hidden`,accentColor:We,views:_e,activeId:ve,onSelect:B,onSave:be,readOnly:!1}),(0,Z.jsx)(`div`,{className:`flex-1 sm:hidden`})]}):(0,Z.jsx)(`div`,{className:`flex-1`}),(0,Z.jsxs)(`button`,{onClick:()=>f(`tools`),className:K(`flex shrink-0 items-center gap-1.5 px-3 py-1 text-xs border rounded-md transition-colors`,p?`border-info bg-info text-info-foreground hover:bg-info/90`:o.t1Open&&o.t1View===`tools`?`bg-accent text-foreground`:`hover:bg-accent text-muted-foreground hover:text-foreground`),title:p?`Toolbox filters are active and narrow this view`:`Open the toolbox filters`,children:[(0,Z.jsx)(Qe,{className:`w-3 h-3`}),`Filter`,p?` on`:``]}),(0,Z.jsx)(pb,{})]})]}),(0,Z.jsx)(Sx,{urlType:ce,urlDisplay:S.url,contextPath:se,workspaceId:S.workspaceName||S.workspaceId,documents:W,isLoading:A,totalCount:M,currentPage:I,pageSize:te,onPageChange:ee,onPageSizeChange:e=>{ne(e),ee(1)},onRemoveDocument:se===`/`?void 0:Le,onDeleteDocument:Re,onRemoveDocuments:se===`/`?void 0:ze,onDeleteDocuments:Be,onCopyDocuments:Ve,onPasteDocuments:He,onImportDocuments:oe?void 0:Ue,pastedDocumentIds:P,backendSearchQueries:re,onBackendSearch:Ne,serverSort:o.filters.sort,onServerSortChange:l,onRemoveBackendQuery:Pe,canSaveChanges:Ie,isSavingChanges:o.isSaving,onSaveChanges:s,onUrlClick:h&&e?()=>m(`contexts`,`detail`,e):void 0,children:ye.kind===`columns`?(0,Z.jsx)(Fx,{documents:W,workspaceId:S.workspaceName||S.workspaceId,columns:ye.columns??[],onColumnsChange:e=>be(_e.map(t=>t.id===ye.id?{...t,columns:e}:t))}):ye.kind===`app`&&ye.app?(0,Z.jsx)(Mx,{app:ye.app,workspaceId:S.workspaceName||S.workspaceId,treeName:Na,path:se}):null})]})}function PC(){let{openM1Drawer:e}=Qb();return()=>e(`settings`)}function FC(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),{showToast:m}=po(),h=(0,X.useRef)(null),g=(0,X.useCallback)(async()=>{try{r(!0);let e=await Y.get(Qr.tokens),n=Array.isArray(e)?e:e.tokens||[];t(n),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch tokens`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}},[m]);(0,X.useEffect)(()=>{g()},[g]);let _=async()=>{if(!(!o.trim()||c)){l(!0);try{let e=await Y.post(Qr.tokens,{name:o});s(``),await g(),e&&e.token&&(d(e.token),setTimeout(()=>{if(h.current){h.current.focus();let e=document.createRange();e.selectNodeContents(h.current);let t=window.getSelection();t&&(t.removeAllRanges(),t.addRange(e))}},100)),m({title:`Success`,description:`Token generated successfully`,variant:`default`})}catch(e){let t=e instanceof Error?e.message:`Failed to generate token`;a(t),m({title:`Error`,description:t,variant:`destructive`})}finally{l(!1)}}},v=async e=>{if(confirm(`Are you sure you want to revoke this API token? This action cannot be undone.`))try{await Y.delete(`${Qr.tokens}/${e}`),await g(),m({title:`Success`,description:`API token revoked successfully`})}catch(e){let t=e instanceof Error?e.message:`Failed to revoke API token`;m({title:`Error`,description:t,variant:`destructive`})}},y=async e=>{try{await navigator.clipboard.writeText(e),p(!0),m({title:`Success`,description:`Token copied to clipboard`}),setTimeout(()=>p(!1),2e3)}catch{m({title:`Error`,description:`Failed to copy token to clipboard`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)(fb,{title:`API Tokens`,onBack:PC(),description:`Create and manage API tokens for programmatic access`}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Generate New API Token`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Token Name (e.g., 'CLI Access', 'Automation')`,disabled:c,className:`flex-1`}),(0,Z.jsxs)(J,{type:`button`,disabled:c||!o.trim(),onClick:_,children:[(0,Z.jsx)(H,{className:`mr-2 h-4 w-4`}),c?`Generating...`:`Generate`]})]}),u&&(0,Z.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Your New API Token`}),(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>y(u),children:f?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)($e,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ve,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-2`,children:`Make sure to copy your API token now. You won't be able to see it again!`}),(0,Z.jsx)(`div`,{ref:h,tabIndex:0,className:`p-2 bg-background border rounded font-mono text-sm break-all outline-none focus:ring-2 focus:ring-ring`,children:u})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your API Tokens`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading API tokens...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No API tokens found`}),e.length>0&&(0,Z.jsx)(`div`,{className:`border rounded-md`,children:(0,Z.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Z.jsxs)(`table`,{className:`w-full`,children:[(0,Z.jsx)(`thead`,{children:(0,Z.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Last Used`}),(0,Z.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Expires`}),(0,Z.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,Z.jsx)(`tbody`,{children:e.map(e=>(0,Z.jsxs)(`tr`,{className:`border-t`,children:[(0,Z.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,Z.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.lastUsedAt?new Date(e.lastUsedAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3`,children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,Z.jsx)(`td`,{className:`p-3 text-right`,children:(0,Z.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>v(e.id),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,children:(0,Z.jsx)(tt,{className:`h-4 w-4`})})})]},e.id))})]})})})]})]})}async function IC(){return await Y.get(Qr.devices)||[]}async function LC(e,t){return await Y.patch(`${Qr.devices}/${encodeURIComponent(e)}`,t)}async function RC(e){await Y.delete(`${Qr.devices}/${encodeURIComponent(e)}`)}async function zC(e){return await Y.get(`${Qr.workspaces}/${e}/devices`)||[]}async function BC(e,t){let n=await Y.post(`${Qr.workspaces}/${e}/devices`,{deviceId:t});return Array.isArray(n)?n:[n]}async function VC(e,t){await Y.delete(`${Qr.workspaces}/${e}/devices/${encodeURIComponent(t)}`)}function HC({device:e,onUpdated:t,onRemoved:n}){let[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(e.name),[s,c]=(0,X.useState)(e.description??``),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(!1),{showToast:h}=po(),g=Object.values(e.mirrors??{}),_=async()=>{m(!0);try{await RC(e.deviceId),n(e.deviceId),h({title:`Revoked`,description:`${e.name} can no longer sign in; a running mirror stops on its next request.`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke device`,variant:`destructive`}),f(!1)}finally{m(!1)}},v=async()=>{let n=a.trim();if(n){if(n===e.name&&s.trim()===(e.description??``)){i(!1);return}u(!0);try{let r=await LC(e.deviceId,{name:n,description:s.trim()||void 0});t({...e,...r}),i(!1),h({title:`Saved`,description:`Device updated`})}catch(e){h({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{u(!1)}}},y=()=>{o(e.name),c(e.description??``),i(!1)},b=e=>e?new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}):`—`;return(0,Z.jsx)(`div`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(me,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[r?(0,Z.jsxs)(`div`,{className:`space-y-2 mb-2`,children:[(0,Z.jsx)(q,{value:a,onChange:e=>o(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,disabled:l,onKeyDown:e=>{e.key===`Enter`&&v(),e.key===`Escape`&&y()}}),(0,Z.jsx)(q,{value:s,onChange:e=>c(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,disabled:l,onKeyDown:e=>{e.key===`Enter`&&v(),e.key===`Escape`&&y()}})]}):(0,Z.jsxs)(`div`,{className:`mb-1`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] font-mono text-muted-foreground`,children:[(0,Z.jsx)(`span`,{title:`Device ID`,children:e.deviceId}),e.platform&&(0,Z.jsx)(`span`,{children:e.platform}),e.arch&&(0,Z.jsx)(`span`,{children:e.arch}),e.type&&(0,Z.jsx)(`span`,{className:`capitalize`,children:e.type})]}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 text-[11px] text-muted-foreground`,children:[e.createdAt&&(0,Z.jsxs)(`span`,{children:[`registered `,b(e.createdAt)]}),e.updatedAt&&e.updatedAt!==e.createdAt&&(0,Z.jsxs)(`span`,{children:[`updated `,b(e.updatedAt)]}),e.lastSeen&&(0,Z.jsxs)(`span`,{children:[`seen `,b(e.lastSeen)]})]}),g.length>0&&(0,Z.jsx)(`div`,{className:`mt-3 space-y-1.5`,children:g.map(e=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-0.5 rounded-md bg-muted/50 px-2 py-1.5 text-[11px]`,children:[(0,Z.jsx)(fe,{className:`h-3.5 w-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`font-medium`,children:e.workspaceName||e.workspaceId}),e.client&&(0,Z.jsx)(`span`,{className:`font-mono uppercase text-muted-foreground`,children:e.client}),e.path&&(0,Z.jsx)(`span`,{className:`font-mono text-muted-foreground truncate max-w-[24rem]`,title:e.path,children:e.path}),(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:e.state||`idle`}),(e.pending??0)>0&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[`pending `,e.pending]}),(e.conflicts??0)>0&&(0,Z.jsxs)(`span`,{className:`text-amber-600 dark:text-amber-400`,children:[`conflicts `,e.conflicts]}),(0,Z.jsxs)(`span`,{className:`text-muted-foreground`,children:[`synced `,b(e.lastSync)]})]},e.workspaceId))})]})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:d?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{type:`button`,variant:`destructive`,size:`sm`,onClick:_,disabled:p,children:p?`Revoking…`:`Confirm revoke`}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!1),disabled:p,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}):r?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:v,disabled:l||!a.trim(),children:(0,Z.jsx)($e,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:y,disabled:l,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>i(!0),title:`Edit name / description`,children:(0,Z.jsx)(Fe,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!0),title:`Revoke this device: its tokens stop working and its mirrors stop syncing`,children:(0,Z.jsx)(Pt,{className:`h-3.5 w-3.5`})})]})})]})})}function UC(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),{showToast:i}=po(),a=async()=>{r(!0);try{t(await IC())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}};(0,X.useEffect)(()=>{(async()=>{try{t(await IC())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}})()},[i]);let o=e=>t(t=>t.map(t=>t.deviceId===e.deviceId?e:t)),s=e=>t(t=>t.filter(t=>t.deviceId!==e));return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 space-y-6`,children:[(0,Z.jsx)(fb,{compact:!0,title:`Devices`,onBack:PC(),description:`All devices registered to your account. Link them to individual workspaces in Workspace › Settings › Devices.`,actions:(0,Z.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:a,disabled:n,children:[(0,Z.jsx)(Te,{className:`mr-2 h-3.5 w-3.5 ${n?`animate-spin`:``}`}),`Refresh`]})}),n?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Te,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):e.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border p-6 text-center text-sm text-muted-foreground space-y-2`,children:[(0,Z.jsx)(me,{className:`h-8 w-8 mx-auto text-muted-foreground/40`}),(0,Z.jsx)(`p`,{children:`No devices registered yet.`}),(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`Devices register themselves automatically on first connection via`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]})]}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,Z.jsx)(HC,{device:e,onUpdated:o,onRemoved:s},e.deviceId))}),e.length>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-dashed p-3 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Gt,{className:`h-3.5 w-3.5 shrink-0`}),`To link a device to a workspace, go to Workspace › Settings › Devices.`]})]})})}var WC=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:qt},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:hr},{id:`db`,label:`Search & indexing`,description:`Rebuild indexes, tune search and choose embedding models`,icon:wt},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:me},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:Te},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:_t},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:Gt},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:ae}],GC={embedding:`db`,trash:`data`};function KC(e){return e?GC[e]?GC[e]:WC.some(t=>t.id===e)?e:`general`:`general`}var qC=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:qt},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:Gt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:Ue}];function JC(e){return e&&qC.some(t=>t.id===e)?e:`general`}var YC=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:qt},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:U},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:Re},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:mr},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:rr},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:dt},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:_}];function XC(e){return e&&YC.some(t=>t.id===e)?e:`identity`}var ZC=class{static async handleStreamingResponse(e,t={}){let{onChunk:n,onError:r,onComplete:i,signal:a}=t;try{if(!e.body)throw Error(`Response body is null - streaming not supported`);if(typeof e.body.getReader!=`function`){console.warn(`ReadableStream.getReader not available, falling back to text response`);let t=await e.text();n&&n(t),i&&i();return}let t=e.body.getReader(),r=new TextDecoder;try{for(;;){if(a?.aborted)throw t.cancel(),Error(`Stream aborted`);let{done:e,value:o}=await t.read();if(e){i&&i();break}let s=r.decode(o,{stream:!0});s&&n&&n(s)}}finally{t.releaseLock()}}catch(e){console.error(`Streaming error:`,e),r&&r(e instanceof Error?e:Error(String(e)))}}static processSSEChunk(e){let t=[],n=e.split(`
|
|
13
13
|
`),r={};for(let e of n){let n=e.trim();if(n.startsWith(`data: `))try{let e=JSON.parse(n.slice(6));r={...r,...e}}catch{console.warn(`Failed to parse SSE data:`,n)}else n===``&&(r.agentId&&r.messageId&&t.push(r),r={})}return t}},QC=class{baseUrl;constructor(e,t=`/rest/v2/agents/anthropic`){this.baseUrl=t}async chatStream(e,t){let{agentId:n,messageId:r,onMessage:i,onError:a,onComplete:o,signal:s}=t;try{let t=await fetch(`${this.baseUrl}/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/plain, text/event-stream`,"Cache-Control":`no-cache`},body:JSON.stringify({message:e,agentId:n,messageId:r}),signal:s});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);await ZC.handleStreamingResponse(t,{onChunk:e=>{try{ZC.processSSEChunk(e).forEach(e=>{i&&i(e)})}catch(e){console.warn(`Failed to process streaming chunk:`,e)}},onError:e=>{let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e.message}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)},onComplete:o,signal:s})}catch(e){let t=Error(`Chat stream failed: AnthropicConnector chatStream failed: ${e instanceof Error?e.message:String(e)}`);console.error(`Chat stream error:`,{agentId:n,messageId:r,error:t.message}),a&&a(t)}}},$C=class{wsUrl;socket=null;messageHandlers=new Map;constructor(e){this.wsUrl=e}connect(){return new Promise((e,t)=>{try{this.socket=new WebSocket(this.wsUrl),this.socket.onopen=()=>{console.log(`WebSocket connected for streaming`),e()},this.socket.onerror=e=>{console.error(`WebSocket error:`,e),t(Error(`WebSocket connection failed`))},this.socket.onmessage=e=>{try{let t=JSON.parse(e.data),n=`${t.agentId}-${t.messageId}`,r=this.messageHandlers.get(n);r&&r(t)}catch(e){console.error(`Failed to parse WebSocket message:`,e)}},this.socket.onclose=()=>{console.log(`WebSocket disconnected`),this.socket=null}}catch(e){t(e)}})}startChatStream(e,t,n,r,i){if(!this.socket||this.socket.readyState!==WebSocket.OPEN){i&&i(Error(`WebSocket not connected`));return}let a=`${e}-${t}`;this.messageHandlers.set(a,r);try{this.socket.send(JSON.stringify({type:`chat_stream`,agentId:e,messageId:t,message:n}))}catch(e){i&&i(e instanceof Error?e:Error(String(e)))}}stopChatStream(e,t){let n=`${e}-${t}`;this.messageHandlers.delete(n)}disconnect(){this.socket&&=(this.socket.close(),null),this.messageHandlers.clear()}};function ew(e){if(!e)return``;if(typeof e.errorMessage==`string`&&e.errorMessage.trim())return e.errorMessage.trim();let t=e.content;return typeof t==`string`?t:Array.isArray(t)&&t.filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
@@ -15,7 +15,7 @@ Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}
|
|
|
15
15
|
`).trim():``:``}function nw(e){if(!e)return;let t=tw(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 rw(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 iw(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:ew(e),timestamp:rw(e.timestamp),...e.role===`assistant`?{metadata:nw(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function aw(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:iw(e?.messages||[])}}function ow(e){return{current:aw(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 $C(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new QC(e.apiKey||``,e.endpoint||`${ti}/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(`${ti}/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(`${ti}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await Y.post(`${ti}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function sw(e){return await Y.get(`${ti}/agents/${e}/access`)||null}async function cw(e,t){return await Y.put(`${ti}/agents/${e}/access`,t)}async function lw(e){return await Y.post(`${ti}/agents/${e}/access/token`)}async function uw(e){await Y.delete(`${ti}/agents/${e}/access`)}async function dw(e){return await Y.get(`${ti}/agents/${e}/tools`)||{tools:[],config:{}}}async function fw(){try{return await Y.get(`${ti}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function pw(e){return await Y.get(`${ti}/agents/${e}`)}async function mw(e){return aw(await Y.get(`${ti}/agents/${e}/session`))}async function hw(e){return await Y.get(`${ti}/agents/${e}/sessions`)}async function gw(e,t){return ow(await Y.post(`${ti}/agents/${e}/sessions`,t))}async function _w(e,t){return ow(await Y.put(`${ti}/agents/${e}/session`,t))}async function vw(e,t,n){return ow(await Y.patch(`${ti}/agents/${e}/sessions/${t}`,n))}async function yw(e,t){return ow(await Y.delete(`${ti}/agents/${e}/sessions/${t}`))}async function bw(e){return await Y.get(`${ti}/agents/${e}/skills`)||[]}async function xw(e,t){return await Y.post(`${ti}/agents/${e}/skills`,t)||[]}async function Sw(e,t){return await Y.delete(`${ti}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function Cw(e){return await Y.post(`${ti}/agents`,e)}async function ww(e,t){return await Y.put(`${ti}/agents/${e}`,t)}async function Tw(e){await Y.delete(`${ti}/agents/${e}`)}async function Ew(e){return await Y.post(`${ti}/agents/${e}/start`)}async function Dw(e){return await Y.post(`${ti}/agents/${e}/stop`)}async function Ow(e){return await Y.get(`${ti}/agents/${e}/status`)}async function kw(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(`${ti}/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(`
|
|
16
16
|
|
|
17
17
|
`);f=t.pop()||``;for(let e of t){let t=e.split(`
|
|
18
|
-
`).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||{},...nw(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function Aw(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(`${ti}/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:ew(i),metadata:nw(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function jw(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function Mw(){return await Y.get(`${ti}/voice/status`)}async function Nw(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(`${ti}/agents/${e}/voice${o}`,r)}var Pw=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:WC,load:async()=>(await Pr()).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:qC,load:async()=>(await Yo()).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:YC,load:async()=>(await fw()).map(e=>({id:e.id,label:e.label||e.name}))}];function Fw({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(mu,{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,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(qn,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function Iw({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.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=>Ab(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.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,Z.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,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.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,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(Fw,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function Lw(){let{state:e}=Qb(),[t,n]=(0,X.useState)(``),r=Ob.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>Ab(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Pw.some(e=>e.sections.some(n=>Ab(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)(fb,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{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,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(Fw,{to:e.path,...e},e.path))})]},e.id)),Pw.map(e=>(0,Z.jsx)(Iw,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(Fw,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Rw=[{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`}],zw=`/wallpapers`;function Bw(e){return Rw.find(t=>t.id===e)}function Vw(e,t={}){let n=typeof e==`string`?Bw(e):e;if(!n)return null;let{base:r=zw,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 Hw(e,t=zw){let n=typeof e==`string`?Bw(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var Uw=[{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`}],Ww=`canvas:wallpaper`,Gw=`builtin:`,Kw=Rw;function qw(e){return Hw(e)??``}function Jw(e){return`${Gw}${e}`}function Yw(e){return e?.startsWith(Gw)?e.slice(8):null}function Xw(){try{let e=localStorage.getItem(Ww);if(e){let t=JSON.parse(e);if(typeof t.image==`string`||t.image===null){let e=t.fit===`fill`||t.fit===`center`?t.fit:`cover`;return{image:t.image??null,fit:e}}}}catch{}return{image:null,fit:`cover`}}function Zw(e){localStorage.setItem(Ww,JSON.stringify(e)),tT(e)}var Qw=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function $w(e){if(!e)return null;let t=Yw(e);if(t===null)return`url("${e}")`;let n=Bw(t);if(!n)return null;let r=`url("${Vw(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!Qw||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Vw(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function eT(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}function tT(e=Xw()){let t=document.documentElement.style,n=$w(e.image);if(!n){t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`);return}t.setProperty(`--wallpaper-image`,n),t.setProperty(`--wallpaper-size`,eT(e.fit))}var nT=[{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.`}],rT=`canvas:treeStyle`;function iT(){try{let e=localStorage.getItem(rT);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var aT=iT(),oT=new Set;function sT(){return aT}function cT(e){try{e===`cards`?localStorage.removeItem(rT):localStorage.setItem(rT,e)}catch{}aT=e;for(let e of oT)e()}function lT(e){oT.add(e);let t=t=>{(t.key===rT||t.key===null)&&(aT=iT(),e())};return window.addEventListener(`storage`,t),()=>{oT.delete(e),window.removeEventListener(`storage`,t)}}function uT(){return(0,X.useSyncExternalStore)(lT,sT,()=>`cards`)}function dT(){let e=uT(),t=km();return e===`accordion`||e===`accordion-mobile`&&t}var fT=[{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)`]}],pT=fT.map(e=>e.id),mT=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],hT=[{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`}],gT={theme:`canvas`,scheme:`light`,density:`auto`},_T=`canvas.ui.theme`;function vT(e){return typeof e==`string`&&pT.includes(e)}function yT(e){return e===`light`||e===`dark`||e===`system`}function bT(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function xT(e){let t=typeof e==`object`&&e?e:{};return{theme:vT(t.theme)?t.theme:gT.theme,scheme:yT(t.scheme)?t.scheme:gT.scheme,density:bT(t.density)?t.density:gT.density}}var ST=`(prefers-color-scheme: dark)`;function CT(){return typeof document<`u`}function wT(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(ST).matches}function TT(e){return e===`system`?wT()?`dark`:`light`:e}function ET(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(ST),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function DT(e){return ET(e)}function OT(){return wT()?`dark`:`light`}function kT(){return`light`}function AT(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 jT(e,t=CT()?document.documentElement:void 0){let n=TT(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,AT(t),n):n}function MT(e,t=CT()?document.documentElement:void 0){if(!t||typeof window>`u`)return jT(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=jT(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function NT(e){let t=e??IT();if(!t)return gT;try{let e=t.getItem(_T);return e?xT(JSON.parse(e)):gT}catch{return gT}}function PT(e,t){let n=t??IT();if(n)try{n.setItem(_T,JSON.stringify(e))}catch{}}function FT(e){let t=e??IT();if(t)try{t.removeItem(_T)}catch{}}function IT(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function LT({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...NT(n),...t})),o=(0,X.useSyncExternalStore)(DT,OT,kT),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{MT({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&PT(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?OT():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{FT(n),a(gT)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(Cs.Provider,{value:p,children:e})}var RT={system:me,light:Gn,dark:Pn};function zT(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=ws(),c=sm(),l=Bb(),u=uT(),d=Yb();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:fT.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`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,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)($e,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)(WT,{options:mT.map(e=>{let t=RT[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)(WT,{options:hT.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:hT.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)(WT,{options:jb.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:Rb}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:jb.find(e=>e.id===l)?.description}),l===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)(WT,{options:Vb.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:qb}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[Vb.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)(WT,{options:nT.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:cT}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:nT.find(e=>e.id===u)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)(WT,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:am}),(0,Z.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,Z.jsx)(BT,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),am(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function BT(){let[e,t]=(0,X.useState)(Xw),[n,r]=(0,X.useState)(null),i=e=>{try{Zw(e),t(e),r(null)}catch{r(`Could not store the wallpaper (browser storage full?). Try a smaller image.`)}},a=t=>{if(!t)return;if(!t.type.startsWith(`image/`)){r(`Pick an image file.`);return}let n=new FileReader;n.onload=()=>{let t=String(n.result||``);if(t.length>3670016){r(`Image too large for browser storage. Use one under ~2.5 MB.`);return}i({...e,image:t})},n.readAsDataURL(t)},o=e.image!==null&&Yw(e.image)===null,s=$w(e.image);return(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(HT,{label:`None`,isActive:e.image===null,onSelect:()=>i({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),Kw.map(t=>(0,Z.jsx)(HT,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:Yw(e.image)===t.id,onSelect:()=>i({...e,image:Jw(t.id)}),children:(0,Z.jsx)(`img`,{src:qw(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),o&&(0,Z.jsx)(HT,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(VT,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:s?{backgroundImage:s,backgroundSize:eT(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.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:[o?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>{a(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i({...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,Z.jsx)(WT,{options:Uw.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>i({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n})]})]})]})}function VT(){let e=Kw.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.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 HT({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`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,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)($e,{className:`size-3`})})]})}function UT({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function WT({options:e,value:t,onChange:n}){return(0,Z.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,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`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 GT(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`Appearance`,onBack:PC(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(zT,{})]})}var KT={previousTree:`Alt+Q`,nextTree:`Alt+W`},qT=`canvas:key-bindings`,JT=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function YT(){try{let e=JSON.parse(localStorage.getItem(qT)||`{}`),t={...KT};for(let n of Object.keys(t))(e[n]===``||JT.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...KT}:t}catch{return{...KT}}}function XT(e){localStorage.setItem(qT,JSON.stringify(e))}function ZT(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 QT(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function $T(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function eE(){let[e,t]=(0,X.useState)(YT),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{XT(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`Key bindings`,onBack:PC(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.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)||KT[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.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)||KT[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...KT}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var tE=`offline-content-v1`,nE=`offline-api-v1`,rE=1073741824,iE={enabled:!1,budgetBytes:4*rE,excludedWorkspaces:[]},aE=1e3;function oE(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function sE(e,t,n){return`${e}:${t}:${oE(n)}`}var cE=`canvas-offline`,lE=2,uE=null;function dE(){return uE||(uE=new Promise((e,t)=>{let n=indexedDB.open(cE,lE);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(),uE=null},e(n.result)},n.onerror=()=>{uE=null,t(n.error)}}),uE)}function fE(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function pE(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function mE(e,t){return pE((await dE()).transaction(e).objectStore(e).get(t))}async function hE(e){return pE((await dE()).transaction(e).objectStore(e).getAll())}async function gE(e,t,n){let r=(await dE()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),fE(r)}async function _E(e,t){let n=(await dE()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),fE(n)}async function vE(e){let t=(await dE()).transaction(e,`readwrite`);return t.objectStore(e).clear(),fE(t)}async function yE(){try{let e=await mE(`config`,`settings`);return e?{...iE,...e}:iE}catch{return iE}}async function bE(e){await gE(`config`,e,`settings`)}async function xE(e,t){let n=(await dE()).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 fE(n)}async function SE(e){let t=await hE(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-aE)),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(nE),caches.open(tE)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await _E(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await _E(`entries`,e.url)})])}async function CE(){let e=await hE(`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 wE(){await Promise.all([caches.delete(tE),caches.delete(nE)]),await vE(`entries`),await vE(`scopes`)}async function TE(){return hE(`scopes`)}async function EE(e){return mE(`scopes`,e)}async function DE(e){await gE(`scopes`,e)}async function OE(e){let t=await mE(`scopes`,e);await _E(`scopes`,e),t?.urls.length&&await kE(t.urls)}async function kE(e){let t=await hE(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await xE(r,!1)}var AE=3,jE=`data/schema/file`,ME=128;async function NE({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await yE();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=sE(e,n,t),s=oE(t),c=await EE(o),l=((await Ki(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===jE),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(AE,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Yr(e,t.id);d+=n.size,u.push(`${Qr.workspaces}/${e}/documents/${t.id}/content`);try{await di(e,t.id,ME),u.push(`${Qr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${ME}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await xE(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 DE(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await kE(t)}return g}var PE=[{label:`1 GB`,bytes:1*rE},{label:`2 GB`,bytes:2*rE},{label:`4 GB`,bytes:4*rE},{label:`8 GB`,bytes:8*rE}];function FE(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/rE).toFixed(2)} GB`}function IE(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function LE(){let{showSuccessToast:e,showErrorToast:t}=to(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{yE().then(r).catch(()=>{}),CE().then(a).catch(()=>{}),TE().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Pr().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await bE(e),IE(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),SE(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 wE(),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=sE(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await NE(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${FE(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${FE(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},w=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},T=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),E=async e=>{await OE(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(RE,{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,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`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,Z.jsx)(C,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.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,Z.jsx)($e,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:PE.map(e=>(0,Z.jsx)(J,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[FE(i.contentBytes),` of `,FE(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${FE(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,Z.jsx)(Mt,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(RE,{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,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(J,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(ne,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.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,Z.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,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${FE(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[FE(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>S(T(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(Te,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>E(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.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,Z.jsxs)(`section`,{children:[(0,Z.jsx)(RE,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(vt,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(J,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(pp,{onClose:()=>_(!1),children:(0,Z.jsx)(dp,{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:w,onClose:()=>_(!1)})})]}):null}function RE({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function zE(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`Offline`,onBack:PC(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(LE,{})]})}function BE(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 VE({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function HE(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.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 ${BE(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`About`,onBack:PC(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(VE,{name:`Canvas Web`,detail:`this interface`,version:`v2.14.15`}),e?.version&&(0,Z.jsx)(VE,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(VE,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var UE=[`onnx`,`clip`,`blip`,`openai`],WE=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],GE=[{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`}],KE=e=>`${Qr.workspaces}/${encodeURIComponent(e)}/inferd`;function qE(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 JE(e){return await Y.get(`${KE(e)}/status`)}async function YE(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await Y.post(`${KE(e)}/summarize/images`,n)}async function XE(e){return await Y.post(`${KE(e)}/summarize/images/stop`,{})}async function ZE(e){return await Y.get(`${KE(e)}/config`)}async function QE(e,t){return await Y.put(`${KE(e)}/config`,t)}async function $E(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(`${KE(e)}/reindex`,n)}async function eD(e){return await Y.get(`${KE(e)}/vector-tables`)}async function tD(e,t){return await Y.delete(`${KE(e)}/vector-tables/${encodeURIComponent(t)}`)}async function nD(){return await Y.get(`${Qr.inferd}/config`)}async function rD(e){return await Y.put(`${Qr.inferd}/config`,e)}async function iD(){return await Y.get(`${Qr.inferd}/defaults`)}async function aD(e){return await Y.put(`${Qr.inferd}/defaults`,e)}async function oD(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await Y.post(`${Qr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function sD(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await Y.post(`${Qr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var cD=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,lD=`font-semibold uppercase tracking-[0.08em]`,uD={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`}},dD=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],fD=[{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.`}],pD=12e4;function mD(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 hD({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,lD),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function gD({overridden:e,source:t}){return e?(0,Z.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,Z.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 _D({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,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(gD,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.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,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function vD({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(gD,{overridden:n})]})}function yD({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(gD,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{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,Z.jsx)(q,{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,Z.jsx)(J,{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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function bD({open:e,onClick:t,label:n}){return(0,Z.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,Z.jsx)(Ge,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var xD={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function SD({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}=po(),[f,p]=(0,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.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}`)}},F=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),I=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=F(n),a=i.type?uD[i.type]?.url?.key:void 0,o=a?mD(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await oD(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 sD(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)}},ee=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?uD[i]?.url?.key:void 0;if(!a)continue;let o=mD(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),ne=async()=>{if(ee.length>0){d({title:`Fix the endpoint first`,description:ee.join(` · `),variant:`destructive`});return}await u(qE(f,m)),h(new Set)},re=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(hD,{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,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.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,Z.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,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,xD[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.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,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,lD),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.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,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.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,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>I(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(ye,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(bD,{open:m,onClick:()=>re(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(gD,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:cD,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(_D,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(_D,{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,Z.jsx)(_D,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(vD,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(vD,{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,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{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,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(hD,{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,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=WE.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?uD[l]:void 0,d=u?.url?mD(n[u.url.key]):null,p={...r,...n},h=dD.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,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(bD,{open:s,onClick:()=>re(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(gD,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:cD,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),UE.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!UE.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(_D,{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,Z.jsx)(_D,{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,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(gD,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:cD,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),fD.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:fD.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(_D,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??pD,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,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{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,Z.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,Z.jsx)(yD,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.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,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.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,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{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,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),GE.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(J,{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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:ne,disabled:s||!te||ee.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:ee.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[ee.length,` endpoint `,ee.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function CD(){let{showToast:e}=po(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>nD().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(fb,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:PC(),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,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(Te,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Te,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(SD,{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 rD(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 wD(){let e=Jc(),{showToast:t}=po(),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,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.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,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(fb,{onBack:PC(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(J,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(qu,{className:`mt-8`})]})}function TD(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 ED(){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 DD={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?`${Qr.admin.users}?${n}`:Qr.admin.users;return await Y.get(r)},async getUser(e){return await Y.get(`${Qr.admin.users}/${e}`)},async createUser(e){return await Y.post(Qr.admin.users,e)},async updateUser(e,t){return await Y.put(`${Qr.admin.users}/${e}`,t)},async deleteUser(e){await Y.delete(`${Qr.admin.users}/${e}`)}},OD={async listAllWorkspaces(){return await Y.get(Qr.admin.workspaces)},async createWorkspace(e){return await Y.post(Qr.admin.workspaces,e)},async deleteWorkspace(e){await Y.delete(`${Qr.admin.workspaces}/${e}`)}},kD={async getLogs(e={}){return(await Y.get(`${Qr.admin.logs}${TD(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${Qr.admin.logsStream}${TD(e)}`,{method:`GET`,headers:ED(),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(`
|
|
18
|
+
`).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||{},...nw(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function Aw(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(`${ti}/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:ew(i),metadata:nw(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function jw(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function Mw(){return await Y.get(`${ti}/voice/status`)}async function Nw(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(`${ti}/agents/${e}/voice${o}`,r)}var Pw=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:WC,load:async()=>(await Pr()).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:qC,load:async()=>(await Yo()).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:YC,load:async()=>(await fw()).map(e=>({id:e.id,label:e.label||e.name}))}];function Fw({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(mu,{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,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(qn,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function Iw({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.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=>Ab(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.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,Z.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,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.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,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(Fw,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function Lw(){let{state:e}=Qb(),[t,n]=(0,X.useState)(``),r=Ob.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>Ab(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Pw.some(e=>e.sections.some(n=>Ab(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)(fb,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{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,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(Fw,{to:e.path,...e},e.path))})]},e.id)),Pw.map(e=>(0,Z.jsx)(Iw,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(Fw,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Rw=[{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`}],zw=`/wallpapers`;function Bw(e){return Rw.find(t=>t.id===e)}function Vw(e,t={}){let n=typeof e==`string`?Bw(e):e;if(!n)return null;let{base:r=zw,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 Hw(e,t=zw){let n=typeof e==`string`?Bw(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var Uw=[{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`}],Ww=`canvas:wallpaper`,Gw=`builtin:`,Kw=Rw;function qw(e){return Hw(e)??``}function Jw(e){return`${Gw}${e}`}function Yw(e){return e?.startsWith(Gw)?e.slice(8):null}function Xw(){try{let e=localStorage.getItem(Ww);if(e){let t=JSON.parse(e);if(typeof t.image==`string`||t.image===null){let e=t.fit===`fill`||t.fit===`center`?t.fit:`cover`;return{image:t.image??null,fit:e}}}}catch{}return{image:null,fit:`cover`}}function Zw(e){localStorage.setItem(Ww,JSON.stringify(e)),tT(e)}var Qw=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function $w(e){if(!e)return null;let t=Yw(e);if(t===null)return`url("${e}")`;let n=Bw(t);if(!n)return null;let r=`url("${Vw(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!Qw||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Vw(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function eT(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}function tT(e=Xw()){let t=document.documentElement.style,n=$w(e.image);if(!n){t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`);return}t.setProperty(`--wallpaper-image`,n),t.setProperty(`--wallpaper-size`,eT(e.fit))}var nT=[{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.`}],rT=`canvas:treeStyle`;function iT(){try{let e=localStorage.getItem(rT);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var aT=iT(),oT=new Set;function sT(){return aT}function cT(e){try{e===`cards`?localStorage.removeItem(rT):localStorage.setItem(rT,e)}catch{}aT=e;for(let e of oT)e()}function lT(e){oT.add(e);let t=t=>{(t.key===rT||t.key===null)&&(aT=iT(),e())};return window.addEventListener(`storage`,t),()=>{oT.delete(e),window.removeEventListener(`storage`,t)}}function uT(){return(0,X.useSyncExternalStore)(lT,sT,()=>`cards`)}function dT(){let e=uT(),t=km();return e===`accordion`||e===`accordion-mobile`&&t}var fT=[{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)`]}],pT=fT.map(e=>e.id),mT=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],hT=[{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`}],gT={theme:`canvas`,scheme:`light`,density:`auto`},_T=`canvas.ui.theme`;function vT(e){return typeof e==`string`&&pT.includes(e)}function yT(e){return e===`light`||e===`dark`||e===`system`}function bT(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function xT(e){let t=typeof e==`object`&&e?e:{};return{theme:vT(t.theme)?t.theme:gT.theme,scheme:yT(t.scheme)?t.scheme:gT.scheme,density:bT(t.density)?t.density:gT.density}}var ST=`(prefers-color-scheme: dark)`;function CT(){return typeof document<`u`}function wT(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(ST).matches}function TT(e){return e===`system`?wT()?`dark`:`light`:e}function ET(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(ST),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function DT(e){return ET(e)}function OT(){return wT()?`dark`:`light`}function kT(){return`light`}function AT(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 jT(e,t=CT()?document.documentElement:void 0){let n=TT(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,AT(t),n):n}function MT(e,t=CT()?document.documentElement:void 0){if(!t||typeof window>`u`)return jT(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=jT(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function NT(e){let t=e??IT();if(!t)return gT;try{let e=t.getItem(_T);return e?xT(JSON.parse(e)):gT}catch{return gT}}function PT(e,t){let n=t??IT();if(n)try{n.setItem(_T,JSON.stringify(e))}catch{}}function FT(e){let t=e??IT();if(t)try{t.removeItem(_T)}catch{}}function IT(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function LT({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...NT(n),...t})),o=(0,X.useSyncExternalStore)(DT,OT,kT),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{MT({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&PT(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?OT():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{FT(n),a(gT)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(Cs.Provider,{value:p,children:e})}var RT={system:me,light:Gn,dark:Pn};function zT(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=ws(),c=sm(),l=Bb(),u=uT(),d=Yb();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:fT.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`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,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)($e,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)(WT,{options:mT.map(e=>{let t=RT[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)(WT,{options:hT.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:hT.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)(WT,{options:jb.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:Rb}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:jb.find(e=>e.id===l)?.description}),l===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)(WT,{options:Vb.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:qb}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[Vb.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)(WT,{options:nT.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:cT}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:nT.find(e=>e.id===u)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)(WT,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:am}),(0,Z.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,Z.jsx)(BT,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),am(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function BT(){let[e,t]=(0,X.useState)(Xw),[n,r]=(0,X.useState)(null),i=e=>{try{Zw(e),t(e),r(null)}catch{r(`Could not store the wallpaper (browser storage full?). Try a smaller image.`)}},a=t=>{if(!t)return;if(!t.type.startsWith(`image/`)){r(`Pick an image file.`);return}let n=new FileReader;n.onload=()=>{let t=String(n.result||``);if(t.length>3670016){r(`Image too large for browser storage. Use one under ~2.5 MB.`);return}i({...e,image:t})},n.readAsDataURL(t)},o=e.image!==null&&Yw(e.image)===null,s=$w(e.image);return(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(UT,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(HT,{label:`None`,isActive:e.image===null,onSelect:()=>i({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),Kw.map(t=>(0,Z.jsx)(HT,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:Yw(e.image)===t.id,onSelect:()=>i({...e,image:Jw(t.id)}),children:(0,Z.jsx)(`img`,{src:qw(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),o&&(0,Z.jsx)(HT,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(VT,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:s?{backgroundImage:s,backgroundSize:eT(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.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:[o?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>{a(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i({...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,Z.jsx)(WT,{options:Uw.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>i({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n})]})]})]})}function VT(){let e=Kw.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.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 HT({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`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,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)($e,{className:`size-3`})})]})}function UT({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function WT({options:e,value:t,onChange:n}){return(0,Z.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,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`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 GT(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`Appearance`,onBack:PC(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(zT,{})]})}var KT={previousTree:`Alt+Q`,nextTree:`Alt+W`},qT=`canvas:key-bindings`,JT=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function YT(){try{let e=JSON.parse(localStorage.getItem(qT)||`{}`),t={...KT};for(let n of Object.keys(t))(e[n]===``||JT.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...KT}:t}catch{return{...KT}}}function XT(e){localStorage.setItem(qT,JSON.stringify(e))}function ZT(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 QT(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function $T(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function eE(){let[e,t]=(0,X.useState)(YT),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{XT(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`Key bindings`,onBack:PC(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.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)||KT[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.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)||KT[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.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,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...KT}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var tE=`offline-content-v1`,nE=`offline-api-v1`,rE=1073741824,iE={enabled:!1,budgetBytes:4*rE,excludedWorkspaces:[]},aE=1e3;function oE(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function sE(e,t,n){return`${e}:${t}:${oE(n)}`}var cE=`canvas-offline`,lE=2,uE=null;function dE(){return uE||(uE=new Promise((e,t)=>{let n=indexedDB.open(cE,lE);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(),uE=null},e(n.result)},n.onerror=()=>{uE=null,t(n.error)}}),uE)}function fE(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function pE(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function mE(e,t){return pE((await dE()).transaction(e).objectStore(e).get(t))}async function hE(e){return pE((await dE()).transaction(e).objectStore(e).getAll())}async function gE(e,t,n){let r=(await dE()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),fE(r)}async function _E(e,t){let n=(await dE()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),fE(n)}async function vE(e){let t=(await dE()).transaction(e,`readwrite`);return t.objectStore(e).clear(),fE(t)}async function yE(){try{let e=await mE(`config`,`settings`);return e?{...iE,...e}:iE}catch{return iE}}async function bE(e){await gE(`config`,e,`settings`)}async function xE(e,t){let n=(await dE()).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 fE(n)}async function SE(e){let t=await hE(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-aE)),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(nE),caches.open(tE)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await _E(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await _E(`entries`,e.url)})])}async function CE(){let e=await hE(`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 wE(){await Promise.all([caches.delete(tE),caches.delete(nE)]),await vE(`entries`),await vE(`scopes`)}async function TE(){return hE(`scopes`)}async function EE(e){return mE(`scopes`,e)}async function DE(e){await gE(`scopes`,e)}async function OE(e){let t=await mE(`scopes`,e);await _E(`scopes`,e),t?.urls.length&&await kE(t.urls)}async function kE(e){let t=await hE(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await xE(r,!1)}var AE=3,jE=`data/schema/file`,ME=128;async function NE({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await yE();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=sE(e,n,t),s=oE(t),c=await EE(o),l=((await Ki(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===jE),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(AE,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Yr(e,t.id);d+=n.size,u.push(`${Qr.workspaces}/${e}/documents/${t.id}/content`);try{await di(e,t.id,ME),u.push(`${Qr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${ME}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await xE(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 DE(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await kE(t)}return g}var PE=[{label:`1 GB`,bytes:1*rE},{label:`2 GB`,bytes:2*rE},{label:`4 GB`,bytes:4*rE},{label:`8 GB`,bytes:8*rE}];function FE(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/rE).toFixed(2)} GB`}function IE(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function LE(){let{showSuccessToast:e,showErrorToast:t}=to(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{yE().then(r).catch(()=>{}),CE().then(a).catch(()=>{}),TE().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Pr().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await bE(e),IE(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),SE(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 wE(),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=sE(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await NE(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${FE(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${FE(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},w=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},T=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),E=async e=>{await OE(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(RE,{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,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`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,Z.jsx)(C,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.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,Z.jsx)($e,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:PE.map(e=>(0,Z.jsx)(J,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[FE(i.contentBytes),` of `,FE(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${FE(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(J,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,Z.jsx)(Mt,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(RE,{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,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(J,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(ne,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.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,Z.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,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${FE(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[FE(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>S(T(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(Te,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(J,{variant:`ghost`,size:`sm`,onClick:()=>E(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.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,Z.jsxs)(`section`,{children:[(0,Z.jsx)(RE,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(vt,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(J,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(pp,{onClose:()=>_(!1),children:(0,Z.jsx)(dp,{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:w,onClose:()=>_(!1)})})]}):null}function RE({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function zE(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`Offline`,onBack:PC(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(LE,{})]})}function BE(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 VE({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function HE(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.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 ${BE(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)(fb,{className:`mb-6`,title:`About`,onBack:PC(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(VE,{name:`Canvas Web`,detail:`this interface`,version:`v2.14.16`}),e?.version&&(0,Z.jsx)(VE,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(VE,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var UE=[`onnx`,`clip`,`blip`,`openai`],WE=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],GE=[{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`}],KE=e=>`${Qr.workspaces}/${encodeURIComponent(e)}/inferd`;function qE(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 JE(e){return await Y.get(`${KE(e)}/status`)}async function YE(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await Y.post(`${KE(e)}/summarize/images`,n)}async function XE(e){return await Y.post(`${KE(e)}/summarize/images/stop`,{})}async function ZE(e){return await Y.get(`${KE(e)}/config`)}async function QE(e,t){return await Y.put(`${KE(e)}/config`,t)}async function $E(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(`${KE(e)}/reindex`,n)}async function eD(e){return await Y.get(`${KE(e)}/vector-tables`)}async function tD(e,t){return await Y.delete(`${KE(e)}/vector-tables/${encodeURIComponent(t)}`)}async function nD(){return await Y.get(`${Qr.inferd}/config`)}async function rD(e){return await Y.put(`${Qr.inferd}/config`,e)}async function iD(){return await Y.get(`${Qr.inferd}/defaults`)}async function aD(e){return await Y.put(`${Qr.inferd}/defaults`,e)}async function oD(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await Y.post(`${Qr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function sD(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await Y.post(`${Qr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var cD=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,lD=`font-semibold uppercase tracking-[0.08em]`,uD={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`}},dD=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],fD=[{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.`}],pD=12e4;function mD(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 hD({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,lD),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function gD({overridden:e,source:t}){return e?(0,Z.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,Z.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 _D({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,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(gD,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.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,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function vD({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(gD,{overridden:n})]})}function yD({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(gD,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{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,Z.jsx)(q,{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,Z.jsx)(J,{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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function bD({open:e,onClick:t,label:n}){return(0,Z.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,Z.jsx)(Ge,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var xD={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function SD({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}=po(),[f,p]=(0,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.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}`)}},F=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),I=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=F(n),a=i.type?uD[i.type]?.url?.key:void 0,o=a?mD(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await oD(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 sD(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)}},ee=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?uD[i]?.url?.key:void 0;if(!a)continue;let o=mD(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),te=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),ne=async()=>{if(ee.length>0){d({title:`Fix the endpoint first`,description:ee.join(` · `),variant:`destructive`});return}await u(qE(f,m)),h(new Set)},re=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(hD,{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,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.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,Z.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,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,xD[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.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,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,lD),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.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,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.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,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>I(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(ye,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(bD,{open:m,onClick:()=>re(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(gD,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:cD,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(_D,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(_D,{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,Z.jsx)(_D,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(vD,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(vD,{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,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{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,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(hD,{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,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=WE.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?uD[l]:void 0,d=u?.url?mD(n[u.url.key]):null,p={...r,...n},h=dD.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,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(bD,{open:s,onClick:()=>re(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(gD,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:cD,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),UE.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!UE.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(_D,{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,Z.jsx)(_D,{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,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(gD,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:cD,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),fD.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:fD.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(_D,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??pD,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,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{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,Z.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,Z.jsx)(yD,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.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,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.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,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{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,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),GE.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(J,{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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:te?`default`:`outline`,onClick:ne,disabled:s||!te||ee.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!te,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:ee.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[ee.length,` endpoint `,ee.length===1?`needs`:`need`,` fixing`]}):te?`Unsaved changes`:`Everything saved`})]})]})}function CD(){let{showToast:e}=po(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>nD().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)(fb,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:PC(),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,Z.jsxs)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(Te,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(Te,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(SD,{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 rD(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 wD(){let e=Jc(),{showToast:t}=po(),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,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.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,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(fb,{onBack:PC(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(J,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(qu,{className:`mt-8`})]})}function TD(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 ED(){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 DD={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?`${Qr.admin.users}?${n}`:Qr.admin.users;return await Y.get(r)},async getUser(e){return await Y.get(`${Qr.admin.users}/${e}`)},async createUser(e){return await Y.post(Qr.admin.users,e)},async updateUser(e,t){return await Y.put(`${Qr.admin.users}/${e}`,t)},async deleteUser(e){await Y.delete(`${Qr.admin.users}/${e}`)}},OD={async listAllWorkspaces(){return await Y.get(Qr.admin.workspaces)},async createWorkspace(e){return await Y.post(Qr.admin.workspaces,e)},async deleteWorkspace(e){await Y.delete(`${Qr.admin.workspaces}/${e}`)}},kD={async getLogs(e={}){return(await Y.get(`${Qr.admin.logs}${TD(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${Qr.admin.logsStream}${TD(e)}`,{method:`GET`,headers:ED(),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(`
|
|
19
19
|
`),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(`
|
|
20
20
|
`));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(`
|
|
21
21
|
|