@augmentd-labs/canvas-web 2.26.2 → 2.26.4

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,7 +1,7 @@
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-XoABNf32.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BQnKd3jw.js","assets/sanitize-DrVcFY1Q.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/markdown-html-DtQ7-esK.css","assets/SketchEditor-BBVmOe4V.js","assets/react-BzqgEMSQ.js","assets/ui-NWo4bzrd.js","assets/utils-BxVxyehK.js","assets/alert-dialog-CDKOX-MP.js","assets/utils-2pl1SbIp.js","assets/blobs-NdFfDbao.js","assets/workspace-C0wQoX6y.js","assets/sha256-CKJV7klZ.js","assets/chunk-K2UTITRG-zQFDOW3Q.js","assets/chunk-SRAX5OIU-Dhm3gOdh.js","assets/chunk-6U3AYISY-C6-Mtja1.js","assets/chunk-Z3N5DIM6-D9TMVU7m.js","assets/EditorOverlay-DqlaCJe7.js","assets/SketchEditor-DtRVLazd.css","assets/TextDocumentEditor-C0IJWp9j.js","assets/text-documents-kZCt9P5G.js","assets/LocationTab-BONJQfYM.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/subtree-transfer-dialog-CSjPDp4d.js","assets/NextShell-Cm0yiVMy.js","assets/NextShell-BT6-_CFY.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{a,i as o,l as s,n as c,r as l,t as u,u as d}from"./code-editor-BQnKd3jw.js";import{_t as f,gt as p,vt as m,yt as h}from"./react-BzqgEMSQ.js";import{t as g}from"./preload-helper-Czpn1I53.js";import{$ as _,$n as v,$r as y,$t as b,An as x,Ar as S,At as C,B as w,Bn as T,Br as E,Bt as D,C as O,Cn as k,Cr as A,Ct as j,Dn as M,Dr as N,Dt as P,En as F,Er as I,Et as L,F as R,Fr as z,Ft as ee,G as te,Gn as ne,Gr as B,Gt as re,H as ie,Hn as ae,Hr as oe,Ht as V,I as H,Ir as U,It as se,J as W,Jn as ce,Jr as le,Jt as ue,K as de,Kn as fe,Kr as pe,Kt as me,L as G,Ln as he,Lr as ge,Lt as _e,Mn as ve,Mr as K,Mt as q,Nn as ye,Nr as be,Nt as xe,On as Se,Or as Ce,Ot as we,P 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 Ne,Rn as Pe,Rr as Fe,Rt as Ie,S as Le,Sn as Re,Sr as ze,St as Be,Tn as Ve,Tr as He,Tt as Ue,U as We,Un as Ge,Ur as Ke,Ut as qe,V as Je,Vn as Ye,Vr as Xe,Vt as Ze,W as Qe,Wn as $e,Wr as et,Wt as tt,X as nt,Xn as rt,Xr as it,Xt as at,Y as ot,Yn as st,Yr as ct,Yt as lt,Z as ut,Zn as dt,Zr as ft,Zt as pt,_ as mt,_i as ht,_n as gt,_r as _t,_t as vt,ai as yt,an as bt,ar as xt,at as St,b as Ct,bn as wt,br as Tt,bt as Et,ci as Dt,cn as Ot,cr as kt,ct as At,d as jt,di 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,fn as Vt,fr as Ht,ft as Ut,g as Wt,gi as Gt,gn as Kt,gr as qt,gt as Jt,h as Yt,hi as Xt,hn as Zt,hr as Qt,ht as $t,ii as en,in as tn,ir as nn,it as rn,jn as an,jr as on,jt as sn,kn as cn,kr as ln,kt as un,li as dn,ln as fn,lr as pn,lt as mn,m as hn,mi as gn,mn as _n,mr as vn,mt as yn,ni as bn,nn as xn,nr as Sn,nt as Cn,oi as wn,on as Tn,or as En,ot as Dn,p as On,pi as kn,pr as An,pt as jn,q as Mn,qn as Nn,qr as Pn,qt as Fn,ri as In,rn as Ln,rr as Rn,rt as zn,si as Bn,sn as Vn,sr as Hn,st as Un,tn as Wn,tr as Gn,tt as Kn,u as qn,ui as Jn,un as Yn,ur as Xn,ut as Zn,v as Qn,vn as $n,vr as er,vt as tr,w as nr,wr as rr,wt as ir,x as ar,xn as or,xr as sr,xt as cr,y as lr,yn as ur,yr as dr,yt as fr,z as pr,zn as mr,zr as hr,zt as gr}from"./ui-NWo4bzrd.js";import{i as _r,n as vr,r as yr}from"./utils-BxVxyehK.js";import{n as br,t as J}from"./utils-2pl1SbIp.js";import{_ as xr,a as Sr,b as Y,c as Cr,d as wr,f as Tr,g as Er,h as Dr,i as Or,l as kr,m as Ar,n as jr,o as Mr,p as Nr,r as Pr,s as Fr,t as Ir,u as X,v as Lr,x as Z,y as Rr}from"./alert-dialog-CDKOX-MP.js";import{t as zr}from"./socket-hM4c-ZSl.js";import{a as Br,c as Vr,i as Hr,n as Ur,o as Wr,s as Gr,t as Kr}from"./blobs-NdFfDbao.js";import{$ as qr,A as Jr,An as Yr,At as Xr,B as Zr,Bt as Qr,C as $r,Cn as ei,Ct as ti,D as ni,Dn as ri,Dt as ii,E as ai,Et as oi,F as si,Ft as ci,G as li,Gt as ui,H as di,Hn as fi,Ht as pi,I as mi,It as hi,J as gi,Jt as _i,K as vi,Kt as yi,L as bi,Ln as xi,Lt as Si,M as Ci,Mn as wi,Mt as Ti,Nn as Ei,Nt as Di,O as Oi,On as ki,Ot as Ai,P as ji,Pn as Mi,Pt as Ni,Q as Pi,Qt as Fi,R as Ii,Rt as Li,S as Ri,Sn as zi,St as Bi,T as Vi,Tn as Hi,Tt as Ui,U as Wi,Un as Gi,Ut as Ki,V as qi,Vn as Ji,Vt as Yi,W as Xi,Wn as Zi,Wt as Qi,X as $i,Xt as ea,Y as ta,Yt as na,Z as ra,Zt as ia,_ as aa,_n as oa,_t as sa,a as ca,an as la,at as ua,b as da,bn as fa,bt as pa,c as ma,cn as ha,ct as ga,d as _a,dn as va,dt as ya,en as ba,et as xa,f as Sa,fn as Ca,ft as wa,g as Ta,gn as Ea,gt as Da,h as Oa,hn as ka,ht as Aa,i as ja,in as Ma,it as Na,j as Pa,jn as Fa,jt as Ia,k as La,kn as Ra,kt as za,l as Ba,ln as Va,lt as Ha,m as Ua,mn as Wa,mt as Ga,n as Ka,nn as qa,nt as Ja,o as Ya,on as Xa,ot as Za,p as Qa,pn as $a,pt as eo,q as to,qt as no,r as ro,rn as io,rt as ao,s as oo,sn as so,st as co,t as lo,tn as uo,tt as fo,u as po,un as mo,ut as ho,v as go,vn as _o,vt as vo,w as yo,wn as bo,wt as xo,x as So,xn as Co,xt as wo,y as To,yn as Eo,yt as Do,z as Oo,zn as ko,zt as Ao}from"./workspace-C0wQoX6y.js";import{_ as jo,a as Mo,c as No,d as Po,f as Fo,g as Io,h as Lo,i as Ro,l as zo,m as Bo,n as Vo,o as Ho,p as Uo,r as Wo,s as Go,t as Ko,u as qo,v as Jo,y as Yo}from"./text-documents-kZCt9P5G.js";import{n as Xo,t as Zo}from"./map-BxCwdK0d.js";import{t as Qo}from"./search-COMZIxA7.js";import{A as $o,B as es,C as ts,D as ns,E as rs,F as is,H as as,I as os,L as ss,M as cs,N as ls,O as us,P as ds,R as fs,S as ps,T as ms,V as hs,_ as gs,a as _s,b as vs,c as ys,d as bs,f as xs,g as Ss,h as Cs,i as ws,j as Ts,k as Es,l as Ds,m as Os,o as ks,p as As,r as js,s as Ms,t as Ns,u as Ps,v as Fs,w as Is,x as Ls,y as Rs,z as zs}from"./sha256-CKJV7klZ.js";import{t as Bs}from"./sanitize-DrVcFY1Q.js";import{t as Vs}from"./markdown-it-DRESbtwK.js";import{n as Hs,t as Us}from"./use-theme-Bd8sb5Ox.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Q=n(d(),1),Ws=m(),Gs=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,Ks=/^[\\/]{2}/;function qs(e,t){return t+e.replace(/\\/g,`/`)}var Js=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(Js||{}),Ys=`popstate`;function Xs(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function Zs(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return nc(``,{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:rc(t)}return ac(t,n,null,e)}function Qs(e,t){if(e===!1||e==null)throw Error(t)}function $s(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function ec(){return Math.random().toString(36).substring(2,10)}function tc(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 nc(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?ic(t):t,state:n,key:t&&t.key||r||ec(),mask:i}}function rc({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 ic(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 ac(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=Xs(e)?e:nc(h.location,e,t);n&&n(r,e),l=u()+1;let d=tc(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=Xs(e)?e:nc(h.location,e,t);n&&n(r,e),l=u();let i=tc(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 oc(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(Ys,d),c=e,()=>{i.removeEventListener(Ys,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 oc(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Qs(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:rc(t);return i=i.replace(/ $/,`%20`),!n&&Ks.test(i)&&(i=r+i),new URL(i,r)}function sc(e,t,n=`/`){return cc(e,t,n,!1)}function cc(e,t,n,r,i){let a=Dc((typeof t==`string`?ic(t):t).pathname||`/`,n);if(a==null)return null;let o=i??lc(e),s=null,c=Ec(a);for(let e=0;s==null&&e<o.length;++e)s=Sc(o[e],c,r);return s}function lc(e){let t=uc(e);return fc(t),t}function uc(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;Qs(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=Fc([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Qs(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),uc(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:bc(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Tc(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 dc(e.path))a(e,t,!0,n)}),t}function dc(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=dc(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 fc(e){e.sort((e,t)=>e.score===t.score?xc(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var pc=/^:[\w-]+$/,mc=3,hc=2,gc=1,_c=10,vc=-2,yc=e=>e===`*`;function bc(e,t){let n=e.split(`/`),r=n.length;return n.some(yc)&&(r+=vc),t&&(r+=hc),n.filter(e=>!yc(e)).reduce((e,t)=>e+(pc.test(t)?mc:t===``?gc:_c),r)}function xc(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 Sc(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?wc(u,l,s.matcher,s.compiledParams):Cc(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=Cc({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:Fc([a,d.pathname]),pathnameBase:Lc(Fc([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=Fc([a,d.pathnameBase]))}return o}function Cc(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Tc(e.path,e.caseSensitive,e.end);return wc(e,t,n,r)}function wc(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 Tc(e,t=!1,n=!0){$s(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 Ec(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return $s(!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 Dc(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 Oc(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?ic(e):e,a;return n?(n=Pc(n),a=n.startsWith(`/`)?kc(n.substring(1),`/`):kc(n,t)):a=t,{pathname:a,search:Rc(r),hash:zc(i)}}function kc(e,t){let n=Ic(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Ac(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 jc(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Mc(e){let t=jc(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function Nc(e,t,n,r=!1){let i;typeof e==`string`?i=ic(e):(i={...e},Qs(!i.pathname||!i.pathname.includes(`?`),Ac(`?`,`pathname`,`search`,i)),Qs(!i.pathname||!i.pathname.includes(`#`),Ac(`#`,`pathname`,`hash`,i)),Qs(!i.search||!i.search.includes(`#`),Ac(`#`,`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=Oc(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Pc=e=>e.replace(/[\\/]{2,}/g,`/`),Fc=e=>Pc(e.join(`/`)),Ic=e=>e.replace(/\/+$/,``),Lc=e=>Ic(e).replace(/^\/*/,`/`),Rc=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,zc=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,Bc=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 Vc(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Hc(e){return Fc(e.map(e=>e.route.path).filter(Boolean))||`/`}var Uc=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Wc(e,t){let n=e;if(typeof n!=`string`||!Gs.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(Uc)try{let e=new URL(window.location.href),r=Ks.test(n)?new URL(qs(n,e.protocol)):new URL(n),a=Dc(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{$s(!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 Gc=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Gc);var Kc=[`GET`,...Gc];new Set(Kc);var qc=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Jc(e){try{return qc.includes(new URL(e).protocol)}catch{return!1}}var Yc=Q.createContext(null);Yc.displayName=`DataRouter`;var Xc=Q.createContext(null);Xc.displayName=`DataRouterState`;var Zc=Q.createContext(!1);function Qc(){return Q.useContext(Zc)}var $c=Q.createContext({isTransitioning:!1});$c.displayName=`ViewTransition`;var el=Q.createContext(new Map);el.displayName=`Fetchers`;var tl=Q.createContext(null);tl.displayName=`Await`;var nl=Q.createContext(null);nl.displayName=`Navigation`;var rl=Q.createContext(null);rl.displayName=`Location`;var il=Q.createContext({outlet:null,matches:[],isDataRoute:!1});il.displayName=`Route`;var al=Q.createContext(null);al.displayName=`RouteError`;var ol=`REACT_ROUTER_ERROR`,sl=`REDIRECT`,cl=`ROUTE_ERROR_RESPONSE`;function ll(e){if(e.startsWith(`${ol}:${sl}:{`))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 ul(e){if(e.startsWith(`${ol}:${cl}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new Bc(t.status,t.statusText,t.data)}catch{}}function dl(e,{relative:t}={}){Qs(fl(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=Q.useContext(nl),{hash:i,pathname:a,search:o}=xl(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:Fc([n,a])),r.createHref({pathname:s,search:o,hash:i})}function fl(){return Q.useContext(rl)!=null}function pl(){return Qs(fl(),`useLocation() may be used only in the context of a <Router> component.`),Q.useContext(rl).location}var ml=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function hl(e){Q.useContext(nl).static||Q.useLayoutEffect(e)}function gl(){let{isDataRoute:e}=Q.useContext(il);return e?Rl():_l()}function _l(){Qs(fl(),`useNavigate() may be used only in the context of a <Router> component.`);let e=Q.useContext(Yc),{basename:t,navigator:n}=Q.useContext(nl),{matches:r}=Q.useContext(il),{pathname:i}=pl(),a=JSON.stringify(Mc(r)),o=Q.useRef(!1);return hl(()=>{o.current=!0}),Q.useCallback((r,s={})=>{if($s(o.current,ml),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=Nc(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:Fc([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var vl=Q.createContext(null);function yl(e){let t=Q.useContext(il).outlet;return Q.useMemo(()=>t&&Q.createElement(vl.Provider,{value:e},t),[t,e])}function bl(){let{matches:e}=Q.useContext(il);return e[e.length-1]?.params??{}}function xl(e,{relative:t}={}){let{matches:n}=Q.useContext(il),{pathname:r}=pl(),i=JSON.stringify(Mc(n));return Q.useMemo(()=>Nc(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Sl(e,t){return Cl(e,t)}function Cl(e,t,n){Qs(fl(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=Q.useContext(nl),{matches:i}=Q.useContext(il),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||``;Bl(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=pl(),d;if(t){let e=typeof t==`string`?ic(t):t;Qs(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})):sc(e,{pathname:p});$s(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),$s(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=Al(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Fc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:Fc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?Q.createElement(rl.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function wl(){let e=Ll(),t=Vc(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=Q.createElement(Q.Fragment,null,Q.createElement(`p`,null,`💿 Hey developer 👋`),Q.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,Q.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,Q.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),Q.createElement(Q.Fragment,null,Q.createElement(`h2`,null,`Unexpected Application Error!`),Q.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?Q.createElement(`pre`,{style:i},n):null,o)}var Tl=Q.createElement(wl,null),El=class extends Q.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=ul(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:Q.createElement(il.Provider,{value:this.props.routeContext},Q.createElement(al.Provider,{value:e,children:this.props.component}));return this.context?Q.createElement(Ol,{error:e},t):t}};El.contextType=Zc;var Dl=new WeakMap;function Ol({children:e,error:t}){let{basename:n}=Q.useContext(nl);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=ll(t.digest);if(e){let r=Dl.get(t);if(r)throw r;let i=Wc(e.location,n),a=i.absoluteURL||i.to;if(Jc(a))throw Error(`Invalid redirect location`);if(Uc&&!Dl.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 Dl.set(t,n),n}}return Q.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function kl({routeContext:e,match:t,children:n}){let r=Q.useContext(Yc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),Q.createElement(il.Provider,{value:e},n)}function Al(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);Qs(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:Hc(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||Tl,o&&(s<0&&c===0?(Bl(`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?Q.createElement(n.route.Component,null):n.route.element?n.route.element:e,Q.createElement(kl,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?Q.createElement(El,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function jl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Ml(e){let t=Q.useContext(Yc);return Qs(t,jl(e)),t}function Nl(e){let t=Q.useContext(Xc);return Qs(t,jl(e)),t}function Pl(e){let t=Q.useContext(il);return Qs(t,jl(e)),t}function Fl(e){let t=Pl(e),n=t.matches[t.matches.length-1];return Qs(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Il(){return Fl(`useRouteId`)}function Ll(){let e=Q.useContext(al),t=Nl(`useRouteError`),n=Fl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Rl(){let{router:e}=Ml(`useNavigate`),t=Fl(`useNavigate`),n=Q.useRef(!1);return hl(()=>{n.current=!0}),Q.useCallback(async(r,i={})=>{$s(n.current,ml),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var zl={};function Bl(e,t,n){!t&&!zl[e]&&(zl[e]=!0,$s(!1,n))}Q.memo(Vl);function Vl({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Cl(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Hl({to:e,replace:t,state:n,relative:r}){Qs(fl(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=Q.useContext(nl);$s(!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}=Q.useContext(il),{pathname:o}=pl(),s=gl(),c=Nc(e,Mc(a),o,r===`path`),l=JSON.stringify(c);return Q.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function Ul(e){return yl(e.context)}function Wl(e){Qs(!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 Gl({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Qs(!fl(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=Q.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=ic(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=Q.useMemo(()=>{let e=Dc(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 $s(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:Q.createElement(nl.Provider,{value:c},Q.createElement(rl.Provider,{children:t,value:h}))}function Kl({children:e,location:t}){return Sl(ql(e),t)}Q.Component;function ql(e,t=[]){let n=[];return Q.Children.forEach(e,(e,r)=>{if(!Q.isValidElement(e))return;let i=[...t,r];if(e.type===Q.Fragment){n.push.apply(n,ql(e.props.children,i));return}Qs(e.type===Wl,`[${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>`),Qs(!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=ql(e.props.children,i)),n.push(a)}),n}var Jl=`get`,Yl=`application/x-www-form-urlencoded`;function Xl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Zl(e){return Xl(e)&&e.tagName.toLowerCase()===`button`}function Ql(e){return Xl(e)&&e.tagName.toLowerCase()===`form`}function $l(e){return Xl(e)&&e.tagName.toLowerCase()===`input`}function eu(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function tu(e,t){return e.button===0&&(!t||t===`_self`)&&!eu(e)}function nu(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 ru(e,t){let n=nu(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var iu=null;function au(){if(iu===null)try{new FormData(document.createElement(`form`),0),iu=!1}catch{iu=!0}return iu}var ou=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function su(e){return e!=null&&!ou.has(e)?($s(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Yl}"`),null):e}function cu(e,t){let n,r,i,a,o;if(Ql(e)){let o=e.getAttribute(`action`);r=o?Dc(o,t):null,n=e.getAttribute(`method`)||Jl,i=su(e.getAttribute(`enctype`))||Yl,a=new FormData(e)}else if(Zl(e)||$l(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?Dc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Jl,i=su(e.getAttribute(`formenctype`))||su(o.getAttribute(`enctype`))||Yl,a=new FormData(o,e),!au()){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(Xl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Jl,r=null,i=Yl,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 lu(e,t){if(e===!1||e==null)throw Error(t)}function uu(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&&Dc(i.pathname,t)===`/`?`${Ic(t)}/_root.${r}`:`${Ic(i.pathname)}.${r}`,i}async function du(e,t){if(e.id in t)return t[e.id];try{let n=await g(()=>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 fu(e){return e!=null&&typeof e.page==`string`}function pu(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 mu(e,t,n){return yu((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await du(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(pu).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function hu(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 gu(e,t,{includeHydrateFallback:n}={}){return _u(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 _u(e){return[...new Set(e)]}function vu(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function yu(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!fu(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(vu(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function bu(){let e=Q.useContext(Yc);return lu(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function xu(){let e=Q.useContext(Xc);return lu(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Su=Q.createContext(void 0);Su.displayName=`FrameworkContext`;function Cu(){let e=Q.useContext(Su);return lu(e,`You must render this element inside a <HydratedRouter> element`),e}function wu(e,t){let n=Q.useContext(Su),[r,i]=Q.useState(!1),[a,o]=Q.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=Q.useRef(null);Q.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]),Q.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:Tu(s,p),onBlur:Tu(c,m),onMouseEnter:Tu(l,p),onMouseLeave:Tu(u,m),onTouchStart:Tu(d,p)}]:[a,f,{}]:[!1,f,{}]}function Tu(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Eu({page:e,...t}){let n=Qc(),{nonce:r}=Cu(),{router:i}=bu(),a=Q.useMemo(()=>sc(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?Q.createElement(Ou,{page:e,matches:a,...t}):Q.createElement(ku,{page:e,matches:a,...t})):null}function Du(e){let{manifest:t,routeModules:n}=Cu(),[r,i]=Q.useState([]);return Q.useEffect(()=>{let r=!1;return mu(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Ou({page:e,matches:t,...n}){let r=pl(),{future:i}=Cu(),{basename:a}=bu(),o=Q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=uu(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 Q.createElement(Q.Fragment,null,o.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function ku({page:e,matches:t,...n}){let r=pl(),{future:i,manifest:a,routeModules:o}=Cu(),{basename:s}=bu(),{loaderData:c,matches:l}=xu(),u=Q.useMemo(()=>hu(e,t,l,a,r,`data`),[e,t,l,a,r]),d=Q.useMemo(()=>hu(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=Q.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=uu(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=Q.useMemo(()=>gu(d,a),[d,a]),m=Du(d);return Q.createElement(Q.Fragment,null,f.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>Q.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>Q.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Au(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}Q.Component;var ju=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{ju&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Mu({basename:e,children:t,useTransitions:n,window:r}){let i=Q.useRef();i.current??=Zs({window:r,v5Compat:!0});let a=i.current,[o,s]=Q.useState({action:a.action,location:a.location}),c=Q.useCallback(e=>{n===!1?s(e):Q.startTransition(()=>s(e))},[n]);return Q.useLayoutEffect(()=>a.listen(c),[a,c]),Q.createElement(Gl,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var Nu=Q.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:_}=Q.useContext(nl),v=typeof l==`string`&&Gs.test(l),y=Wc(l,h);l=y.to;let b=dl(l,{relative:r}),x=pl(),S=null;if(o){let e=Nc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:Fc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=wu(n,p),E=Ru(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=Q.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:Au(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?Q.createElement(Q.Fragment,null,k,Q.createElement(Eu,{page:b})):k});Nu.displayName=`Link`;var Pu=Q.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=xl(a,{relative:c.relative}),d=pl(),f=Q.useContext(Xc),{navigator:p,basename:m}=Q.useContext(nl),h=f!=null&&Wu(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=Dc(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 Q.createElement(Nu,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Pu.displayName=`NavLink`;var Fu=Q.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Jl,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=Q.useContext(nl),g=Hu(),_=Uu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Gs.test(s);return Q.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?Q.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});Fu.displayName=`Form`;function Iu(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Lu(e){let t=Q.useContext(Yc);return Qs(t,Iu(e)),t}function Ru(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=gl(),d=pl(),f=xl(e,{relative:o});return Q.useCallback(p=>{if(tu(p,t)){p.preventDefault();let t=n===void 0?rc(d)===rc(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?Q.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function zu(e){$s(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=Q.useRef(nu(e)),n=Q.useRef(!1),r=pl(),i=Q.useMemo(()=>ru(r.search,n.current?null:t.current),[r.search]),a=gl();return[i,Q.useCallback((e,t)=>{let r=nu(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Bu=0,Vu=()=>`__${String(++Bu)}__`;function Hu(){let{router:e}=Lu(`useSubmit`),{basename:t}=Q.useContext(nl),n=Il(),r=e.fetch,i=e.navigate;return Q.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=cu(e,t);if(a.navigate===!1){let e=a.fetcherKey||Vu();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 Uu(e,{relative:t}={}){let{basename:n}=Q.useContext(nl),r=Q.useContext(il);Qs(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...xl(e||`.`,{relative:t})},o=pl();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:Fc([n,a.pathname])),rc(a)}function Wu(e,{relative:t}={}){let n=Q.useContext($c);Qs(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Lu(`useViewTransitionState`),i=xl(e,{relative:t});if(!n.isTransitioning)return!1;let a=Dc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Dc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Cc(i.pathname,o)!=null||Cc(i.pathname,a)!=null}var $=s(),Gu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(ht,{ref:n,className:J(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Gu.displayName=ht.displayName;var Ku=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Ku.displayName=`Card`;var qu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex flex-col space-y-1.5 p-6`,e),...t}));qu.displayName=`CardHeader`;var Ju=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`h3`,{ref:n,className:J(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Ju.displayName=`CardTitle`;var Yu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`p`,{ref:n,className:J(`text-sm text-muted-foreground`,e),...t}));Yu.displayName=`CardDescription`;var Xu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`p-6 pt-0`,e),...t}));Xu.displayName=`CardContent`;var Zu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex items-center p-6 pt-0`,e),...t}));Zu.displayName=`CardFooter`;var Qu=`2.26.2`,$u=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function ed(e){(0,Q.useEffect)(()=>{if(window.particlesJS!==void 0)$u(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`),$u(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var td=`session.open`,nd=`session.set`,rd=`session.ids`,id=`session.materialize`,ad=`session.close`,od=`session.delta`;function sd(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await X.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 cd=`https://github.com/canvas-ui/canvas-server`,ld=null;function ud(){return ld||=X.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||cd,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),ld=null,{sourceUrl:cd,version:null,commit:null,license:null})),ld}function dd(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;return ud().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function fd({className:e=``}){let t=dd();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function pd({children:e}){ed(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=sd();return(0,$.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,$.jsxs)(Ku,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,$.jsxs)(Nu,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,$.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,$.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,$.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Qu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,$.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,$.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,$.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,$.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,$.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,$.jsx)(`span`,{children:`View on GitHub`})]}),(0,$.jsx)(fd,{className:`mt-4 text-center`})]})]})})]})})}function md(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var hd=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=Rr,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||md();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=zr(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 gd(e,t,n=`auto`){try{let r=await X.post(xr.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)+`...`),X.setAuthToken(i.token),hd.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)+`...`),X.setAuthToken(i.payload.token),hd.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),X.clearAuthToken(),e}}async function _d(e,t,n){try{return await X.post(xr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function vd(e){return e instanceof Error&&/^Network error/i.test(e.message)}function yd(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return yr(e).exp*1e3>Date.now()}catch{return!1}}function bd(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=yr(e);return t.exp*1e3<Date.now()?(X.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),X.clearAuthToken(),null}}async function xd(){try{if(!X.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await X.get(xr.me);return console.log(`Current user response:`,e),e&&e?(hd.isConnected()||hd.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),vd(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),X.clearAuthToken(),hd.disconnect(),null):null}}function Sd(){return X.isAuthenticated()}function Cd(){let e=new URL(`${Lr}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function wd(e){let t=await X.post(`${Lr}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);X.setAuthToken(t.token),hd.connect(t.token)}async function Td(){try{let e=await X.get(xr.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 Ed(e){try{await X.post(xr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var Dd=e=>e?.strategies?.local?.enabled!==!1,Od=e=>e?.allowUserRegistrations!==!1;function kd(){let e=gl(),[t,n]=Q.useState(!1),[r,i]=Q.useState(``),[a,o]=Q.useState(``),[s,c]=Q.useState(!1),[l,u]=Q.useState({}),[d,p]=Q.useState(null),[m,h]=Q.useState({email:``,password:``,strategy:`auto`});Q.useEffect(()=>{Sd()&&e(`/workspaces`),fetch(`${Lr}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),Td().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let g=()=>{let e={};return m.email?/\S+@\S+\.\S+/.test(m.email)||(e.email=`Email is invalid`):e.email=`Email is required`,m.password||(e.password=`Password is required`),u(e),Object.keys(e).length===0},_=e=>{let{name:t,value:n}=e.target;h(e=>({...e,[t]:n}))};async function v(t){if(t.preventDefault(),g()){c(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await gd(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),u({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}u({password:t})}finally{c(!1)}}}return t?(0,$.jsx)(pd,{children:(0,$.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(X.setAuthToken(r.trim()),!await xd())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){X.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,$.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,$.jsx)(Gu,{htmlFor:`local-token`,children:`Local access token`}),(0,$.jsx)(Y,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(Z,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,$.jsx)(pd,{children:(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,$.jsx)(`form`,{onSubmit:v,children:(0,$.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Gu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,$.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:m.strategy,onChange:_,disabled:s,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,$.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,$.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,$.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Gu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),l.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Gu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,$.jsxs)(Z,{type:`button`,variant:`outline`,disabled:s,onClick:()=>Cd(),children:[(0,$.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),Dd(d)&&Od(d)&&(0,$.jsx)(Z,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function Ad(){let e=gl(),{showToast:t}=Vr(),[n,r]=Q.useState(!1),[i,a]=Q.useState({}),[o,s]=Q.useState({name:``,email:``,password:``}),[c,l]=Q.useState(!1),[u,d]=Q.useState(!1),[f,p]=Q.useState(null);Q.useEffect(()=>{(async()=>{let t=await Td(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=Q.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,$.jsxs)(pd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,$.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,$.jsx)(Z,{asChild:!0,className:`w-full`,children:(0,$.jsx)(Nu,{to:`/login`,children:`Go to Login`})})})]}):(0,$.jsxs)(pd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,$.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await _d(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Gu,{htmlFor:`name`,children:`Username`}),(0,$.jsx)(Y,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Gu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Gu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,$.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,$.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,$.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,$.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,$.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,$.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,$.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,$.jsx)(Z,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,$.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,$.jsx)(Nu,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,$.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,$.jsx)(Nu,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,$.jsx)(Nu,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function jd(){let e=gl(),[t]=zu(),[n,r]=Q.useState(t.get(`error`)),i=Q.useRef(!1);return Q.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,wd(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,$.jsx)(pd,{children:(0,$.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Md({className:e=`h-5 w-5`,...t}){return(0,$.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,$.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,$.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 Nd({children:e}){let[t,n]=(0,Q.useState)(`loading`);return(0,Q.useEffect)(()=>{(async()=>{try{if(!Sd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await xd();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),vd(e)){n(yd()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),X.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,$.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,$.jsx)(Md,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,$.jsx)(Hl,{to:`/login`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}function Pd({children:e}){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{(async()=>{try{await X.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),X.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,$.jsx)(Hl,{to:`/workspaces`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}var Fd=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})}))})),Id=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)}})),Ld=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=oe,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=z,e.setTopLeft=te,e.setTransform=ee,e.sortLayoutItems=ne,e.sortLayoutItemsByColRow=re,e.sortLayoutItemsByRowCol=B,e.synchronizeLayoutWithChildren=ie,e.validateLayout=ae,e.withLayoutItem=p;var t=Fd(),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=Id();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=ne(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=ne(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)}},L=(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)}},R={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 L(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},s:L,sw:function(){return L(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 z(e,t,n,r){let i=R[e];return i?i(t,a(a({},t),n),r):n}function ee(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 te(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 ne(e,t){return t===`horizontal`?re(e):t===`vertical`?B(e):e}function B(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 re(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 ie(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 ae(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function oe(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Rd=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)}})),zd=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),Bd=i(((e,t)=>{var n=zd();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}})),Vd=i(((e,t)=>{t.exports=Bd()()})),Hd=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},u=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{DraggableCore:()=>K,default:()=>q}),t.exports=f(p);var m=u(d()),g=u(Vd()),_=u(h()),v=vr();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 L(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function R(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 z(e,t){let n=te(e,t,`px`);return{[E(`transform`,O)]:n}}function ee(e,t){return te(e,t,``)}function te({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 ne(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function B(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function re(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ie(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??re();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=pl(),d;if(t){let e=typeof t==`string`?ic(t):t;Qs(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})):sc(e,{pathname:p});$s(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),$s(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=Al(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Fc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:Fc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?Q.createElement(rl.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function wl(){let e=Ll(),t=Vc(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=Q.createElement(Q.Fragment,null,Q.createElement(`p`,null,`💿 Hey developer 👋`),Q.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,Q.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,Q.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),Q.createElement(Q.Fragment,null,Q.createElement(`h2`,null,`Unexpected Application Error!`),Q.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?Q.createElement(`pre`,{style:i},n):null,o)}var Tl=Q.createElement(wl,null),El=class extends Q.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=ul(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:Q.createElement(il.Provider,{value:this.props.routeContext},Q.createElement(al.Provider,{value:e,children:this.props.component}));return this.context?Q.createElement(Ol,{error:e},t):t}};El.contextType=Zc;var Dl=new WeakMap;function Ol({children:e,error:t}){let{basename:n}=Q.useContext(nl);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=ll(t.digest);if(e){let r=Dl.get(t);if(r)throw r;let i=Wc(e.location,n),a=i.absoluteURL||i.to;if(Jc(a))throw Error(`Invalid redirect location`);if(Uc&&!Dl.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 Dl.set(t,n),n}}return Q.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function kl({routeContext:e,match:t,children:n}){let r=Q.useContext(Yc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),Q.createElement(il.Provider,{value:e},n)}function Al(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);Qs(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:Hc(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||Tl,o&&(s<0&&c===0?(Bl(`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?Q.createElement(n.route.Component,null):n.route.element?n.route.element:e,Q.createElement(kl,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?Q.createElement(El,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function jl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Ml(e){let t=Q.useContext(Yc);return Qs(t,jl(e)),t}function Nl(e){let t=Q.useContext(Xc);return Qs(t,jl(e)),t}function Pl(e){let t=Q.useContext(il);return Qs(t,jl(e)),t}function Fl(e){let t=Pl(e),n=t.matches[t.matches.length-1];return Qs(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Il(){return Fl(`useRouteId`)}function Ll(){let e=Q.useContext(al),t=Nl(`useRouteError`),n=Fl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Rl(){let{router:e}=Ml(`useNavigate`),t=Fl(`useNavigate`),n=Q.useRef(!1);return hl(()=>{n.current=!0}),Q.useCallback(async(r,i={})=>{$s(n.current,ml),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var zl={};function Bl(e,t,n){!t&&!zl[e]&&(zl[e]=!0,$s(!1,n))}Q.memo(Vl);function Vl({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Cl(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Hl({to:e,replace:t,state:n,relative:r}){Qs(fl(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=Q.useContext(nl);$s(!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}=Q.useContext(il),{pathname:o}=pl(),s=gl(),c=Nc(e,Mc(a),o,r===`path`),l=JSON.stringify(c);return Q.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function Ul(e){return yl(e.context)}function Wl(e){Qs(!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 Gl({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Qs(!fl(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=Q.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=ic(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=Q.useMemo(()=>{let e=Dc(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 $s(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:Q.createElement(nl.Provider,{value:c},Q.createElement(rl.Provider,{children:t,value:h}))}function Kl({children:e,location:t}){return Sl(ql(e),t)}Q.Component;function ql(e,t=[]){let n=[];return Q.Children.forEach(e,(e,r)=>{if(!Q.isValidElement(e))return;let i=[...t,r];if(e.type===Q.Fragment){n.push.apply(n,ql(e.props.children,i));return}Qs(e.type===Wl,`[${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>`),Qs(!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=ql(e.props.children,i)),n.push(a)}),n}var Jl=`get`,Yl=`application/x-www-form-urlencoded`;function Xl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Zl(e){return Xl(e)&&e.tagName.toLowerCase()===`button`}function Ql(e){return Xl(e)&&e.tagName.toLowerCase()===`form`}function $l(e){return Xl(e)&&e.tagName.toLowerCase()===`input`}function eu(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function tu(e,t){return e.button===0&&(!t||t===`_self`)&&!eu(e)}function nu(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 ru(e,t){let n=nu(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var iu=null;function au(){if(iu===null)try{new FormData(document.createElement(`form`),0),iu=!1}catch{iu=!0}return iu}var ou=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function su(e){return e!=null&&!ou.has(e)?($s(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Yl}"`),null):e}function cu(e,t){let n,r,i,a,o;if(Ql(e)){let o=e.getAttribute(`action`);r=o?Dc(o,t):null,n=e.getAttribute(`method`)||Jl,i=su(e.getAttribute(`enctype`))||Yl,a=new FormData(e)}else if(Zl(e)||$l(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?Dc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Jl,i=su(e.getAttribute(`formenctype`))||su(o.getAttribute(`enctype`))||Yl,a=new FormData(o,e),!au()){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(Xl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Jl,r=null,i=Yl,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 lu(e,t){if(e===!1||e==null)throw Error(t)}function uu(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&&Dc(i.pathname,t)===`/`?`${Ic(t)}/_root.${r}`:`${Ic(i.pathname)}.${r}`,i}async function du(e,t){if(e.id in t)return t[e.id];try{let n=await g(()=>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 fu(e){return e!=null&&typeof e.page==`string`}function pu(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 mu(e,t,n){return yu((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await du(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(pu).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function hu(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 gu(e,t,{includeHydrateFallback:n}={}){return _u(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 _u(e){return[...new Set(e)]}function vu(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function yu(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!fu(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(vu(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function bu(){let e=Q.useContext(Yc);return lu(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function xu(){let e=Q.useContext(Xc);return lu(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Su=Q.createContext(void 0);Su.displayName=`FrameworkContext`;function Cu(){let e=Q.useContext(Su);return lu(e,`You must render this element inside a <HydratedRouter> element`),e}function wu(e,t){let n=Q.useContext(Su),[r,i]=Q.useState(!1),[a,o]=Q.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=Q.useRef(null);Q.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]),Q.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:Tu(s,p),onBlur:Tu(c,m),onMouseEnter:Tu(l,p),onMouseLeave:Tu(u,m),onTouchStart:Tu(d,p)}]:[a,f,{}]:[!1,f,{}]}function Tu(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Eu({page:e,...t}){let n=Qc(),{nonce:r}=Cu(),{router:i}=bu(),a=Q.useMemo(()=>sc(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?Q.createElement(Ou,{page:e,matches:a,...t}):Q.createElement(ku,{page:e,matches:a,...t})):null}function Du(e){let{manifest:t,routeModules:n}=Cu(),[r,i]=Q.useState([]);return Q.useEffect(()=>{let r=!1;return mu(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Ou({page:e,matches:t,...n}){let r=pl(),{future:i}=Cu(),{basename:a}=bu(),o=Q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=uu(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 Q.createElement(Q.Fragment,null,o.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function ku({page:e,matches:t,...n}){let r=pl(),{future:i,manifest:a,routeModules:o}=Cu(),{basename:s}=bu(),{loaderData:c,matches:l}=xu(),u=Q.useMemo(()=>hu(e,t,l,a,r,`data`),[e,t,l,a,r]),d=Q.useMemo(()=>hu(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=Q.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=uu(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=Q.useMemo(()=>gu(d,a),[d,a]),m=Du(d);return Q.createElement(Q.Fragment,null,f.map(e=>Q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>Q.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>Q.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Au(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}Q.Component;var ju=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{ju&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Mu({basename:e,children:t,useTransitions:n,window:r}){let i=Q.useRef();i.current??=Zs({window:r,v5Compat:!0});let a=i.current,[o,s]=Q.useState({action:a.action,location:a.location}),c=Q.useCallback(e=>{n===!1?s(e):Q.startTransition(()=>s(e))},[n]);return Q.useLayoutEffect(()=>a.listen(c),[a,c]),Q.createElement(Gl,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var Nu=Q.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:_}=Q.useContext(nl),v=typeof l==`string`&&Gs.test(l),y=Wc(l,h);l=y.to;let b=dl(l,{relative:r}),x=pl(),S=null;if(o){let e=Nc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:Fc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=wu(n,p),E=Ru(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=Q.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:Au(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?Q.createElement(Q.Fragment,null,k,Q.createElement(Eu,{page:b})):k});Nu.displayName=`Link`;var Pu=Q.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=xl(a,{relative:c.relative}),d=pl(),f=Q.useContext(Xc),{navigator:p,basename:m}=Q.useContext(nl),h=f!=null&&Wu(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=Dc(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 Q.createElement(Nu,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Pu.displayName=`NavLink`;var Fu=Q.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Jl,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=Q.useContext(nl),g=Hu(),_=Uu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Gs.test(s);return Q.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?Q.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});Fu.displayName=`Form`;function Iu(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Lu(e){let t=Q.useContext(Yc);return Qs(t,Iu(e)),t}function Ru(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=gl(),d=pl(),f=xl(e,{relative:o});return Q.useCallback(p=>{if(tu(p,t)){p.preventDefault();let t=n===void 0?rc(d)===rc(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?Q.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function zu(e){$s(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=Q.useRef(nu(e)),n=Q.useRef(!1),r=pl(),i=Q.useMemo(()=>ru(r.search,n.current?null:t.current),[r.search]),a=gl();return[i,Q.useCallback((e,t)=>{let r=nu(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Bu=0,Vu=()=>`__${String(++Bu)}__`;function Hu(){let{router:e}=Lu(`useSubmit`),{basename:t}=Q.useContext(nl),n=Il(),r=e.fetch,i=e.navigate;return Q.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=cu(e,t);if(a.navigate===!1){let e=a.fetcherKey||Vu();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 Uu(e,{relative:t}={}){let{basename:n}=Q.useContext(nl),r=Q.useContext(il);Qs(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...xl(e||`.`,{relative:t})},o=pl();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:Fc([n,a.pathname])),rc(a)}function Wu(e,{relative:t}={}){let n=Q.useContext($c);Qs(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Lu(`useViewTransitionState`),i=xl(e,{relative:t});if(!n.isTransitioning)return!1;let a=Dc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Dc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Cc(i.pathname,o)!=null||Cc(i.pathname,a)!=null}var $=s(),Gu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(ht,{ref:n,className:J(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Gu.displayName=ht.displayName;var Ku=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`rounded-(--card-radius) border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Ku.displayName=`Card`;var qu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex flex-col space-y-1.5 p-6`,e),...t}));qu.displayName=`CardHeader`;var Ju=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`h3`,{ref:n,className:J(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Ju.displayName=`CardTitle`;var Yu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`p`,{ref:n,className:J(`text-sm text-muted-foreground`,e),...t}));Yu.displayName=`CardDescription`;var Xu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`p-6 pt-0`,e),...t}));Xu.displayName=`CardContent`;var Zu=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(`div`,{ref:n,className:J(`flex items-center p-6 pt-0`,e),...t}));Zu.displayName=`CardFooter`;var Qu=`2.26.4`,$u=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function ed(e){(0,Q.useEffect)(()=>{if(window.particlesJS!==void 0)$u(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`),$u(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var td=`session.open`,nd=`session.set`,rd=`session.ids`,id=`session.materialize`,ad=`session.close`,od=`session.delta`;function sd(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await X.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 cd=`https://github.com/canvas-ui/canvas-server`,ld=null;function ud(){return ld||=X.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||cd,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),ld=null,{sourceUrl:cd,version:null,commit:null,license:null})),ld}function dd(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!0;return ud().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function fd({className:e=``}){let t=dd();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,$.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function pd({children:e}){ed(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=sd();return(0,$.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,$.jsxs)(Ku,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,$.jsxs)(Nu,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,$.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,$.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,$.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Qu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,$.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,$.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,$.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,$.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,$.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,$.jsx)(`span`,{children:`View on GitHub`})]}),(0,$.jsx)(fd,{className:`mt-4 text-center`})]})]})})]})})}function md(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var hd=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=Rr,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||md();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=zr(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 gd(e,t,n=`auto`){try{let r=await X.post(xr.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)+`...`),X.setAuthToken(i.token),hd.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)+`...`),X.setAuthToken(i.payload.token),hd.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),X.clearAuthToken(),e}}async function _d(e,t,n){try{return await X.post(xr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function vd(e){return e instanceof Error&&/^Network error/i.test(e.message)}function yd(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return yr(e).exp*1e3>Date.now()}catch{return!1}}function bd(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=yr(e);return t.exp*1e3<Date.now()?(X.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),X.clearAuthToken(),null}}async function xd(){try{if(!X.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await X.get(xr.me);return console.log(`Current user response:`,e),e&&e?(hd.isConnected()||hd.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),vd(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),X.clearAuthToken(),hd.disconnect(),null):null}}function Sd(){return X.isAuthenticated()}function Cd(){let e=new URL(`${Lr}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function wd(e){let t=await X.post(`${Lr}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);X.setAuthToken(t.token),hd.connect(t.token)}async function Td(){try{let e=await X.get(xr.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 Ed(e){try{await X.post(xr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var Dd=e=>e?.strategies?.local?.enabled!==!1,Od=e=>e?.allowUserRegistrations!==!1;function kd(){let e=gl(),[t,n]=Q.useState(!1),[r,i]=Q.useState(``),[a,o]=Q.useState(``),[s,c]=Q.useState(!1),[l,u]=Q.useState({}),[d,p]=Q.useState(null),[m,h]=Q.useState({email:``,password:``,strategy:`auto`});Q.useEffect(()=>{Sd()&&e(`/workspaces`),fetch(`${Lr}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),Td().then(e=>{p(e)}).catch(e=>{console.error(`Failed to load auth config:`,e)})},[e]);let g=()=>{let e={};return m.email?/\S+@\S+\.\S+/.test(m.email)||(e.email=`Email is invalid`):e.email=`Email is required`,m.password||(e.password=`Password is required`),u(e),Object.keys(e).length===0},_=e=>{let{name:t,value:n}=e.target;h(e=>({...e,[t]:n}))};async function v(t){if(t.preventDefault(),g()){c(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await gd(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),u({}),e(`/home`)}catch(e){console.error(`Login error:`,e);let t=`Login failed`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;n.message?t=n.message:n.error?t=n.error:n.payload?.message&&(t=n.payload.message)}u({password:t})}finally{c(!1)}}}return t?(0,$.jsx)(pd,{children:(0,$.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),c(!0),o(``);try{if(X.setAuthToken(r.trim()),!await xd())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){X.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{c(!1)}},children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,$.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,$.jsx)(Gu,{htmlFor:`local-token`,children:`Local access token`}),(0,$.jsx)(Y,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(Z,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,$.jsx)(pd,{children:(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,$.jsx)(`form`,{onSubmit:v,children:(0,$.jsxs)(`div`,{className:`grid gap-4`,children:[d?.strategies?.imap?.enabled&&d.strategies.imap.domains.length>0&&(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Gu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,$.jsxs)(`select`,{id:`strategy`,name:`strategy`,value:m.strategy,onChange:_,disabled:s,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`,children:[(0,$.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,$.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,$.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Gu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),l.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.email})]}),(0,$.jsxs)(`div`,{className:`grid gap-2`,children:[(0,$.jsx)(Gu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),l.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:l.password})]}),(0,$.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),d?.strategies?.google?.enabled&&(0,$.jsxs)(Z,{type:`button`,variant:`outline`,disabled:s,onClick:()=>Cd(),children:[(0,$.jsx)(f,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),Dd(d)&&Od(d)&&(0,$.jsx)(Z,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function Ad(){let e=gl(),{showToast:t}=Vr(),[n,r]=Q.useState(!1),[i,a]=Q.useState({}),[o,s]=Q.useState({name:``,email:``,password:``}),[c,l]=Q.useState(!1),[u,d]=Q.useState(!1),[f,p]=Q.useState(null);Q.useEffect(()=>{(async()=>{let t=await Td(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=Q.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,$.jsxs)(pd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,$.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,$.jsx)(Z,{asChild:!0,className:`w-full`,children:(0,$.jsx)(Nu,{to:`/login`,children:`Go to Login`})})})]}):(0,$.jsxs)(pd,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,$.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await _d(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Gu,{htmlFor:`name`,children:`Username`}),(0,$.jsx)(Y,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Gu,{htmlFor:`email`,children:`Email`}),(0,$.jsx)(Y,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Gu,{htmlFor:`password`,children:`Password`}),(0,$.jsx)(Y,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,$.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,$.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,$.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,$.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,$.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,$.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,$.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,$.jsx)(Z,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,$.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,$.jsx)(Nu,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,$.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,$.jsx)(Nu,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,$.jsx)(Nu,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function jd(){let e=gl(),[t]=zu(),[n,r]=Q.useState(t.get(`error`)),i=Q.useRef(!1);return Q.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,wd(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,$.jsx)(pd,{children:(0,$.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function Md({className:e=`h-5 w-5`,...t}){return(0,$.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,$.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,$.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 Nd({children:e}){let[t,n]=(0,Q.useState)(`loading`);return(0,Q.useEffect)(()=>{(async()=>{try{if(!Sd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await xd();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),vd(e)){n(yd()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),X.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,$.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,$.jsx)(Md,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,$.jsx)(Hl,{to:`/login`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}function Pd({children:e}){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{(async()=>{try{await X.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),X.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,$.jsx)(Hl,{to:`/workspaces`,replace:!0}):(0,$.jsx)($.Fragment,{children:e})}var Fd=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})}))})),Id=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)}})),Ld=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.bottom=l,e.childrenEqual=h,e.cloneLayout=u,e.cloneLayoutItem=m,e.collides=_,e.compact=v,e.compactItem=x,e.compactType=oe,e.correctBounds=S,e.fastPositionEqual=g,e.fastRGLPropsEqual=void 0,e.getAllCollisions=T,e.getFirstCollision=w,e.getLayoutItem=C,e.getStatics=E,e.modifyLayout=f,e.moveElement=D,e.moveElementAwayFromCollision=O,e.noop=void 0,e.perc=k,e.resizeItemInDirection=z,e.setTopLeft=te,e.setTransform=ee,e.sortLayoutItems=ne,e.sortLayoutItemsByColRow=re,e.sortLayoutItemsByRowCol=B,e.synchronizeLayoutWithChildren=ie,e.validateLayout=ae,e.withLayoutItem=p;var t=Fd(),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=Id();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=ne(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=ne(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)}},L=(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)}},R={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 L(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},s:L,sw:function(){return L(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 z(e,t,n,r){let i=R[e];return i?i(t,a(a({},t),n),r):n}function ee(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 te(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 ne(e,t){return t===`horizontal`?re(e):t===`vertical`?B(e):e}function B(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 re(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 ie(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 ae(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Layout`,n=[`x`,`y`,`w`,`h`];if(!Array.isArray(e))throw Error(t+` must be an array!`);for(let r=0,i=e.length;r<i;r++){let i=e[r];for(let e=0;e<n.length;e++){let a=n[e],o=i[a];if(typeof o!=`number`||Number.isNaN(o))throw Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${o} (${typeof o})`)}if(i.i!==void 0&&typeof i.i!=`string`)throw Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${i.i} (${typeof i.i})`)}}function oe(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Rd=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)}})),zd=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),Bd=i(((e,t)=>{var n=zd();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}})),Vd=i(((e,t)=>{t.exports=Bd()()})),Hd=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},l=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!s.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(o=i(t,c))||o.enumerable});return e},u=(e,t,i)=>(i=e==null?{}:n(o(e)),l(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),f=e=>l(r({},`__esModule`,{value:!0}),e),p={};c(p,{DraggableCore:()=>K,default:()=>q}),t.exports=f(p);var m=u(d()),g=u(Vd()),_=u(h()),v=vr();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 L(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function R(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 z(e,t){let n=te(e,t,`px`);return{[E(`transform`,O)]:n}}function ee(e,t){return te(e,t,``)}function te({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 ne(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function B(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function re(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ie(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??re();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&&V(e.body,`react-draggable-transparent-selection`)}function ae(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{oe(e)}):oe(e)}function oe(e){if(e)try{e.body&&H(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 V(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function H(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function U(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:fe(r);let i=pe(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:L(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 se(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function W(e){return e.props.axis===`both`||e.props.axis===`x`}function ce(e){return e.props.axis===`both`||e.props.axis===`y`}function le(e,t,n){let r=typeof t==`number`?ne(e,t):null;if(typeof t==`number`&&!r)return null;let i=pe(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return R(r||e,a,n.props.scale)}function ue(e,t,n){let r=!x(e.lastX),i=pe(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 de(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 fe(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function pe(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var me=u(d()),G=u(Vd()),he=u(h()),ge=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},_e={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},ve=_e.mouse,K=class extends me.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=B(e);this.touchIdentifier=r;let i=le(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=ue(this,a,o);ge(`DraggableCore: handleDragStart: %j`,s),ge(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&ie(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,ve.move,this.handleDrag),M(n,ve.stop,this.handleDragStop))},this.handleDrag=e=>{let t=le(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]=se(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=ue(this,n,r);if(ge(`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=le(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]=se(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=ue(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&ae(a.ownerDocument),ge(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(ge(`DraggableCore: Removing handlers`),N(a.ownerDocument,ve.move,this.handleDrag),N(a.ownerDocument,ve.stop,this.handleDragStop))},this.onMouseDown=e=>(ve=_e.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(ve=_e.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(ve=_e.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(ve=_e.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,_e.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,_e.mouse.move,this.handleDrag),N(t,_e.touch.move,this.handleDrag),N(t,_e.mouse.stop,this.handleDragStop),N(t,_e.touch.stop,this.handleDragStop),N(e,_e.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&ae(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=he.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(ge(`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 me.cloneElement(me.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};K.displayName=`DraggableCore`,K.propTypes={allowAnyClick:G.default.bool,allowMobileScroll:G.default.bool,children:G.default.node.isRequired,disabled:G.default.bool,enableUserSelectHack:G.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:G.default.arrayOf(G.default.number),handle:G.default.string,cancel:G.default.string,nodeRef:G.default.object,nonce:G.default.string,onStart:G.default.func,onDrag:G.default.func,onStop:G.default.func,onMouseDown:G.default.func,scale:G.default.number,className:C,style:C,transform:C},K.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var q=class extends m.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(ge(`Draggable: onDragStart: %j`,t),this.props.onStart(e,de(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;ge(`Draggable: onDrag: %j`,t);let n=de(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]=U(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,de(this,t))===!1)return!1;ge(`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)?(ge(`Draggable: getDerivedStateFromProps %j`,{position:e,prevPropsPosition:t}),{x:e.x,y:e.y,prevPropsPosition:{...e}}):null}componentDidMount(){window.SVGElement!==void 0&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.state.dragging&&this.setState({dragging:!1})}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=_.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):null}render(){let{axis:e,bounds:t,children:n,defaultPosition:r,defaultClassName:i,defaultClassNameDragging:a,defaultClassNameDragged:o,position:s,positionOffset:c,scale:l,...u}=this.props,d={},f=null,p=!s||this.state.dragging,h=s||r,g={x:W(this)&&p?this.state.x:h.x,y:ce(this)&&p?this.state.y:h.y};this.state.isElementSVG?f=ee(g,c):d=z(g,c);let _=m.Children.only(n),y=(0,v.clsx)(_.props.className||``,i,{[a]:this.state.dragging,[o]:this.state.dragged});return m.createElement(K,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},m.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};q.displayName=`Draggable`,q.propTypes={...K.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},q.defaultProps={...K.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:K})})),Ud=i(((e,t)=>{var n=Hd(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),Wd=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)}})),Gd=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(Vd());Ud();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)}}})),Kd=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=Ud(),r=Wd(),i=Gd(),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}})),qd=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(Vd()),r=o(Kd()),i=Gd(),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})})),Jd=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=Kd().default,t.exports.ResizableBox=qd().default})),Yd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(Vd()),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&&Ld().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}})),Xd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=u(d()),n=h(),r=u(Vd()),i=Ud(),a=Jd(),o=Ld(),s=Rd(),c=Yd(),l=u(vr());function u(e){return e&&e.__esModule?e:{default:e}}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?f(Object(n),!0).forEach(function(t){m(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function m(e,t,n){return(t=g(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e){var t=_(e,`string`);return typeof t==`symbol`?t:t+``}function _(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var v=class extends t.default.Component{constructor(){super(...arguments),m(this,`state`,{resizing:null,dragging:null,className:``}),m(this,`elementRef`,t.default.createRef()),m(this,`onDragStart`,(e,t)=>{let{node:n}=t,{onDragStart:r,transformScale:i}=this.props;if(!r)return;let a={top:0,left:0},{offsetParent:o}=n;if(!o)return;let c=o.getBoundingClientRect(),l=n.getBoundingClientRect(),u=l.left/i,d=c.left/i,f=l.top/i,p=c.top/i;a.left=u-d+o.scrollLeft,a.top=f-p+o.scrollTop,this.setState({dragging:a});let{x:m,y:h}=(0,s.calcXY)(this.getPositionParams(),a.top,a.left,this.props.w,this.props.h);return r.call(this,this.props.i,m,h,{e,node:n,newPosition:a})}),m(this,`onDrag`,(e,t,r)=>{let{node:i,deltaX:a,deltaY:o}=t,{onDrag:c}=this.props;if(!c)return;if(!this.state.dragging)throw Error(`onDrag called before onDragStart.`);let l=this.state.dragging.top+o,u=this.state.dragging.left+a,{isBounded:d,i:f,w:p,h:m,containerWidth:h}=this.props,g=this.getPositionParams();if(d){let{offsetParent:e}=i;if(e){let{margin:t,rowHeight:n}=this.props,r=e.clientHeight-(0,s.calcGridItemWHPx)(m,n,t[1]);l=(0,s.clamp)(l,0,r);let i=(0,s.calcGridColWidth)(g),a=h-(0,s.calcGridItemWHPx)(p,i,t[0]);u=(0,s.clamp)(u,0,a)}}let _={top:l,left:u};r?this.setState({dragging:_}):(0,n.flushSync)(()=>{this.setState({dragging:_})});let{x:v,y}=(0,s.calcXY)(g,l,u,p,m);return c.call(this,f,v,y,{e,node:i,newPosition:_})}),m(this,`onDragStop`,(e,t)=>{let{node:n}=t,{onDragStop:r}=this.props;if(!r)return;if(!this.state.dragging)throw Error(`onDragEnd called before onDragStart.`);let{w:i,h:a,i:o}=this.props,{left:c,top:l}=this.state.dragging,u={top:l,left:c};this.setState({dragging:null});let{x:d,y:f}=(0,s.calcXY)(this.getPositionParams(),l,c,i,a);return r.call(this,o,d,f,{e,node:n,newPosition:u})}),m(this,`onResizeStop`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStop`)),m(this,`onResizeStart`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStart`)),m(this,`onResize`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResize`))}shouldComponentUpdate(e,t){if(this.props.children!==e.children||this.props.droppingPosition!==e.droppingPosition)return!0;let n=(0,s.calcGridItemPosition)(this.getPositionParams(this.props),this.props.x,this.props.y,this.props.w,this.props.h,this.state),r=(0,s.calcGridItemPosition)(this.getPositionParams(e),e.x,e.y,e.w,e.h,t);return!(0,o.fastPositionEqual)(n,r)||this.props.useCSSTransforms!==e.useCSSTransforms}componentDidMount(){this.moveDroppingItem({})}componentDidUpdate(e){this.moveDroppingItem(e)}moveDroppingItem(e){let{droppingPosition:t}=this.props;if(!t)return;let n=this.elementRef.current;if(!n)return;let r=e.droppingPosition||{left:0,top:0},{dragging:i}=this.state,a=i&&t.left!==r.left||t.top!==r.top;if(!i)this.onDragStart(t.e,{node:n,deltaX:t.left,deltaY:t.top});else if(a){let e=t.left-i.left,r=t.top-i.top;this.onDrag(t.e,{node:n,deltaX:e,deltaY:r},!0)}}getPositionParams(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.props;return{cols:e.cols,containerPadding:e.containerPadding,containerWidth:e.containerWidth,margin:e.margin,maxRows:e.maxRows,rowHeight:e.rowHeight}}createStyle(e){let{usePercentages:t,containerWidth:n,useCSSTransforms:r}=this.props,i;return r?i=(0,o.setTransform)(e):(i=(0,o.setTopLeft)(e),t&&(i.left=(0,o.perc)(e.left/n),i.width=(0,o.perc)(e.width/n))),i}mixinDraggable(e,n){return t.default.createElement(i.DraggableCore,{disabled:!n,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,handle:this.props.handle,cancel:`.react-resizable-handle`+(this.props.cancel?`,`+this.props.cancel:``),scale:this.props.transformScale,nodeRef:this.elementRef},e)}curryResizeHandler(e,t){return(n,r)=>t(n,r,e)}mixinResizable(e,n,r){let{cols:i,minW:o,minH:c,maxW:l,maxH:u,transformScale:d,resizeHandles:f,resizeHandle:p}=this.props,m=this.getPositionParams(),h=(0,s.calcGridItemPosition)(m,0,0,i,0).width,g=(0,s.calcGridItemPosition)(m,0,0,o,c),_=(0,s.calcGridItemPosition)(m,0,0,l,u),v=[g.width,g.height],y=[Math.min(_.width,h),Math.min(_.height,1/0)];return t.default.createElement(a.Resizable,{draggableOpts:{disabled:!r},className:r?void 0:`react-resizable-hide`,width:n.width,height:n.height,minConstraints:v,maxConstraints:y,onResizeStop:this.curryResizeHandler(n,this.onResizeStop),onResizeStart:this.curryResizeHandler(n,this.onResizeStart),onResize:this.curryResizeHandler(n,this.onResize),transformScale:d,resizeHandles:f,handle:p},e)}onResizeHandler(e,t,r,i){let{node:a,size:c,handle:l}=t,u=this.props[i];if(!u)return;let{x:d,y:f,i:p,maxH:m,minH:h,containerWidth:g}=this.props,{minW:_,maxW:v}=this.props,y=c;a&&(y=(0,o.resizeItemInDirection)(l,r,c,g),(0,n.flushSync)(()=>{this.setState({resizing:i===`onResizeStop`?null:y})}));let{w:b,h:x}=(0,s.calcWH)(this.getPositionParams(),y.width,y.height,d,f,l);b=(0,s.clamp)(b,Math.max(_,1),v),x=(0,s.clamp)(x,h,m),u.call(this,p,b,x,{e,node:a,size:y,handle:l})}render(){let{x:e,y:n,w:r,h:i,isDraggable:a,isResizable:o,droppingPosition:c,useCSSTransforms:u}=this.props,d=(0,s.calcGridItemPosition)(this.getPositionParams(),e,n,r,i,this.state),f=t.default.Children.only(this.props.children),m=t.default.cloneElement(f,{ref:this.elementRef,className:(0,l.default)(`react-grid-item`,f.props.className,this.props.className,{static:this.props.static,resizing:!!this.state.resizing,"react-draggable":a,"react-draggable-dragging":!!this.state.dragging,dropping:!!c,cssTransforms:u}),style:p(p(p({},this.props.style),f.props.style),this.createStyle(d))});return m=this.mixinResizable(m,d,o),m=this.mixinDraggable(m,a),m}};e.default=v,m(v,`propTypes`,{children:r.default.element,cols:r.default.number.isRequired,containerWidth:r.default.number.isRequired,rowHeight:r.default.number.isRequired,margin:r.default.array.isRequired,maxRows:r.default.number.isRequired,containerPadding:r.default.array.isRequired,x:r.default.number.isRequired,y:r.default.number.isRequired,w:r.default.number.isRequired,h:r.default.number.isRequired,minW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minWidth not Number`);if(n>e.w||n>e.maxW)return Error(`minWidth larger than item width/maxWidth`)},maxW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxWidth not Number`);if(n<e.w||n<e.minW)return Error(`maxWidth smaller than item width/minWidth`)},minH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minHeight not Number`);if(n>e.h||n>e.maxH)return Error(`minHeight larger than item height/maxHeight`)},maxH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxHeight not Number`);if(n<e.h||n<e.minH)return Error(`maxHeight smaller than item height/minHeight`)},i:r.default.string.isRequired,resizeHandles:c.resizeHandleAxesType,resizeHandle:c.resizeHandleType,onDragStop:r.default.func,onDragStart:r.default.func,onDrag:r.default.func,onResizeStop:r.default.func,onResizeStart:r.default.func,onResize:r.default.func,isDraggable:r.default.bool.isRequired,isResizable:r.default.bool.isRequired,isBounded:r.default.bool.isRequired,static:r.default.bool,useCSSTransforms:r.default.bool.isRequired,transformScale:r.default.number,className:r.default.string,handle:r.default.string,cancel:r.default.string,droppingPosition:r.default.shape({e:r.default.object.isRequired,left:r.default.number.isRequired,top:r.default.number.isRequired})}),m(v,`defaultProps`,{className:``,cancel:``,handle:``,minH:1,minW:1,maxH:1/0,maxW:1/0,transformScale:1})})),Zd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=Fd(),r=c(vr()),i=Ld(),a=Rd(),o=c(Xd()),s=c(Yd());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})})),Qd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=Ld();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]})}})),$d=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(Vd()),r=Fd(),i=Ld(),a=Qd(),o=c(Zd()),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})})),ef=r({default:()=>Af});function tf(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){hf(a)}function s(){var e=Date.now();if(n){if(e-i<gf)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function nf(e){return parseFloat(e)||0}function rf(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+nf(r)},0)}function af(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]=nf(o)}return n}function of(e){var t=e.getBBox();return df(0,0,t.width,t.height)}function sf(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return Cf;var r=Sf(e).getComputedStyle(e),i=af(r),a=i.left+i.right,o=i.top+i.bottom,s=nf(r.width),c=nf(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=rf(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=rf(r,`top`,`bottom`)+o)),!cf(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 df(i.left,i.top,s,c)}function cf(e){return e===Sf(e).document.documentElement}function lf(e){return pf?wf(e)?of(e):sf(e):Cf}function uf(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return xf(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function df(e,t,n,r){return{x:e,y:t,width:n,height:r}}var ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf=t((()=>{ff=(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}()})(),pf=typeof window<`u`&&typeof document<`u`&&window.document===document,mf=(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`)()})(),hf=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(mf):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),gf=2,_f=20,vf=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],yf=typeof MutationObserver<`u`,bf=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=tf(this.refresh.bind(this),_f)}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(){!pf||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),yf?(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(){!pf||!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;vf.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),xf=(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}),Sf=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||mf}),Cf=df(0,0,0,0),wf=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof Sf(e).SVGGraphicsElement}:function(e){return e instanceof Sf(e).SVGElement&&typeof e.getBBox==`function`}})(),Tf=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=df(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=lf(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}(),Ef=function(){function e(e,t){var n=uf(t);xf(this,{target:e,contentRect:n})}return e}(),Df=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new ff,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 Sf(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new Tf(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 Sf(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 Ef(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 ff,kf=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 Df(t,bf.getInstance(),this);Of.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){kf.prototype[e]=function(){var t;return(t=Of.get(this))[e].apply(t,arguments)}}),Af=(function(){return mf.ResizeObserver===void 0?kf:mf.ResizeObserver})()})),Mf=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(Vd()),i=s((jf(),e(ef))),a=s(vr()),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}})),Nf=n(i(((e,t)=>{t.exports=Zd().default,t.exports.utils=Ld(),t.exports.calculateUtils=Rd(),t.exports.Responsive=$d().default,t.exports.Responsive.utils=Qd(),t.exports.WidthProvider=Mf().default}))(),1),Pf=new Map;function Ff(e){Pf.set(e.type,e)}function If(e){return Pf.get(e)}function Lf(){return[...Pf.values()]}async function Rf(e,t,n){let r={successful:[],failed:[],pending:[]},i=[...new Set(e)],a=0;n.onProgress(0,i.length);for(let e of i){if(n.shouldStop())break;try{let n=await t([e]);r.successful.push(...n.successful),r.failed.push(...n.failed)}catch(t){r.failed.push({id:e,reason:t instanceof Error?t.message:String(t)}),a++,n.onProgress(a,i.length);break}a++,n.onProgress(a,i.length)}return r.pending=i.slice(a),r}function zf(e){return`/workspaces/${e}/hooks`}async function Bf(e){return await X.get(zf(e))||[]}async function Vf(e,t){return(await X.get(`${zf(e)}/${t}`))?.content??``}async function Hf(e,t,n){await X.put(`${zf(e)}/${t}`,{content:n})}async function Uf(e,t){await X.delete(`${zf(e)}/${t}`)}var Wf=[`example-`,`disabled-`,`_`];function Gf(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function Kf(e){return Wf.find(t=>e.startsWith(t))??null}function qf(e){return Kf(Gf(e).base)===null}function Jf(e){return Gf(e).base.startsWith(`example-`)}function Yf(e){let{dir:t,base:n}=Gf(e),r=Kf(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function Xf(e,t,n){if(qf(t)===n)return t;let r=Yf(t);return await Hf(e,r,await Vf(e,t)),await Uf(e,t),r}function Zf(e){let t={};for(let n of e){let e;e=n.path.includes(`/`)?n.path.split(`/`)[0]:/^(?:example-|disabled-|_)?rules\.json$/.test(n.path)?`rules`:n.path.replace(/\.js$/,``),(t[e]||=[]).push(n)}return t}function Qf(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function $f(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function ep(e){let t=String(e||``).split(`/`).filter(Boolean);return t[0]===`workspace`&&t.length>=2?{backend:`workspace:${t[1]}`,rel:t.slice(2).join(`/`)}:t[0]===`device`?t.length>=3?{backend:t[2],rel:t.slice(3).join(`/`)}:null:t.length>=2?{backend:t[1],rel:t.slice(2).join(`/`)}:null}function tp(e){let t=new URLSearchParams;return e.kind&&e.kind!==`mirror`&&t.set(`addRuleKind`,e.kind),e.path&&t.set(`addRulePath`,e.path),e.target&&t.set(`addRuleTarget`,e.target),e.storeTo&&t.set(`addRuleStoreTo`,e.storeTo),e.storeFolder&&t.set(`addRuleStoreFolder`,e.storeFolder),t}function np(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var rp=`rules.json`;async function ip(e){try{let t=await Vf(e,rp),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function ap(e,t){await Hf(e,rp,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
7
7
  `)}async function op(e,t={}){let n=new URLSearchParams;t.status&&n.set(`status`,t.status),t.handler&&n.set(`handler`,t.handler),t.limit&&n.set(`limit`,String(t.limit));let r=n.toString();return await X.get(`${zf(e)}/pending${r?`?${r}`:``}`)||[]}async function sp(e,t){return await X.post(`${zf(e)}/pending/decisions`,t)}async function cp(e,t){return await X.get(`${zf(e)}/runs/${encodeURIComponent(t)}`)}async function lp(e,t={}){let n=new URLSearchParams;t.limit&&n.set(`limit`,String(t.limit)),t.handler&&n.set(`handler`,t.handler),t.event&&n.set(`event`,t.event),t.failed&&n.set(`failed`,`true`);let r=n.toString();return await X.get(`${zf(e)}/runs${r?`?${r}`:``}`)||[]}var up=1e4,dp=`canvas.hooks.backfillLimit`;function fp(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?100:Math.min(t,up)}function pp(){try{let e=localStorage.getItem(dp);return e?fp(e):100}catch{return 100}}function mp(e){let t=fp(e);try{localStorage.setItem(dp,String(t))}catch{}return t}function hp(e){if(e.includes(`/`)){let t=e.split(`/`)[0];return t===`lib`||t===`rules`?null:t}return e.endsWith(`.js`)?e.replace(/\.js$/,``).replace(/^(?:example-|disabled-|_)/,``):null}async function gp(e,t){return await X.post(`${zf(e)}/backfill`,t)}async function _p(e,t){return await X.post(`${zf(e)}/run`,t)}async function vp(e,t){return await X.post(`${zf(e)}/runs/${t}/replay`,{})}async function yp(e){return await X.get(`${zf(e)}/meta`)}async function bp(e,t){return await X.post(`${zf(e)}/generate`,t)}async function xp(e,t){let n=await Vf(e,rp),r=JSON.parse(n),i=Array.isArray(r)?r:r?.rules;if(!Array.isArray(i))throw Error(`The workspace rules file is invalid. Fix it in Rules before adding a rule.`);let a=(Array.isArray(t)?t:[t]).filter(e=>!i.some(t=>t.id===e.id));if(!a.length)return;let o=Array.isArray(r)?[...i,...a]:{...r,rules:[...i,...a]};await Hf(e,rp,JSON.stringify(o,null,2)+`
@@ -18,15 +18,15 @@ Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})
18
18
  `;case`paragraph_close`:case`heading_close`:return`
19
19
 
20
20
  `;case`list_item_open`:return`- `;case`link_open`:return n.push(String(e.attrGet(`href`)||``)),``;case`link_close`:return` (${n.pop()||``})`;case`image`:return e.content;default:return``}}).join(``)};return t(xv.parse(e,{})).trim()}function Cv(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 wv={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function Tv({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${Cv(e)}:smtp-test:${i?.address}`:Cv(e,t,s),l=()=>({requestId:crypto.randomUUID(),text:a?`This is a test email sent from Canvas to check the SMTP configuration.`:``,replyToDocumentId:t,...i,...a?{subject:`Canvas SMTP test`}:{},...s?{forward:!0}:t?{replyAll:n===`replyAll`,quote:!0}:{}}),[u,d]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(c);if(e){let r=JSON.parse(e),i=r.draft||r;if(s||!t||r.attempted)return i;let a=n===`replyAll`;return{...i,replyAll:a,...!!i.replyAll===a?{}:{to:void 0,cc:void 0}}}}catch{}return l()}),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)([]),[g,_]=(0,Q.useState)(navigator.onLine);(0,Q.useEffect)(()=>{let e=()=>_(navigator.onLine);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]);let v=(0,Q.useRef)(!1),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let n=!0;return Promise.all([Gp(e),t?Kp(e,t):Promise.resolve(null)]).then(([e,r])=>{n&&(p(r),h(e.filter(e=>e.canSend&&(!r||e.driver===r.driver&&e.address===r.address))),t&&!r&&E(`This message has no supported reply account.`),r&&d(e=>{let t=e.replyAll?r.allRecipients:r.recipients;return{...e,driver:r.driver,address:r.address,...!s&&t&&!C?{to:e.to?.some(e=>e.trim())?e.to:t.to,cc:e.cc?.some(e=>e.trim())?e.cc:t.cc}:{}}}))}).catch(e=>{n&&E(e.message)}),()=>{n=!1}},[e,t,s,C]),(0,Q.useEffect)(()=>{try{D?.status===`accepted`?localStorage.removeItem(c):localStorage.setItem(c,JSON.stringify({draft:u,attempted:C}))}catch{}},[c,u,C,D]);let k=m.find(e=>e.driver===u.driver&&e.address===u.address),A=k?.driver===`imap`,j=k?.driver===`whatsapp`,M=!!u.images?.length,N=!!u.text.trim(),P=e=>d(t=>({...t,...e})),F=async()=>{S(!0),E(``),w(!0);let t=A?N?u:{...u,html:void 0}:{...u,text:j?Sv(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await Yp(e,u.requestId).catch(n=>{if(n.statusCode===404)return qp(e,t);throw n}):await qp(e,t);if(O(n),n.status===`accepted`){try{localStorage.removeItem(c)}catch{}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}}))}}catch(e){let t=e;E(t.message),!C&&t.statusCode&&t.statusCode>=400&&t.statusCode<500&&t.statusCode!==409&&w(!1)}finally{S(!1)}},I=async e=>{if(R||v.current)return;let t=e.filter(e=>[`image/png`,`image/jpeg`,`image/webp`,`image/gif`].includes(e.type));if(t.length){if((u.images?.length||0)+t.length>(j?1:8)){E(j?`One picture per WhatsApp reply.`:`Up to 8 pictures per email.`);return}if((u.images||[]).reduce((e,t)=>e+t.base64.length*3/4,0)+t.reduce((e,t)=>e+t.size,0)>8388608){E(`Pictures must total at most 8 MB.`);return}v.current=!0,b(!0);try{let e=await Promise.all(t.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>n(Error(`Could not read picture`)),r.onload=()=>t({name:e.name,mimeType:e.type,base64:String(r.result).split(`,`)[1]}),r.readAsDataURL(e)})));d(t=>({...t,images:[...t.images||[],...e]})),E(``)}catch(e){E(e instanceof Error?e.message:`Could not read picture`)}finally{v.current=!1,b(!1)}}},L=u.replyAll?f?.allRecipients:f?.recipients,R=x||C||y,z=a?`Send test email`:t?s?wv.forward:wv[u.replyAll?`replyAll`:`reply`]:`New message`,ee=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,$.jsxs)(`section`,{onPasteCapture:e=>{if(!(A||j))return;let t=Array.from(e.clipboardData.files);t.some(e=>e.type.startsWith(`image/`))&&(e.preventDefault(),e.stopPropagation(),I(t))},className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${z} to message`:`New message`,children:[(0,$.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,$.jsx)(`strong`,{className:`text-sm`,children:z}),(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,$.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,$.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:k?`${k.driver}:${k.address}`:``,disabled:R||!!t||!!i,onChange:e=>{let t=m.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&P({driver:t.driver,address:t.address,to:[],cc:[],bcc:[],subject:void 0,target:void 0,images:void 0,replyAll:!1})},children:[(0,$.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,$.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Uses the saved SMTP settings. Enter a recipient you control, then click Send. This sends a real email; provider acceptance does not guarantee inbox delivery.`}),!m.length&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Enable sending in the account’s workspace settings. Your draft stays on this device.`}),A?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,$.jsx)(Y,{"aria-label":`To`,disabled:R,value:u.to?.join(`, `)||``,onChange:e=>P({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&L&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,L.to.join(`, `),L.cc.length?` · Cc: ${L.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,$.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,$.jsx)(Y,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:R,value:u[e]?.join(`, `)||``,onChange:t=>P({[e]:[t.target.value]})})]},e)),(0,$.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,$.jsx)(Y,{"aria-label":`Subject`,disabled:R,value:u.subject||``,placeholder:ee,onChange:e=>P({subject:e.target.value||void 0})})]}),t&&!s&&(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,$.jsxs)(`label`,{className:`flex gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:R,checked:u.replyAll||!1,onChange:e=>{let t=e.target.checked?f?.allRecipients:f?.recipients;P({replyAll:e.target.checked,...t?{to:t.to,cc:t.cc}:{}})}}),`Reply all`]}),(0,$.jsxs)(`label`,{className:`flex gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:R,checked:u.quote||!1,onChange:e=>P({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,$.jsx)(Po,{format:`html`,editable:!R,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>P({html:e,text:t.slice(0,32e3)})})]}):(0,$.jsxs)($.Fragment,{children:[!t&&(0,$.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,$.jsx)(Y,{"aria-label":`Conversation`,disabled:R,value:u.target||``,onChange:e=>P({target:e.target.value})})]}),j?(0,$.jsx)(Po,{format:`markdown`,editable:!R,value:u.text,placeholder:`Write a message…`,onChange:e=>P({text:e.slice(0,32e3)})}):(0,$.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:R,value:u.text,onChange:e=>P({text:e.target.value}),placeholder:`Write a message…`})]}),(A||j)&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,$.jsx)(`input`,{"aria-label":`Attach pictures`,className:`block`,type:`file`,accept:`image/png,image/jpeg,image/webp,image/gif`,multiple:!j,disabled:R,onChange:e=>{I(Array.from(e.target.files||[])),e.target.value=``}})]}),u.images?.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,$.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,disabled:R,onClick:()=>P({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),j&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[D.status===`accepted`?`Accepted by the provider.`:D.message,` `,D.warnings?.join(` `),` `,D.rejected?.length?`Not accepted for: ${D.rejected.join(`, `)}`:``]}),D?.status!==`accepted`&&(0,$.jsx)(Z,{size:`sm`,disabled:x||y||!C&&(!k||!N&&!M&&!(A&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void F(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,disabled:x,onClick:()=>{window.confirm(C?`This message may already have been sent. Discard this draft only after checking the conversation.`:`Discard this draft?`)&&(d({...l(),driver:u.driver,address:u.address}),w(!1),O(null),E(``))},children:`Discard draft`}),C&&D?.status!==`accepted`&&(0,$.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.`})]})}function Ev(e){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(e.onClose);return(0,Q.useEffect)(()=>{n.current=e.onClose}),(0,Q.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,$.jsx)(`dialog`,{ref:t,"aria-label":e.replyToDocumentId?`${e.mode===`forward`?`Forward`:e.mode===`replyAll`?`Reply all`:`Reply`} message`:`Send test email`,className:`m-auto w-[calc(100%-2rem)] max-w-3xl max-h-[90dvh] overflow-y-auto rounded-(--panel-radius) border bg-card p-0 text-foreground shadow-elevation-4 backdrop:bg-black/40`,onKeyDown:e=>e.stopPropagation(),onCancel:e=>{e.preventDefault(),e.stopPropagation(),n.current()},children:(0,$.jsx)(Tv,{...e})})}function Dv({workspaceId:e,documentId:t}){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)({}),[c,l]=(0,Q.useState)(null),u=(0,Q.useCallback)(async()=>{try{let n=await Zp(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,Q.useEffect)(()=>{let n=!0;Zp(e,t).then(e=>{n&&(r(e),a(``))}).catch(e=>{n&&a(e instanceof Error?e.message:`Could not load thread`)});let i=()=>{u()};return window.addEventListener(`workspace:documents:refresh`,i),window.addEventListener(Lg,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(Lg,i)}},[e,t,u]),i?(0,$.jsxs)(`div`,{className:`p-3`,children:[(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,$.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,$.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No linked replies have been indexed. Other messages in this conversation are separate from this reply thread.`}),n.truncated&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Showing up to 200 linked messages.`}),n.documents.map(r=>{let i=Yr(r),a=r.schema===`data/schema/message/email`,c=a||[`slack`,`whatsapp`].includes(String(r.data.platform)),u=r.data.timestamp||r.data.date,d=u?new Date(String(u)):null,f=(n.parents[r.id]||[]).flatMap(e=>{let t=n.documents.find(t=>Number(t.id)===e);return t?[Yr(t).title]:[]}),p=o[Number(r.id)]??Number(r.id)===t;return(0,$.jsxs)(`details`,{open:p,onToggle:e=>{let t=e.currentTarget.open;s(e=>e[Number(r.id)]===t?e:{...e,[Number(r.id)]:t})},className:`rounded-lg border bg-card`,children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,$.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,$.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,$.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,$.jsx)(bv,{workspaceId:e,document:r})]},r.id)}),c&&(0,$.jsx)(Ev,{workspaceId:e,replyToDocumentId:Number(c.document.id),mode:c.mode,originalSubject:typeof c.document.data.subject==`string`?c.document.data.subject:void 0,onClose:()=>l(null)},`${c.document.id}:${c.mode}`)]})}var Ov=15,kv=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function Av(e){return String(e).padStart(2,`0`)}function jv(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 Mv(e){return`${e.getFullYear()}-${Av(e.getMonth()+1)}-${Av(e.getDate())}`}function Nv(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function Pv(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/Ov)*Ov),`${Av(e.getHours())}:${Av(e.getMinutes())}`}function Fv(){let e=[];for(let t=0;t<1440;t+=Ov)e.push(`${Av(Math.floor(t/60))}:${Av(t%60)}`);return e}var Iv=Fv();function Lv(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 Rv(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 zv(e){let t=jv(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 Bv({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,Q.useState)(!1),u=(0,Q.useRef)(null),d=jv(e),f=d?zv(e):``;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:J(`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,$.jsx)(pe,{className:J(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,$.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,$.jsx)(G,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,$.jsx)(Vv,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Vv({anchorRef:e,value:t,onChange:n,onClose:r}){let i=jv(t),a=i?.date??Mv(new Date),o=i?.time??null,[s,c]=(0,Q.useState)(()=>{let e=Nv(a);return new Date(e.getFullYear(),e.getMonth(),1)}),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(null);(0,Q.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,Q.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,Q.useMemo)(()=>!o||Iv.includes(o)?Iv:[...Iv,o].sort(),[o]);(0,Q.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??Pv();m(Mv(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??Pv();m(Mv(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},v=Mv(new Date),y=Lv(s);return(0,Ip.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,$.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,$.jsxs)(`div`,{className:`w-[236px]`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,$.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,$.jsx)(E,{className:`h-4 w-4`})}),(0,$.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,$.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,$.jsx)(hr,{className:`h-4 w-4`})})]}),(0,$.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:kv.map(e=>(0,$.jsx)(`span`,{children:e},e))}),(0,$.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:y.map(e=>{let t=Mv(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,$.jsx)(`button`,{type:`button`,onClick:()=>h(e),"aria-pressed":r,className:J(`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,$.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,$.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,$.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,$.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,$.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,$.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>g(e),"aria-pressed":t,className:J(`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:Rv(e)},e)})})]})]})]}),document.body)}var Hv={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Uv=`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`,Wv=`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 Gv({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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${u}-title`,children:`Title`}),(0,$.jsx)(Y,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${u}-desc`,children:`Description`}),(0,$.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:Wv})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${u}-due`,children:`Due`}),(0,$.jsx)(Bv,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${u}-priority`,children:`Priority`}),(0,$.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Uv,children:[(0,$.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,$.jsx)(`option`,{value:e,children:Hv[e]},e))]})]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${u}-status`,children:`Status`}),(0,$.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Uv,children:B_.map(e=>(0,$.jsx)(`option`,{value:e,children:V_[e]},e))})]})]})}var Kv=`3.0`,qv=[`person`,`organization`,`service`,`bot`],Jv={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Yv=[`email`,`phone`,`sms`,`chat`,`web`],Xv=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function Zv(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 Qv(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Gi(String(e?.schema||``),xi);return{displayName:String(t.displayName||``),type:qv.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 $v(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await go(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function ey(e){let[t,n]=(0,Q.useState)(e?.displayName??``),[r,i]=(0,Q.useState)(e?.type??`person`),[a,o]=(0,Q.useState)(e?.primaryEmail??``),[s,c]=(0,Q.useState)(e?.given??``),[l,u]=(0,Q.useState)(e?.family??``),[d,f]=(0,Q.useState)(e?.channels??[]),[p,m]=(0,Q.useState)(e?.identifiers??[]),[h,g]=(0,Q.useState)(e?.organizations??[]),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.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:`${xi}/${C.type}`,schemaVersion:Kv,data:Zv(C),...t?{comment:t}:{},metadata:{features:Yo(_)}},r=await ys(e,[n]);return await $v(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 ty=`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 ny({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(Gu,{children:e}),(0,$.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,$.jsx)(sn,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,$.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,$.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,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]},i))})]})}function ry(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 iy(e){let[t,n]=(0,Q.useState)([]);return(0,Q.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Ui(e,`organization`);t||n(r.map(e=>({id:e.id,name:Yr(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function ay({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=iy(t);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,$.jsx)(Y,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${e}-type`,children:`Type`}),(0,$.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:J(ty,`w-full`),children:qv.map(e=>(0,$.jsx)(`option`,{value:e,children:Jv[e]},e))})]}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${e}-email`,children:`Primary email`}),(0,$.jsx)(Y,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${e}-given`,children:`Given name`}),(0,$.jsx)(Y,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${e}-family`,children:`Family name`}),(0,$.jsx)(Y,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,$.jsx)(ny,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:J(ty,`w-24`),children:[Yv.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),!Yv.includes(e.kind)&&(0,$.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,$.jsx)(Y,{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,$.jsx)(`button`,{type:`button`,onClick:()=>p(ry(f,f.indexOf(e))),className:J(`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,$.jsx)(Cn,{className:J(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,$.jsx)(ny,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:J(ty,`w-24`),children:[Xv.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),!Xv.includes(e.type)&&(0,$.jsx)(`option`,{value:e.type,children:e.type})]}),(0,$.jsx)(Y,{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,$.jsx)(ny,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,$.jsxs)($.Fragment,{children:[y.length>0?(0,$.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:J(ty,`min-w-0 flex-1`),children:[(0,$.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,$.jsx)(Y,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,$.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,$.jsx)(Zt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Y,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function oy(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 sy(e){return oy(e.schema)||Ro(e)}function cy(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function ly(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await $i(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 go(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await ui(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function uy({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),a=oy(e.schema),o=e.schema===ko,s=Ro(e),c=Wo(e)??`markdown`,l=s&&Mo(e),u=e.schema===Ji,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=cy(e.schema),[m,h]=(0,Q.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,Q.useState)(String(e.data?.[p]??``)),[v,y]=(0,Q.useState)(String(e.data?.content??``)),[b,x]=(0,Q.useState)(String(e.data?.description??``)),[S,C]=(0,Q.useState)(e.data?.status??`pending`),[w,T]=(0,Q.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,Q.useState)(e.data?.dueDate?W_(String(e.data.dueDate)):K_()),O=ey(Qv(e)),[k,A]=(0,Q.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[M,N]=(0,Q.useState)(j),P=e.features??e.metadata?.features,[F,I]=(0,Q.useState)(Jo(P).length?Jo(P):e.data?.tags??[]),L=No(e,t,o),{title:R,content:z,comment:ee,tags:te,geo:ne,setTitle:B,setContent:re,setComment:ie,setTags:ae,setGeo:oe}=o?L:{title:g,content:v,comment:k,tags:F,geo:M,setTitle:_,setContent:y,setComment:A,setTags:I,setGeo:N},V=JSON.stringify(ne??null)!==JSON.stringify(j??null),H=Fo(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Vo,version:e.checksumArray?.[0]??null}),[U,se]=(0,Q.useState)(null),W=`${e.id}:${e.checksumArray?.[0]??``}`;s&&H.text!=null&&U!==W&&(se(W),re(H.text));let[ce,le]=(0,Q.useState)([]),[ue,de]=(0,Q.useState)(!1),{replicating:fe,mirror:pe}=bo(e);(0,Q.useEffect)(()=>{let e=!1;return Xr(t).then(t=>{e||le(t)}).catch(()=>{}),()=>{e=!0}},[t]);let me=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),G=!ue&&(s?!l&&H.text!=null&&!H.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?R.trim().length>0:o?L.canSave:me:!0),he=async()=>{de(!0);try{if(o){await L.save(),n();return}if(s){let i=await Ko(t,e,z,{comment:ee.trim(),...V?{metadata:{geo:ne}}:{}});r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n(i);return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:ee.trim()};if(d){let{type:t,...n}=e.data??{};i.schema=`${xi}/${O.values.type}`,i.data={...n,...Zv(O.values)},i.metadata={features:Yo(te)}}else if(u)i.data={...e.data,...q_({title:R,description:b,status:S,priority:w,due:E})},i.metadata={features:Yo(te)};else if(a){let t=te.map(e=>e.trim()).filter(Boolean),n;o?n={...R.trim()?{title:R.trim()}:{},content:z}:(n={...e.data},f&&(n[f]=m.trim()),R.trim()?n[p]=R.trim():delete n[p],n.tags=t),i.data=n,i.metadata={features:Yo(te)}}V&&(i.metadata={...i.metadata??{},geo:ne}),await fa(t,i),d&&(await ly(t,e.id,O.values.organizations),Rg()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{de(!1)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`edit-url`,children:`URL`}),(0,$.jsx)(Y,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!me&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,$.jsx)(ay,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,$.jsx)(Gv,{idPrefix:`edit-todo`,title:R,setTitle:B,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`edit-title`,children:`Title`}),(0,$.jsx)(Y,{id:`edit-title`,value:R,onChange:e=>B(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Body`}),l?(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&H.error?(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:H.error}):s&&H.text==null?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,$.jsx)(Ho,{kind:o?`markdown`:c,value:z,onChange:re,placeholder:o?`Write your note…`:void 0})]}),a&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:te,onChange:ae,suggestions:ce})]}),(0,$.jsx)(mg,{value:ne,onChange:oe}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`edit-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`edit-comment`,value:ee,onChange:e=>ie(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`})]}),o&&(0,$.jsx)(Go,{...L,onRetry:L.save}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>n(),disabled:ue,children:o?`Close`:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:he,disabled:!G,children:ue?fe?`Replicating to ${pe.label}…`:`Saving…`:`Save changes`})]})]})}var dy=(0,Q.createContext)(null),fy={open:()=>{},close:()=>{}};function py(){return(0,Q.useContext)(dy)??fy}var my=`main`,hy=(0,Q.createContext)(null);function gy(){return(0,Q.useContext)(hy)}var _y=50;function vy({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=py(),o=Eg(),s=gy(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?Yr(l).title:``,[d,f]=(0,Q.useState)(!1),{showErrorToast:p}=Wr(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await Ja(t,c):l;s?o.open(n,t):a(n,t)}catch(e){p(e instanceof Error?e.message:`Failed to open document`)}finally{f(!1)}}},h=!e.meta||e.meta.src===`doc`;return(0,$.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,$.jsx)(Dt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,$.jsx)(Jn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,$.jsx)(Gm,{document:l,size:3.5}):null,l?(0,$.jsx)(`button`,{type:`button`,onClick:()=>void m(),disabled:d,className:`min-w-0 flex-1 truncate text-left hover:underline`,title:u,children:u}):(0,$.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,$.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!h&&(0,$.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}),h&&(0,$.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,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})}function yy({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(0),[g,_]=(0,Q.useState)(1),v=(0,Q.useRef)(0),y=(0,Q.useCallback)(()=>{v.current++},[]),b=(0,Q.useCallback)(async()=>{let n=++v.current;try{let r=await $i(t,e.id,{offset:m*_y,limit:_y,summary:!0});if(n!==v.current)return;let i=Math.max(0,Math.ceil(Math.max(r.outgoingCount??r.outgoing.length,r.incomingCount??r.incoming.length)/_y)-1);if(_(i+1),m>i){h(i);return}a(r),s(null)}catch(e){if(n!==v.current)return;s(e instanceof Error?e.message:String(e))}},[t,e.id,m]),x=`${t}:${e.id}`,[S,C]=(0,Q.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,Q.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(Lg,e),()=>{y(),window.removeEventListener(Lg,e)}},[b,y]);let w=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 ui(t,e.id,i.p,o,a),n(`Relation removed`),Rg()}catch(e){r(e instanceof Error?e.message:`Failed to remove relation`)}finally{p(null)}},T=[{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??[]}],E=e=>{a(null),h(e)};return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,$.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,$.jsx)(sn,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,$.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,$.jsxs)(`div`,{children:[(0,$.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,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.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,$.jsx)(vy,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,$.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,$.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,$.jsx)($p,{onClose:()=>{u||l(!1)},children:(0,$.jsx)(ih,{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 go(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),Rg()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var by=(0,Q.lazy)(()=>g(()=>import(`./SketchEditor-BBVmOe4V.js`),__vite__mapDeps([9,3,4,10,1,11,12,13,14,15,16,17,18,19,20,21,22,23]))),xy=(0,Q.lazy)(()=>g(()=>import(`./TextDocumentEditor-C0IJWp9j.js`),__vite__mapDeps([24,3,4,11,10,13,12,14,15,16,25,1,22]))),Sy={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},Cy={reply:Ue,replyAll:L,forward:Ge};function wy({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=jo()!=null,{showErrorToast:a}=Wr(),[o,s]=(0,Q.useState)(!1),c=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[l,u]=(0,Q.useState)(null),d=e.schema===`data/schema/message/email`,f=!i&&(d||[`slack`,`whatsapp`].includes(String(e.data?.platform))),p=d?[`reply`,`replyAll`,`forward`]:[`reply`],m=e=>u(t=>t===e?null:e),h=!i,[g,_]=(0,Q.useState)(n&&sy(e)),v=e.schema===Mi,[y,b]=(0,Q.useState)(!1),x=e.schema===`data/schema/note`||Ro(e),[S,C]=(0,Q.useState)(!1),w=`${t}:${e.id}:${n}:${i}`,[T,E]=(0,Q.useState)(w);w!==T&&(E(w),_(n&&sy(e)),u(null),s(!1),b(!1),C(!1));let D=t=>{if(!h||!sy(e)||t.defaultPrevented)return!1;let n=t.target;return n instanceof Element&&t.currentTarget.contains(n)&&!n.closest(`a, button, input, textarea, select, label, summary, audio, video, [role="button"], [role="checkbox"], [contenteditable]:not([contenteditable="false"])`)};return g&&h?(0,$.jsx)(uy,{document:e,workspaceId:t,onClose:e=>{_(!1),r?.(e)}}):(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[h&&(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[c&&(0,$.jsx)(Z,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=Cy[e];return(0,$.jsxs)(Z,{size:`sm`,variant:l===e?`secondary`:`outline`,onClick:()=>m(e),children:[(0,$.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),Sy[e]]},e)}),e.schema===`data/schema/file`&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>ji(t,e.id,wi(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,$.jsx)(qt,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,$.jsx)(le,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>C(!0),children:[(0,$.jsx)(gr,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,$.jsx)(_e,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),y&&h&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,$.jsx)(by,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),_(!0)}})}),S&&h&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,$.jsx)(xy,{doc:e,workspaceName:t,onSaved:e=>{C(!1),r?.(e)},onClose:()=>C(!1),onDetails:()=>{C(!1),_(!0)}})}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,onMouseDownCapture:e=>{e.button===0&&e.detail>1&&D(e)&&e.preventDefault()},onDoubleClickCapture:e=>{D(e)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.ownerDocument.getSelection()?.removeAllRanges(),_(!0))},children:[o&&!i?(0,$.jsx)(Dv,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,$.jsx)(bv,{workspaceId:t,document:e}),l&&f&&(0,$.jsx)(Ev,{workspaceId:t,replyToDocumentId:Number(e.id),mode:l,originalSubject:d&&typeof e.data?.subject==`string`?e.data.subject:void 0,onClose:()=>u(null)},`${e.id}:${l}`)]}),e.comment?.trim()&&(0,$.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,$.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,$.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var Ty=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,Ey=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function Dy({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,$.jsxs)(`div`,{children:[(0,$.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,$.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,$.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`,Ey(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`,Ty(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,$.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 Oy({document:e}){let t=e.metadata;return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,$.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,$.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,$.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,$.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,$.jsx)(`span`,{className:`ml-2`,children:Ty(e.createdAt)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,$.jsx)(`span`,{className:`ml-2`,children:Ty(e.updatedAt)})]})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,$.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,$.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,$.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,$.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,$.jsx)(Dy,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,$.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=My(e.url);return(0,$.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,$.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),r&&(0,$.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,$.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,$.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,$.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,$.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,$.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,$.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,$.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,$.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function ky({document:e}){let{showSuccessToast:t,showErrorToast:n}=Wr(),r=JSON.stringify(e,null,2);return(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`flex justify-end`,children:(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,$.jsx)(A,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,$.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function Ay({document:e,workspaceId:t}){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,Q.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,Q.useEffect)(()=>{let n=!1;return ta(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,$.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,$.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,$.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,$.jsx)(yy,{document:e,workspaceId:t})]}):(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function jy(e){return e===`stored`?er:e===`workspace-file`?Pe:e===`imap`?bt:e===`readonly`?Ye:Hn}function My(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 Ny({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(!1),_=`${t}:${e.id}`,[v,y]=(0,Q.useState)(_);_!==v&&(y(_),o(null),c(null),f(null));let b=()=>{gi(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,Q.useEffect)(()=>{let n=!1;return gi(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 La(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 Wa(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(wp(i.failed,new Map([[e.id,wi(e)||`Document ${e.id}`]]))||`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,$.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let w=a.length===0,T=wi(e);return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,$.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(er,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,$.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,$.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),w?(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>m(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,$.jsx)(A,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,$.jsxs)(Z,{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,$.jsx)(Dt,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=jy(n.kind),{backend:a,key:o}=My(n.url),s=l===n.url;return(0,$.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,$.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,$.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,$.jsx)(`button`,{onClick:()=>ji(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,$.jsx)(qt,{className:`h-3.5 w-3.5`})}),(0,$.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,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})]}),d===n.url&&(0,$.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,$.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,$.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(Z,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!1),children:`Also remove index entry`}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!0),children:`Keep index entry (no bytes)`}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>f(null),children:`Cancel`})]})]})]},n.url)}),p&&(0,Ip.createPortal)((0,$.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,$.jsx)(Sg,{workspaceId:t,documentCount:1,initialMode:p,defaultFilename:T,saving:h,onConfirm:S,onClose:()=>{h||m(null)}})}),window.document.body)]})}function Py(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 Fy(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 Iy(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&&Fy(e,t,n.points)}function Ly(e,t,n=!1){let r=Py(e);return r?Iy(r.lat,r.lon,t):n}var Ry=(0,Q.lazy)(()=>g(()=>import(`./LocationTab-BONJQfYM.js`),__vite__mapDeps([26,3,4,27,28]))),zy=[{id:`view`,label:`View`,icon:Xn},{id:`location`,label:`Location`,icon:tn},{id:`metadata`,label:`Metadata`,icon:F},{id:`json`,label:`JSON`,icon:it},{id:`synapses`,label:`Synapses`,icon:jn},{id:`backends`,label:`Backends`,icon:er}];function By({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1,navigation:s,tabActions:c,onTabChange:l}){let u=jo()!=null,d=Py(e),f=zy.filter(e=>(e.id!==`location`||d!==null)&&(!u||![`synapses`,`backends`].includes(e.id))),[p,m]=(0,Q.useState)(n),h=`${e.id}:${n}`,[g,_]=(0,Q.useState)(h);h!==g&&(_(h),m(n));let v=f.some(e=>e.id===p)?p:`view`,y=e=>{m(e),l?.(e)},b=o&&!!c&&!s,x=(0,$.jsx)(`div`,{className:J(b&&`document-detail-header shrink-0 border-b-[3px] bg-muted`),children:(0,$.jsxs)(`div`,{className:J(`flex min-w-0 items-center`,b&&`mx-auto h-[calc(3rem-4px)] w-full max-w-[var(--document-reading-width,100%)] gap-1 pl-2 pr-2 sm:pl-4`),children:[(0,$.jsx)(Qg,{tabs:f,active:v,onChange:y,className:J(`min-w-0 flex-1 px-1`,b&&`h-full border-b-0 px-0 max-sm:gap-0 max-sm:[&>button]:px-2.5`),iconOnly:o}),c]})});return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[s?(0,$.jsx)(Zg,{...s,tabs:x,section:v,onDocument:()=>y(`view`),onSection:()=>y(`view`),onBack:v===`view`?s.onBack:()=>y(`view`)}):x,(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto h-full w-full max-w-[var(--document-reading-width,100%)] p-4`,children:[v===`view`&&(0,$.jsx)(wy,{document:e,workspaceId:t,initialEdit:r&&!u,onChanged:i}),v===`location`&&d&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,$.jsx)(Ry,{lat:d.lat,lon:d.lon})}),v===`metadata`&&(0,$.jsx)(Oy,{document:e,workspaceId:t}),v===`json`&&(0,$.jsx)(ky,{document:e,workspaceId:t}),v===`synapses`&&!u&&(0,$.jsx)(Ay,{document:e,workspaceId:t}),v===`backends`&&!u&&(0,$.jsx)(Ny,{document:e,workspaceId:t,onChanged:i})]})})]})}function Vy(e,t){let[n,r]=(0,Q.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,Q.useState)(a);a!==o&&(s(a),r(null));let c=(0,Q.useRef)(a),l=(0,Q.useRef)(0);(0,Q.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,Q.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}Ja(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}function Hy(e){let t=qg(),n=(0,Q.useContext)(wg),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,Q.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,$.jsx)(Uy,{...e})}function Uy({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,Q.useState)(!1),c=es(),{document:l,refresh:u}=Vy(r,e);if(Fp(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,Ip.createPortal)((0,$.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:J(`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,$.jsxs)(`div`,{className:J(`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-(--panel-radius) md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-(--panel-radius)`),onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:Yr(l).title}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=Fa(l);return e?(0,$.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,$.jsx)(Ht,{className:`h-4 w-4`})}):null})(),(0,$.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,$.jsx)(lt,{className:`h-4 w-4`}):(0,$.jsx)(xn,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,$.jsx)(zg.Provider,{value:()=>s(e=>!e),children:(0,$.jsx)(By,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Wy={sortBy:`alphabetical`,order:`asc`};function Gy(e){return e?.sortBy===`crud:deleted`?{...Wy}:{sortBy:e?.sortBy??Wy.sortBy,order:e?.order??Wy.order}}var Ky={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:{...Wy}};function qy(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function Jy(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 Yy(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function Xy(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Yy(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 Zy(e,t,n=[]){return{features:e.features,filters:[...Xy(e.timeline),...qy(e.geo),...Jy(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 Qy=Wy,$y={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function eb(e){return $y[e]??e}function tb(e){let[t,n]=(0,Q.useState)([]);return(0,Q.useEffect)(()=>{let t=!1;return Ia(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,Q.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:eb(e)})),[t])}function nb({workspaceId:e,value:t,onChange:n}){let r=tb(e);return(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,$.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value,order:[`alphabetical`,`type`].includes(e.target.value)?`asc`:t.order}),className:`h-7 rounded-md border bg-background px-1.5 text-xs`,title:`Sort by`,"aria-label":`Sort by`,children:[t.sortBy!==`crud:deleted`&&!r.some(e=>e.value===t.sortBy)&&(0,$.jsx)(`option`,{value:t.sortBy,children:eb(t.sortBy)}),r.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending`:`Descending`,"aria-label":t.order===`asc`?`Ascending`:`Descending`,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,$.jsx)(yt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Bt,{className:`h-3.5 w-3.5`})})]})}function rb(e,t){let n=t?.replace(/^t:/,``)||`crud:created`,r=(n===`crud:created`?[e.createdAt]:n===`crud:updated`?[e.updatedAt]:(e.timelines??[]).filter(e=>(e.timeline||e.name)===n).map(e=>e.start)).map(e=>Date.parse(e??``)).filter(Number.isFinite);return r.length?Math.min(...r):null}var ib={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},ab=e=>e*1e6;function ob(){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 sb(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function cb(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=sb(e);return r.setDate(r.getDate()-n),r}var lb=864e5;function ub(e){let t=ob(),n=sb(e),r=cb(e,t);return{today:n.getTime(),yesterday:n.getTime()-lb,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*lb,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function db(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:ab(ib.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:ab(ib.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:ab(ib.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:ab(ib.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:ab(ib.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:ab(ib.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:ab(ib.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:ab(ib.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:ab(ib.year)+i}}function fb(e,t,n=`desc`,r=new Date){let i=ub(r),a=new Map;for(let n of e){let e=db(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 pb(e,t){let n=t.split(`/`).filter(Boolean);if(e!==`backends`||n[0]!==`Trash`)return null;try{return{backend:n[1]?decodeURIComponent(n[1]):null,prefix:n.slice(2).join(`/`)}}catch{return null}}function mb(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function hb(e,t=``){let n=new Map,r=[],i=t?`${t}/`:``;for(let t of e){if(!t.key.startsWith(i))continue;let e=t.key.slice(i.length);if(!e)continue;let a=e.indexOf(`/`);if(a>=0){let r=e.slice(0,a),o=i+r,s=n.get(o)??{id:`folder:${o}`,name:r,key:o,directory:!0,navigable:!0,items:[]};s.items.push(t),n.set(o,s)}else r.push({id:t.id,name:e,key:t.key,directory:t.type===`directory`,navigable:!1,items:[t]})}return[...n.values(),...r].sort((e,t)=>Number(t.directory)-Number(e.directory)||e.name.localeCompare(t.name)||t.items[0].deletedAt-e.items[0].deletedAt||e.id.localeCompare(t.id))}var gb=(e,t)=>`${xr.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function _b(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await X.get(`${gb(e,t)}?${o}`);if(n.push(...s.items),a=s.retention?.days??null,i=s.cursor,i&&r.has(i))throw Error(`Trash listing returned a repeated cursor`);i&&r.add(i)}while(i);return{items:n,days:a}}function vb(e,t,n){return bb(e,t,n,`restore`)}function yb(e,t,n){return bb(e,t,n,`discard`)}async function bb(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await X.post(`${gb(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{Da(e,`backends`),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:`backends`}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e,backend:t}}))}}async function xb(e,t){let n=pb(`backends`,t);if(!n?.backend)return;let{items:r}=await _b(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`)).sort((e,t)=>t.deletedAt-e.deletedAt),a=await vb(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} restored; ${o.length} remain in Trash. Existing paths were kept.`)}function Sb(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
21
- `)+(n.length>5?`\n…and ${n.length-5} more paths`:``);return window.confirm(`Permanently delete ${t.length} Trash item(s) from ${e}?\n\n${r}\n\nDeleted folders include all their contents. This cannot be undone. Files currently at the original paths are kept.`)}async function Cb(e,t){let n=pb(`backends`,t);if(!n?.backend)return;let{items:r}=await _b(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Sb(n.backend,i))return;let a=await yb(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} deleted; ${o.length} remain in Trash. ${o[0].message||o[0].reason||`Please retry.`}`)}function wb(){let{showProgress:e}=Vr();return(0,Q.useCallback)(async(t,n,r,i)=>{let a=e({title:t,description:n});try{let e=await i();if(e===!1)throw Error(`The operation could not be completed.`);return a.done({title:r,description:n}),e}catch(e){throw a.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}},[e])}var Tb=new Map;function Eb(e,t,n,r,i){let a=JSON.stringify([t,n,r]),o=Tb.get(a);if(o)return o;let s=(async()=>{let a=e({title:`Resyncing…`,description:r});try{for(await va(t,n,r);;){let e=await Xi(t,n,r);if(i?.(e),!e.resyncing&&e.status!==`syncing`){if(e.lastError)throw Error(e.lastError);a.done({title:e.resyncCancelledAt?`Resync stopped`:`Resync complete`,description:`${r}${e.progress?` · ${e.progress.scanned} files scanned`:``}`}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t,treeName:`backends`}}));return}let o=e.progress;a.update({title:`Resyncing…`,description:`${r}${o?` · ${o.scanned}${o.total==null?``:` / ${o.total}`} files scanned`:``}`}),await new Promise(e=>setTimeout(e,2e3))}}catch(e){throw a.fail({title:`Resync needs attention`,description:`${r}: ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return Tb.set(a,s),s.finally(()=>{Tb.get(a)===s&&Tb.delete(a)}).catch(()=>{}),s}var Db=[`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.path.locked`,`tree.path.unlocked`,`tree.layer.updated`,`tree.layer.converted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`,`context.path.changed`,`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`],Ob=new Map;function kb(e,t,n){Da(e,t),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t,cacheInvalidated:!0}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}function Ab(e,t){let n=Ob.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=Db.map(n=>{let a=(a={})=>{if(n===`backend.resync.changed`&&a.resyncing!==!1)return;let o=typeof a.workspaceId==`string`?a.workspaceId:null,s=typeof a.workspaceName==`string`?a.workspaceName:null;if(o&&!t.has(o)||!o&&s&&s!==e)return;let c=typeof a.treeName==`string`?a.treeName:void 0;n===`tree.renamed`?c=void 0:n===`context.path.changed`?c??=`context`:[`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`].includes(n)&&(c??=`backends`),r.add(c),!i&&(i=setTimeout(()=>{i=void 0;let t=r.has(void 0)?[void 0]:[...r];r.clear();for(let n of t)Da(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return hd.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)Da(e,t);a.forEach(([e,t])=>hd.off(e,t))}},Ob.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),Ob.delete(e))}}function jb({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=wb(),{showProgress:a}=Vr(),o=n||`context`,s=o===`directory`,c=(0,Q.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),l=(0,Q.useCallback)(async(n,r=!0)=>{let i;if(e)i=await vs(e,n,r);else if(t)i=await Aa(t,n,r,o);else return!1;let a=Tm(n);if(i&&a)try{e?await ds(e,n,a):t&&await zi(t,n,a,o)}catch{}return c(),i},[e,t,o,c]),u=(0,Q.useCallback)(async(n,r=!1,a=!1,s=!1)=>i(s?`Destroying…`:a?`Purging…`:`Removing…`,n,s?`Destroyed`:a?`Purged`:`Removed`,async()=>{try{return e?await us(e,n,r):t?await na(t,n,r,o,a,s):!1}finally{c()}}),[e,t,o,c,i]),d=(0,Q.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await ms(e,n,t.join(`/`),!1)}else if(t)i=await zi(t,n,{name:r},o);else return!1;return c(),i},[e,t,o,c]),f=(0,Q.useCallback)(async(n,r,a=!1,s=o,l=o,u={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await ms(e,n,r,a,u);else if(t)i=await Ao(t,n,r,a,s,l,u);else return!1;return c(),i}),[e,t,o,c,i]),p=(0,Q.useCallback)(async n=>{let r;if(e)r=await Is(e,n);else if(t)r=await hi(t,n,o);else return null;return c(),r},[e,t,o,c]),m=(0,Q.useCallback)(async n=>{let r;if(e)r=await cs(e,n);else if(t)r=await Va(t,n,o);else return null;return c(),r},[e,t,o,c]),h=(0,Q.useCallback)(async(n,r,a=!1,s=o,l=o)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await bs(e,n,r,a);else if(t)i=await Ta(t,n,r,a,s,l);else return!1;return c(),i}),[e,t,o,c,i]),_=(0,Q.useCallback)(async(n,r)=>e?await ds(e,n,r):t?await zi(t,n,r,o):!1,[e,t,o]),v=(0,Q.useCallback)(async(n,r)=>{let i;if(e)i=await ts(e,n,r);else if(t)i=await Si(t,n,r,o);else return null;return c(),i},[e,t,o,c]),y=(0,Q.useCallback)(async(n,r)=>{let i;if(e)i=await Ts(e,n,r);else if(t)i=await mo(t,n,r,o);else return null;return c(),i},[e,t,o,c]),b=(0,Q.useCallback)(async e=>{if(!t)return!1;let n=await ci(t,e,t,o);return c(300),n},[t,o,c]),x=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;try{await Ea(t,e,n??t,o)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return c(300),!0},[t,o,c]),S=(0,Q.useCallback)(async e=>{if(!t)return!1;let n=await Jr(t,e,o);return c(),n},[t,o,c]),C=(0,Q.useCallback)(async e=>{if(!t)return!1;let n=await pa(t).catch(()=>[]),r=oo(e,n);return r?(await Eb(a,t,r.driver,r.address),c(300),!0):!1},[t,c,a]),w=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;let r=await pa(t).catch(()=>[]),i=ma(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await ca(t,i.driver,i.address,[a]),c(200),!0},[t,c]),T=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;let r=await pa(t).catch(()=>[]),i=ma(e,r);return!i||!i.key?!1:(await ea(t,i.driver,i.address,i.key,n),c(200),!0)},[t,c]),E=(0,Q.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await pa(t),r=po(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await Qi(t,r.driver,r.address,r.key),!0}finally{c(200)}}):!1,[t,c,i]),D=(0,Q.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await g(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-CSjPDp4d.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([29,3,4,10,11,13,12,14]));r({mode:e,path:n,workspaceId:t,treeName:o,onImported:()=>{kb(t,o),c()}})},[t,o,c]);return{onInsertPath:l,onRemovePath:u,onRenamePath:d,onMovePath:f,onCopyPath:h,onExportSubtree:t?e=>D(`export`,e):void 0,onImportSubtree:t&&o!==`backends`?e=>D(`import`,e):void 0,onUpdateNode:_,onMergeLayer:v,onSubtractLayer:y,onMergeDown:s?void 0:p,onSubtractDown:s?void 0:m,onLockLayer:t?b:void 0,onUnlockLayer:t?x:void 0,onDestroyLayer:t&&!s?S:void 0,onResyncBackend:t?C:void 0,onCreateBackendFolder:t?w:void 0,onRenameBackendFolder:t?T:void 0,onDeleteBackendFolder:t?E:void 0}}function Mb({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let u=gl(),d=jb({workspaceId:n,treeName:r}),f=r===`backends`,p=f?ma(i):null,[m,h]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{if(!f)return;let e=!1;return pa(n).then(t=>{e||h(t)}).catch(()=>{}),()=>{e=!0}},[n,f]);let g=f?po(i,m):null,_=i.split(`/`).filter(Boolean).pop()||i,[v,y]=(0,Q.useState)(void 0);(0,Q.useEffect)(()=>{let e=!1;return Ai(n).then(t=>{e||y(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||y(null)}),()=>{e=!0}},[n,r,i]);let b=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},x=(e,t,n,r=!1)=>(0,$.jsxs)(`button`,{type:`button`,className:J(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>b(n),children:[e,t]}),S=(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),C=e=>{let t=f?(()=>{let t=ep(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:np(i)};u(`/workspaces/${n}/settings/hooks?${tp(t).toString()}`)},w=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},T=pb(r,i);return T?(0,$.jsxs)(em,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[x((0,$.jsx)(nt,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),T.backend&&x((0,$.jsx)(ir,{className:`h-3 w-3`}),`Restore original paths`,()=>xb(n,i)),T.backend&&x((0,$.jsx)(nt,{className:`h-3 w-3`}),`Empty Trash`,()=>Cb(n,i),!0)]}):(0,$.jsxs)(em,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[x((0,$.jsx)(rt,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&x((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),S,f?p&&(0,$.jsxs)($.Fragment,{children:[x((0,$.jsx)(sn,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=w(`New folder name:`);e&&await d.onCreateBackendFolder?.(i,e)}),p.key&&x((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=w(`New folder name:`,_);e&&await d.onRenameBackendFolder?.(i,e)}),x((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create storage rule…`,()=>C(`store`))]}):(0,$.jsxs)($.Fragment,{children:[x((0,$.jsx)(sn,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=w(`New folder name:`);e&&await d.onInsertPath(`${i===`/`?``:i}/${e}`)}),x((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename`,async()=>{let e=w(`New name:`,_);e&&await d.onRenamePath(i,e)}),x((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create rule…`,()=>C(`store`)),x((0,$.jsx)(qt,{className:`w-3 h-3`}),`Create download rule…`,()=>C(`download`))]}),v!==void 0&&x(v?(0,$.jsx)(ee,{className:`w-3 h-3`}):(0,$.jsx)(Oe,{className:`w-3 h-3`}),v?`Unpin`:`Pin`,async()=>{v?await oa(n,v.id):await Yi(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),S,x((0,$.jsx)(A,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!f&&l&&c&&c.length>0&&x((0,$.jsx)(Ce,{className:`w-3 h-3`}),`Paste ${c.length} document(s)`,()=>l(i,c)),f?g&&(0,$.jsxs)($.Fragment,{children:[S,x((0,$.jsx)(nt,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${_}" and its contents from the backend?`)&&await d.onDeleteBackendFolder?.(i)},!0)]}):(0,$.jsxs)($.Fragment,{children:[S,x((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await d.onRemovePath(i,!0)},!0)]})]})}function Nb({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,Q.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,$.jsx)(Lp,{label:`Export Documents`,onClose:o,children:(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,$.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,$.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,$.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,$.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,$.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,$.jsxs)(Z,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,$.jsx)(A,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,$.jsx)(`textarea`,{className:`w-full min-h-24 flex-1 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,$.jsx)(`div`,{className:`mt-8 pt-4 border-t flex justify-end`,children:(0,$.jsx)(Z,{onClick:o,children:`Close`})})]})})}function Pb({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.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,Ip.createPortal)((0,$.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,$.jsx)(`div`,{className:`bg-background border rounded-(--panel-radius) 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,$.jsxs)(`div`,{className:`p-6`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data containing documents to import`})]}),(0,$.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,$.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,$.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,$.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,$.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,$.jsx)(Z,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,$.jsx)(Z,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function Fb({document:e}){let{replicating:t,label:n}=bo(e);return t?(0,$.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,$.jsx)(Yn,{className:`h-3 w-3 animate-spin`}),n]}):null}function Ib(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:lm(e.currentTarget,`inside`)}function Lb({documentId:e,onOpenActions:t,className:n}){return t?(0,$.jsx)(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),t(n.currentTarget,e)},className:`rounded-sm p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground ${n??``}`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,$.jsx)(Qt,{className:`h-4 w-4`})}):null}function Rb(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function zb({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Ep(),[c,l]=(0,Q.useState)(!1),{replicating:u}=bo(e),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=Yr(e),m=Vb(e),h=m||Ub(e),{blobUrl:g}=__(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),_=t=>{o?.(t,e.id)},v=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),y=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),b=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||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},x=e=>{e.shiftKey&&e.preventDefault()},S=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(jg,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>Rb(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring transition-opacity ${u?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:b,onMouseDown:x,...s,onContextMenu:S,draggable:!0,onDragStart:_,children:[(0,$.jsx)(Ng,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,$.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,$.jsx)(Ng,{className:`w-12`,children:g?(0,$.jsx)(`img`,{src:g,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,$.jsx)(Gm,{document:e,chip:!0})}),(0,$.jsx)(Ng,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),p.isExternal&&(0,$.jsx)(Ht,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,$.jsx)(Fb,{document:e})]}),p.subtitle&&(0,$.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,$.jsx)(Ng,{className:`hidden md:table-cell`,children:(0,$.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:p.schemaLabel})}),(0,$.jsx)(Ng,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,$.jsx)(Ng,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:y&&(0,$.jsx)(`span`,{className:`font-mono`,title:`${y.algo} checksum`,children:y.hash})}),(0,$.jsx)(Ng,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,$.jsx)(Ng,{className:`w-12 text-right`,children:(0,$.jsx)(Lb,{documentId:e.id,onOpenActions:a})})]}),(0,$.jsx)(Hy,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function Bb({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Ep(),[c,l]=(0,Q.useState)(!1),u=e.schema===`data/schema/tab`,{replicating:d}=bo(e),f=u?e.data.url:null,p=Yr(e),m=Vb(e),h=m||Ub(e),{blobUrl:g,loading:_}=__(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),v=t=>{o?.(t,e.id)},y=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),b=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),x=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||(u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},S=e=>{e.shiftKey&&e.preventDefault()},C=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>Rb(n,()=>u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${d?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${u&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:x,onMouseDown:S,...s,onContextMenu:C,draggable:!0,onDragStart:v,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[h&&(0,$.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:g?(0,$.jsx)(`img`,{src:g,alt:p.title,loading:`lazy`,className:`h-full w-full object-cover`}):_?(0,$.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,$.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,$.jsx)(Gm,{document:e})})}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,$.jsx)(Gm,{document:e,chip:!0}),(0,$.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:p.title,children:p.title}),p.isExternal&&(0,$.jsx)(Ht,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,$.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:p.schemaLabel}),(0,$.jsx)(Fb,{document:e})]}),p.subtitle&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:p.subtitle,children:p.subtitle}),p.preview&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:p.preview}),(0,$.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,$.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),b&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,$.jsx)(he,{className:`h-3 w-3`}),(0,$.jsx)(`span`,{className:`font-mono`,title:`${b.algo} checksum`,children:b.hash})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,$.jsx)(et,{className:`h-3 w-3`}),(0,$.jsx)(`span`,{title:`Created: ${y(e.createdAt)}`,children:y(e.createdAt)})]})]})]}),(0,$.jsx)(Lb,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,$.jsx)(Hy,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function Vb(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Hb(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function Ub(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Wb({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Uo(e,t),[a,o]=(0,Q.useState)(!1);return i||a?(0,$.jsx)($.Fragment,{children:n}):r?(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,$.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,$.jsx)(xe,{className:`h-3.5 w-3.5`})})]}):(0,$.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function Gb({document:e,workspaceId:t,markdown:n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(()=>typeof IntersectionObserver>`u`);(0,Q.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}=Fo(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,$.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,$.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,$.jsx)(E_,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,$.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,$.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,$.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,$.jsx)(Gm,{document:e,size:10,chip:!0}),i&&s&&(0,$.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function Kb({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let c=Ep(),[l,u]=(0,Q.useState)(!1),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=Vb(e),m=Hb(e),h=p||Ub(e),g=Yr(e),_=fi(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||wi(e)),v=e.schema===`data/schema/file`&&(_===`markdown`||_===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,y=!h&&e.schema!==`data/schema/file`&&!!(g.preview||g.subtitle),{replicating:b}=bo(e),{blobUrl:x,loading:S}=__(n??``,e.id,768,{enabled:h,blobFallback:p,version:e.checksumArray?.[0]??null}),C=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||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0))},w=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>Rb(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0),()=>r?.(e.id,!t,!0)),className:`group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-(--card-radius) border transition cursor-pointer outline-none hover:shadow-elevation-2 focus-visible:ring-2 focus-visible:ring-ring ${b?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:C,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...c,onContextMenu:w,draggable:!0,onDragStart:t=>s?.(t,e.id),title:g.title,children:[(0,$.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,$.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${h&&x||y||v&&n||m&&n?``:`aspect-square`}`,children:[h&&S&&(0,$.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),h&&x?(0,$.jsx)(`img`,{src:x,alt:g.title,loading:`lazy`,className:`block h-auto w-full`}):m&&n?(0,$.jsx)(Wb,{workspaceId:n,documentId:e.id,fallback:(0,$.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,$.jsx)(Gm,{document:e,size:10,chip:!0})})}):v&&n?(0,$.jsx)(Gb,{document:e,workspaceId:n,markdown:_===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):y?(0,$.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,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(Gm,{document:e}),(0,$.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:g.schemaLabel})]}),(0,$.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:g.title}),g.subtitle&&(0,$.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:g.subtitle}),(0,$.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:g.preview})]}):(0,$.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,$.jsx)(Gm,{document:e,size:10,chip:!0})}),(0,$.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,$.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Open to the side`,children:(0,$.jsx)(Ze,{className:`h-3.5 w-3.5`})}),o&&(0,$.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(t.currentTarget,e.id)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,$.jsx)(Qt,{className:`h-3.5 w-3.5`})})]})]}),!y&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,$.jsx)(`span`,{className:`truncate text-xs font-medium`,title:g.title,children:g.title}),g.isExternal&&(0,$.jsx)(Ht,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,$.jsx)(Hy,{document:e,isOpen:l,onClose:()=>u(!1),workspaceId:n})]})}function qb(e,t,n,r,i){let[a,o]=(0,Q.useState)(!1),s=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:a,onDragOver:e=>{!t||!s(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,a||o(!0))},onDragLeave:()=>o(!1),onDrop:async a=>{if(o(!1),!t||!s(a))return;a.preventDefault(),a.stopPropagation();let c=null;try{c=JSON.parse(a.dataTransfer.getData(`application/json`))}catch{c=null}if(!(c?.type!==`document`||!Array.isArray(c.documentIds)||c.documentIds.length===0)&&!_g(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function Jb(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function Yb({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,$.jsx)(sr,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,$.jsx)($e,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var Xb=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function Zb({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=qb(e,r,i,a,o);return(0,$.jsxs)(`button`,{type:`button`,title:Xb(e),onClick:()=>t?.(e.path),onContextMenu:t=>Jb(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.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 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,$.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,$.jsx)(Yb,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,$.jsx)(sr,{className:`hidden h-4 w-4 group-hover:block`}):(0,$.jsx)(rt,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,$.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,$.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function Qb({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=qb(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,$.jsxs)(`button`,{type:`button`,title:Xb(e),onClick:()=>t?.(e.path),onContextMenu:t=>Jb(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-(--card-radius) border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,$.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,$.jsx)(sr,{className:`h-10 w-10`,strokeWidth:1.5}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)($e,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,$.jsx)(rt,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c})]})}),(0,$.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,$.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function $b({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,$.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,$.jsx)(Qb,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function ex({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,$.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,$.jsx)(Zb,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function tx({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=qb(e,r,i,a,o);return(0,$.jsxs)(jg,{"data-selection-ignore":``,className:`cursor-pointer ${s.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:t=>Jb(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:Xb(e),children:[(0,$.jsx)(Ng,{className:`w-10`}),(0,$.jsx)(Ng,{className:`w-12`,children:(0,$.jsx)(Yb,{folder:e})}),(0,$.jsx)(Ng,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,$.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,$.jsx)(Ng,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,$.jsx)(Ng,{className:`hidden lg:table-cell`}),(0,$.jsx)(Ng,{className:`hidden lg:table-cell`}),(0,$.jsx)(Ng,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,$.jsx)(Ng,{className:`w-12 md:w-auto`})]})}function nx({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,$.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,$.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,$.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,$.jsx)(hr,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,$.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,$.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function rx({externalSearchQuery:e,toolbarActions:t,documents:n,isLoading:r,contextPath:i,treeName:a,workspaceId:o,totalCount:s,onRemoveDocument:c,onDeleteDocument:l,onDestroyDocument:u,onRemoveDocuments:d,onDeleteDocuments:f,onDestroyDocuments:p,onCopyDocuments:m,onCutDocuments:h,onPasteDocuments:g,onImportDocuments:v,onSelectionChange:y,pastedDocumentIds:b,viewMode:x=`card`,allowViewToggle:S=!1,activeContextUrl:C,currentContextUrl:w,currentPage:T=1,pageSize:D=50,onPageChange:O,onPageSizeChange:k,onPurgeDocuments:j,disablePurgeDocuments:M=!1,backendSearchQueries:N=[],onBackendSearch:P,onRemoveBackendQuery:F,serverSort:I,onServerSortChange:L,scope:R=`path`,onScopeChange:z,canSaveChanges:ee=!1,isSavingChanges:te=!1,onSaveChanges:ne,linkTree:ie,folders:ae,onOpenFolder:oe}){let[V,H]=(0,Q.useState)(()=>{if(!S)return x;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return x}),U=S?V:x,se=(0,Q.useCallback)(e=>{H(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[W,ce]=(0,Q.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),le=(0,Q.useCallback)(()=>{ce(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[ue,de]=(0,Q.useState)(new Set),fe=(0,Q.useCallback)(e=>{de(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[pe,me]=(0,Q.useState)(new Set),[he,ve]=(0,Q.useState)(null),[K,q]=(0,Q.useState)(null),ye=es(),be=!!(ye&&o),xe=(0,Q.useCallback)((e,t=!1)=>{if(!ye||!o)return;let r=e.map(e=>n.find(t=>t.id===e)).filter(e=>!!e);r.length!==0&&ye.openAddRelated({workspaceName:o,documents:r},t)},[ye,o,n]),[Se,we]=(0,Q.useState)(!1),[Te,Ee]=(0,Q.useState)(null),[De,Oe]=(0,Q.useState)(!1),[ke,Ae]=(0,Q.useState)(null),[je,Me]=(0,Q.useState)(!1),Ne=(0,Q.useRef)(!1),Ie=(0,Q.useRef)(!1),Le=a===`backends`&&R===`path`?ep(i):null;(0,Q.useEffect)(()=>()=>{Ne.current=!0},[]);let[Re,ze]=(0,Q.useState)(!1),[Ve,He]=(0,Q.useState)(null),[Ue,We]=(0,Q.useState)(!1),[Ge,Ke]=(0,Q.useState)(null),qe=jo()==null&&!!o,[Je,Xe]=(0,Q.useState)(null),[$e,et]=(0,Q.useState)(null),tt=!!(ie&&g),rt=!!o,{showSuccessToast:it,showErrorToast:at}=Wr(),{showProgress:ot}=Vr(),st=Eg(),ct=o?e=>st.open(e,o):void 0,lt=R===`workspace`,ut=lt?void 0:c,dt=lt?void 0:d,[ft,pt]=(0,Q.useState)(!1),[mt,ht]=(0,Q.useState)(!1),[gt,_t]=(0,Q.useState)(``),vt=e??gt,yt=e!==void 0,[bt,xt]=(0,Q.useState)(!1),Ct=N.length>0,wt=(0,Q.useRef)(null),Tt=(0,Q.useCallback)(()=>{_t(``),wt.current&&(wt.current.value=``)},[]);(0,Q.useEffect)(()=>{if(!S||window.matchMedia(`(max-width: 767px)`).matches)return;let e=wt.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[S]);let Dt=JSON.stringify([o,a,i]),[Ot,kt]=(0,Q.useState)(Dt);Dt!==Ot&&(kt(Dt),me(new Set),Ee(null),q(null),ve(null)),(0,Q.useEffect)(()=>{y?.(Array.from(pe))},[pe,y]);let At=(0,Q.useCallback)(()=>{if(!P)return;let e=vt.trim();e&&(P(e),Tt())},[P,vt,Tt]),jt=(0,Q.useCallback)(()=>{Tt(),F&&N.length>0&&F(-1)},[F,N.length,Tt]),Mt=(0,Q.useCallback)((e,t)=>{let n;pe.has(t)&&pe.size>1?n=Array.from(pe):(n=[t],me(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:R===`path`?i:void 0,sourceTreeName:a,sourceWorkspaceId:o};e.dataTransfer.setData(`application/json`,JSON.stringify(r)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[pe,i,a,o,R]),Nt=(0,Q.useCallback)(async e=>{if(!g)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let n=null;try{n=JSON.parse(t)}catch{return}n?.type!==`document`||!Array.isArray(n.documentIds)||n.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),xt(!1),!_g(n,o,a,i)&&(await g(i,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),me(new Set)))},[i,a,o,g]),Pt=(0,Q.useCallback)(e=>{g&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,xt(!0))},[g]),Ft=(0,Q.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||xt(!1)},[]),It=(0,Q.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}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),Lt=(0,Q.useMemo)(()=>n.length===0?null:new Qo(n,It),[n,It]),Rt=(0,Q.useDeferredValue)(vt),zt=(0,Q.useMemo)(()=>{if(!Rt.trim())return n;let{text:e,ids:t,invalid:r}=Cp(Rt);if(r)return[];let i=e&&Lt?Lt.search(e).map(e=>e.item):n;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[n,Rt,Lt]),Bt=(0,Q.useMemo)(()=>{if(!ae||ae.length===0||Rt.trim())return[];let e=I?.order===`desc`?-1:1;return[...ae].sort((t,n)=>Number(!!n.isParent)-Number(!!t.isParent)||(t.label||t.name).localeCompare(n.label||n.name,void 0,{numeric:!0,sensitivity:`base`})*e)},[ae,Rt,I?.order]),Vt=Bt.length>0,[Ut,Wt]=(0,Q.useState)(null),Gt=(0,Q.useMemo)(()=>o&&a&&oe?(e,t)=>Wt({x:t.clientX,y:t.clientY,path:e}):void 0,[o,a,oe]),Jt={folders:Bt,onOpen:oe,onMenu:Gt,onPasteDocuments:g,contextPath:i,treeName:a,workspaceId:o},{sorted:Yt,sort:Xt,toggleSort:Qt}=Ig(zt,(0,Q.useMemo)(()=>({title:e=>Yr(e).title?.toLowerCase()??``,schema:e=>Yr(e).schemaLabel??``,type:Hi,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),$t=(0,Q.useCallback)(e=>rb(e,I?.sortBy),[I?.sortBy]),en=(0,Q.useMemo)(()=>fb(zt,$t,I?.order===`asc`?`asc`:`desc`),[zt,$t,I?.order]),tn=W&&!ri(I?.sortBy)&&en.length>1,nn=(0,Q.useCallback)((e,t)=>{me(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),rn=(0,Q.useMemo)(()=>(U===`table`?Yt:tn?en.filter(e=>!ue.has(e.key)).flatMap(e=>e.items):zt).map(e=>e.id),[U,Yt,tn,en,ue,zt]),an=(0,Q.useRef)(null),on=JSON.stringify([o,i,a,T]),cn=(0,Q.useCallback)(e=>{an.current=null,me(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),ln=(0,Q.useCallback)((e,t,n,r=!1)=>{let i=an.current,a=i?.scope===on&&rn.includes(i.id)?i.id:null;(!r||a===null)&&(an.current={scope:on,id:e}),me(i=>{if(r)return Dp(rn,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[on,rn]),un=(0,Q.useCallback)((e,t)=>{let n;pe.has(e)?n=Array.from(pe):(n=[e],me(new Set([e]))),ve({anchor:t,ids:n})},[pe]),fn=(0,Q.useCallback)((e,t)=>{un(t,lm(e))},[un]),pn=(0,Q.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),un(t,Ib(e)))},[un]),mn=(0,Q.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){we(!0);try{for(let n of t)await go(o,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;it(`Created ${n} relation${n===1?``:`s`}`),Rg(),q(null)}catch(e){at(e instanceof Error?e.message:`Failed to create relations`)}finally{we(!1)}}},[o,it,at]),hn=(0,Q.useCallback)(async(e,t,n)=>{if(g){for(let r of e)await g(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});me(new Set)}},[g]),gn=(0,Q.useCallback)(async(e,t,r)=>{if(!o||!Te||Ie.current)return;Ie.current=!0,Ne.current=!1,Me(!1),Oe(!0);let i=ot({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${Te.ids.length} document(s) · ${e.join(`, `)}`});try{let a=n=>Wa(o,n,{to:e,mode:t,keepDocument:r.keepDocument,...t===`delete`&&Le?{deleteFrom:{backend:Le.backend,folder:Le.rel}}:{},folder:r.folder,filename:r.filename,onConflict:r.onConflict}),s=t===`delete`?await Rf(Te.ids,a,{shouldStop:()=>Ne.current,onProgress:(t,n)=>{Ae({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(Te.ids),pending:[]},c=s.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,l=s.successful.filter(e=>e.transfers?.some(e=>e.state===`pending`)).length,u=s.successful.length-c-l,d=s.failed.length,f=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,p=e.join(`, `),m=[c?`${c} already there`:null,l?`${l} queued for backend sync`:null,d?`${d} skipped`:null,s.pending.length?`${s.pending.length} not processed`:null].filter(Boolean).join(` · `),h=`${f} ${p}: ${u} document${u===1?``:`s`}${m?` · ${m}`:``}`;d>0?(i.fail({title:`Operation incomplete`,description:`${h}. ${wp(s.failed,new Map(n.map(e=>[e.id,Yr(e).title])))}`,variant:`destructive`}),console.warn(`Backend transfer skipped documents:`,s.failed)):i.done({title:s.pending.length?`Operation stopped`:l?`Transfer queued`:`Operation complete`,description:h}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`));let g=[...s.failed.map(e=>e.id),...s.pending];Ee(g.length?{ids:g,mode:t}:null),me(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{Ie.current=!1,Oe(!1),Ae(null)}},[o,Te,Le,n,ot]),yn=(0,Q.useCallback)(()=>{pe.size===zt.length?me(new Set):me(new Set(zt.map(e=>e.id)))},[pe.size,zt]),bn=(0,Q.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{let t=window.document.createElement(`textarea`);t.value=e,window.document.body.appendChild(t),t.select(),window.document.execCommand(`copy`),window.document.body.removeChild(t)}},[]),xn=e=>{if(e.length===0)return[];let t=e.length,r=t>1?` (${t})`:``,i=t===1?n.find(t=>t.id===e[0]):void 0,o=()=>me(new Set),s=e.some(e=>(n.find(t=>t.id===e)?.locations?.length??0)>0),c=[],d=e=>{e&&c.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;d({id:`view`,group:`open`,label:`View details`,icon:Xn,run:()=>et({document:i})}),d(sy(i)&&qe&&{id:`edit`,group:`open`,label:`Edit`,icon:_e,run:()=>et({document:i,edit:!0})}),d(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:Ht,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),d(ct&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:Ze,run:()=>ct(i)})}return d(m&&{id:`copy`,group:`clipboard`,label:`Copy${r}`,icon:A,shortcut:`Mod+C`,run:()=>m(e)}),d(h&&{id:`cut`,group:`clipboard`,label:`Cut${r}`,icon:Et,shortcut:`Mod+X`,run:()=>h(e)}),d(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:_n,run:()=>bn(String(i.id))}),d(i&&qe&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:Dn,run:()=>Xe(i)}),d(tt&&{id:`link-to`,group:`organize`,label:`Link to…${r}`,icon:Zt,run:()=>q(e)}),d(be&&{id:`add-related`,group:`organize`,label:`Add related document…${r}`,icon:sn,run:t=>xe(e,t?.shiftKey)}),d(qe&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${r}`,icon:_e,run:()=>Ke(e)}),d(qe&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:A,run:t=>{We(!!t?.shiftKey),He(e)}}),d({id:`export`,group:`organize`,label:`Export…${r}`,icon:qt,run:()=>pt(!0)}),d(a!==`backends`&&(ut||dt)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${r}`,icon:re,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&ut?ut(e[0]):dt?.(e),o()}}),d(a!==`backends`&&(l||f)&&{id:`delete`,group:`remove`,label:`Delete from index${r}`,icon:nt,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&l?l(e[0]):f?.(e),o()}}),s&&rt?(d({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${r}`,icon:Pe,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Ee({ids:e,mode:`copy`})}),d({id:`backend-move`,group:`backends`,label:`Move to backend…${r}`,icon:dn,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Ee({ids:e,mode:`move`})}),d({id:`backend-delete`,group:`backends`,label:`Delete from backend…${r}`,icon:nt,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Ee({ids:e,mode:`delete`})})):s&&(u||p)&&d({id:`destroy`,group:`backends`,label:`Delete from backend(s)${r}`,icon:nt,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&u?u(e[0]):p?.(e),o()}}),c},Sn=()=>{let e=[],t=t=>{t&&e.push(t)},r=b??[];return t(g&&r.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${r.length})`,icon:Ce,shortcut:`Mod+V`,run:async()=>{try{await g(i,r)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(zt.length>0&&{id:`select-all`,group:`select`,label:vt?`Select all matches (${zt.length})`:`Select all on this page`,icon:St,shortcut:`Mod+A`,run:()=>me(new Set(zt.map(e=>e.id)))}),t(pe.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:zn,run:()=>me(new Set)}),t(g&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:En,hint:`Browse and add existing documents to this folder`,run:()=>ze(!0)}),t(v&&{id:`import`,group:`add`,label:`Import…`,icon:Qe,run:()=>ht(!0)}),t(n.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:qt,run:()=>{me(new Set),pt(!0)}}),t(j&&s>0&&{id:`purge`,group:`purge`,label:`Purge all (${s})`,icon:nt,destructive:!0,disabled:M||!!vt,hint:vt?`Purge is disabled while local search is active`:M?`Purge requires loaded server results with no browser-only or live selection`:`Delete all documents matching the current server-side filters across all pages`,run:j}),e},Cn=!!(L&&I&&o),wn=he?he.ids?xn(he.ids):Sn():[],Tn=he?.ids?.length===1?n.find(e=>e.id===he.ids[0]):void 0,On=Tn?(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,$.jsx)(Gm,{document:Tn,chip:!0}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Yr(Tn).title}),(0,$.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Tn.id,` · `,Tn.schema]})]})]}):(0,$.jsx)(`div`,{className:`truncate text-base font-semibold`,children:he?.ids?`${he.ids.length} documents`:`This folder`}),kn=e=>{ve({anchor:lm(e.currentTarget),ids:pe.size>0?Array.from(pe):null})},An=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),me(new Set),ve({anchor:Ib(e),ids:null}))},jn=e=>{if(e.defaultPrevented||am(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(sm(e)){e.preventDefault(),t?un(Number(t.dataset.documentId),lm(t,`inside`)):ve({anchor:lm(e.target,`inside`),ids:pe.size>0?Array.from(pe):null});return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=Array.from(e.currentTarget.querySelectorAll(`[data-document-id]`));if(n.length===0)return;let r=t?n.indexOf(t):-1,i=n[e.key===`ArrowDown`?Math.min(r+1,n.length-1):Math.max(r-1,0)];e.preventDefault(),i.focus({preventScroll:!0}),i.scrollIntoView({block:`nearest`}),e.shiftKey&&ln(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&pe.size>0){e.preventDefault(),me(new Set);return}om(e,[...xn(Array.from(pe)),...Sn()])},Mn=(0,Q.useCallback)(async e=>{if(!v)return!1;try{return await v(e,i)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[v,i]),Nn=e=>tn?en.map(t=>{let n=ue.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!pe.has(t),0);return(0,$.jsxs)(`section`,{className:`group mb-4`,children:[(0,$.jsx)(nx,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>fe(t.key),onSelectAll:e=>nn(r,e)}),!n&&e(t.items)]},t.key)}):e(zt);return r?(0,$.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})}):(0,$.jsxs)(`div`,{tabIndex:-1,onKeyDown:jn,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${bt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:Pt,onDragLeave:Ft,onDrop:Nt,children:[(0,$.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,$.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,$.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:vt?`${zt.length} of ${n.length}`:`${s.toLocaleString()} document${s===1?``:`s`}`})]}),(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,$.jsxs)(`p`,{hidden:yt,className:`min-w-0 truncate`,children:[`Context: `,(0,$.jsx)(`span`,{className:`font-mono`,children:i}),C&&w&&C!==w&&(0,$.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,$.jsxs)(`p`,{className:`shrink-0`,children:[pe.size>0&&(0,$.jsxs)(`span`,{className:`text-info`,children:[pe.size,` selected`]}),pe.size>0&&(vt||s>D)&&(0,$.jsx)(`span`,{className:`mx-1`,children:`·`}),vt?`on this page`:s>D?`Showing ${Math.min((T-1)*D+1,s)}–${Math.min(T*D,s)}`:null]})]})]}),!yt&&(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[!yt&&z&&(0,$.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>z(`path`),className:`px-2.5 py-2 transition-colors ${R===`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,$.jsxs)(`button`,{type:`button`,onClick:()=>z(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${R===`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,$.jsx)(Ye,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!yt&&(0,$.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,$.jsx)(tr,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,$.jsx)(`input`,{ref:wt,type:`text`,placeholder:P?Ct?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,title:`Search text or an exact document ID, e.g. @id:101140. Press Enter to search the server.`,defaultValue:``,onChange:e=>_t(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`&&P&&(e.preventDefault(),At())},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`}),(vt||Ct)&&(0,$.jsx)(`button`,{onClick:jt,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,$.jsx)(G,{className:`h-4 w-4`})})]}),!yt&&P&&vt.trim()&&!N.includes(vt.trim())&&(0,$.jsxs)(Z,{size:`sm`,variant:`default`,onClick:At,className:`shrink-0`,title:Ct?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,$.jsx)(tr,{className:`h-3.5 w-3.5 mr-1`}),Ct?`Refine`:`Search server`]})]}),!yt&&Ct&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),N.map((e,t)=>(0,$.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,$.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,$.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,$.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),F&&(0,$.jsx)(`button`,{onClick:()=>F(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),F&&N.length>1&&(0,$.jsx)(`button`,{onClick:()=>F(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,$.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,$.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,$.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[S&&(0,$.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,_,`Table view`],[`tile`,$n,`Tile view`],[`card`,Kt,`Card view`]].map(([e,t,n])=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>se(e),title:n,"aria-pressed":U===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${U===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,$.jsx)(t,{className:`h-4 w-4`})},e))}),S&&U!==`table`&&!ri(I?.sortBy)&&(0,$.jsx)(`button`,{type:`button`,onClick:le,title:W?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":W,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${W?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,$.jsx)(B,{className:`h-4 w-4`})})]}),O&&s>0&&(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,$.jsxs)(`select`,{value:D,onChange:e=>k?.(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`,"aria-label":`Documents per page`,children:[(0,$.jsx)(`option`,{value:25,children:`25`}),(0,$.jsx)(`option`,{value:50,children:`50`}),(0,$.jsx)(`option`,{value:100,children:`100`}),(0,$.jsx)(`option`,{value:200,children:`200`})]}),(0,$.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,$.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[Cn&&(0,$.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,$.jsx)(nb,{workspaceId:o,value:I,onChange:L})]}),(0,$.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(n.length>0||v||g)&&(0,$.jsxs)(`div`,{className:`contents`,children:[(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:kn,"aria-haspopup":`menu`,"aria-label":pe.size>0?`Actions (${pe.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${rm(`Shift+F10`)} or right-click)`,children:[(0,$.jsx)(vn,{className:`h-4 w-4`}),(0,$.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,pe.size>0?` (${pe.size} selected)`:``]})]}),pe.size>0&&(0,$.jsxs)(Z,{variant:`ghost`,size:`sm`,onClick:()=>me(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,$.jsx)(G,{className:`h-3.5 w-3.5`}),(0,$.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),b&&b.length>0&&g&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>g(i,b),className:`flex items-center gap-1.5`,title:`Paste into this folder (${rm(`Mod+V`)})`,children:[(0,$.jsx)(Ce,{className:`h-4 w-4`}),`Paste (`,b.length,`)`]})]}),ee&&ne&&(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:ne,disabled:te,className:`w-control-sm shrink-0 px-0 touch-target`,"aria-label":te?`Saving filters`:`Save current query and filters`,title:`Save current query and filters`,children:(0,$.jsx)(Be,{className:`h-3.5 w-3.5`})}),t]})]})]})}),O&&s>D&&(0,$.jsxs)(`div`,{className:`document-pagination mt-3 flex min-w-0 flex-wrap items-center justify-end gap-2 border-t pt-3 max-sm:gap-0.5`,children:[(0,$.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((T-1)*D+1,s),` - `,Math.min(T*D,s),` of `,s]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>O(1),disabled:T===1,className:`p-1 touch-target`,children:(0,$.jsx)(Fe,{className:`h-4 w-4`})}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>O(T-1),disabled:T===1,className:`p-1 touch-target`,children:(0,$.jsx)(E,{className:`h-4 w-4`})}),(0,$.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,$.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),T,(0,$.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,$.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(s/D)]}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>O(T+1),disabled:T>=Math.ceil(s/D),className:`p-1 touch-target`,children:(0,$.jsx)(hr,{className:`h-4 w-4`})}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>O(Math.ceil(s/D)),disabled:T>=Math.ceil(s/D),className:`p-1 touch-target`,children:(0,$.jsx)(ge,{className:`h-4 w-4`})})]})]})]}),(0,$.jsx)($h,{scope:JSON.stringify([on,U,rn]),selected:pe,onSelectionChange:cn,onContextMenu:An,children:zt.length===0&&!Vt?(0,$.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(Rn,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:vt?`No documents match your search`:`No documents found in this context`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:vt?(0,$.jsxs)($.Fragment,{children:[`Search: `,(0,$.jsxs)(`span`,{className:`font-mono`,children:[`"`,vt,`"`]})]}):(0,$.jsxs)($.Fragment,{children:[`Path: `,(0,$.jsx)(`span`,{className:`font-mono`,children:i})]})}),!yt&&vt&&(0,$.jsx)(`button`,{onClick:Tt,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!vt&&b&&b.length>0&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,rm(`Mod+V`),` to paste `,b.length,` document(s)`]})]})}):U===`tile`?(0,$.jsxs)(`div`,{children:[(0,$.jsx)($b,{...Jt}),zt.length===0&&(0,$.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Nn(e=>(0,$.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,$.jsx)(Kb,{document:e,isSelected:pe.has(e.id),workspaceId:o,onSelect:ln,onOpenToSide:ct,onRightClick:pn,onOpenActions:fn,onDragStart:Mt},e.id))}))]}):U===`table`?(0,$.jsx)(`div`,{children:(0,$.jsxs)(Dg,{children:[(0,$.jsx)(Og,{children:(0,$.jsxs)(jg,{children:[(0,$.jsx)(Mg,{className:`w-10`,children:(0,$.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:zt.length>0&&pe.size===zt.length,ref:e=>{e&&(e.indeterminate=pe.size>0&&pe.size<zt.length)},onChange:yn,title:`Select all on this page`})}),(0,$.jsx)(Fg,{label:(0,$.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:Xt,onSort:Qt,className:`w-12`}),(0,$.jsx)(Fg,{label:`Title`,sortKey:`title`,sort:Xt,onSort:Qt,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,$.jsx)(Fg,{label:`Schema`,sortKey:`schema`,sort:Xt,onSort:Qt,className:`hidden md:table-cell`}),(0,$.jsx)(Fg,{label:`ID`,sortKey:`id`,sort:Xt,onSort:Qt,className:`hidden lg:table-cell`}),(0,$.jsx)(Mg,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,$.jsx)(Fg,{label:`Created`,sortKey:`created`,sort:Xt,onSort:Qt,className:`hidden sm:table-cell`}),(0,$.jsx)(Mg,{className:`w-12 md:w-auto`,children:(0,$.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,$.jsxs)(kg,{children:[Bt.map(e=>(0,$.jsx)(tx,{folder:e,onOpen:oe,onMenu:Gt,onPasteDocuments:g,contextPath:i,treeName:a,workspaceId:o},e.path)),Yt.map(e=>(0,$.jsx)(zb,{document:e,isSelected:pe.has(e.id),workspaceId:o,onSelect:ln,onOpenToSide:ct,onRightClick:pn,onOpenActions:fn,onDragStart:Mt},e.id))]})]})}):(0,$.jsxs)(`div`,{children:[(0,$.jsx)(ex,{...Jt}),zt.length===0&&(0,$.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Nn(e=>(0,$.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,$.jsx)(`div`,{children:(0,$.jsx)(Bb,{document:e,isSelected:pe.has(e.id),workspaceId:o,onSelect:ln,onOpenToSide:ct,onRightClick:pn,onOpenActions:fn,onDragStart:Mt})},e.id))}))]})}),he&&(0,$.jsx)(mm,{anchor:he.anchor,items:wn,onClose:()=>ve(null),label:he.ids?`Document actions`:`Folder actions`,header:On}),(0,$.jsx)(Nb,{isOpen:ft,onClose:()=>pt(!1),documents:n,selectedDocuments:pe}),(0,$.jsx)(Pb,{isOpen:mt,onClose:()=>ht(!1),onImport:Mn}),Ve&&o&&(0,$.jsx)(tg,{modal:Ue,workspaceId:o,ids:Ve,onClose:()=>He(null)}),K&&ie&&(0,$.jsx)(Lp,{label:`Link to`,onClose:()=>q(null),children:(0,$.jsx)(ih,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:K.length,fixedWorkspaceName:o,tabs:[`context`,`directory`,`relations`],saving:Se,relationExcludeIds:new Set(K),onConfirm:(e,t)=>hn(e,K,t),onConfirmRelation:e=>mn(e,K),onClose:()=>q(null)})}),Te&&o&&(0,Ip.createPortal)((0,$.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,$.jsx)(Sg,{workspaceId:o,documentCount:Te.ids.length,initialMode:Te.mode,defaultFilename:Te.ids.length===1?wi(n.find(e=>e.id===Te.ids[0])??{}):``,saving:De,progress:ke,stopping:je,onStop:()=>{Ne.current=!0,Me(!0)},deleteFrom:Le?{backend:Le.backend,folder:Le.rel}:void 0,onConfirm:gn,onClose:()=>{De||Ee(null)}})}),window.document.body),Re&&g&&(0,Ip.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>ze(!1),"aria-hidden":!0}),(0,$.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,$.jsx)(Cg,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:o,onConfirm:async e=>{await g(i,e),ze(!1)},onClose:()=>ze(!1)})})]}),window.document.body),Je&&o&&(0,$.jsx)(qh,{workspaceId:o,document:Je,onClose:()=>Xe(null)},`${o}:${Je.id}`),Ge&&o&&(0,$.jsx)(hg,{workspaceId:o,documentIds:Ge,onClose:()=>Ke(null)}),(0,$.jsx)(Hy,{document:$e?.document??null,isOpen:!!$e,onClose:()=>et(null),workspaceId:o,initialEdit:$e?.edit}),Ut&&o&&a&&oe&&(0,$.jsx)(Mb,{x:Ut.x,y:Ut.y,workspaceName:o,treeName:a,path:Ut.path,onClose:()=>Wt(null),onOpen:oe,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:a,path:e}})),pastedDocumentIds:b,onPasteDocuments:g?(e,t)=>g(e,t):void 0})]})}function ix(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,Q.useState)(e.canvasQueries??[]),a=(0,Q.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,Q.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,Q.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,Q.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,Q.useCallback)(()=>o([]),[o])}}function ax({config:e,canvas:t}){let n=typeof e.pageSize==`number`?e.pageSize:50,r=e.viewMode===`card`||e.viewMode===`tile`||e.viewMode===`table`?e.viewMode:`table`,[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(1),[u,d]=(0,Q.useState)(!0),f=t.canvasSort??Qy,{queries:p,runSearch:m,removeQuery:h}=ix(t,()=>l(1));(0,Q.useEffect)(()=>{let e=!1;return(async()=>{d(!0);try{let r=await t.fetchDocuments({limit:n,page:c,sortBy:f.sortBy,order:f.order,queries:p.length?p:void 0});if(e)return;a(r.payload||[]),s(r.totalCount||r.count||0)}catch{e||(a([]),s(0))}finally{e||d(!1)}})(),()=>{e=!0}},[t,n,c,f.sortBy,f.order,p]);let g=(0,Q.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,$.jsx)(nb,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,$.jsx)(rx,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,serverSort:f,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}Ff({type:`documents-table`,name:`Documents`,icon:_,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:ax});function ox({config:e,setConfig:t,canvas:n}){let[r,i]=(0,Q.useState)(()=>new Date),a=e.format!==`24`;return(0,Q.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,$.jsx)(`div`,{className:`text-3xl font-semibold tabular-nums`,children:r.toLocaleTimeString(void 0,{hour12:a,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>t({...e,format:a?`24`:`12`}),className:`mt-1 px-2 py-0.5 text-[10px] border rounded-md text-muted-foreground hover:bg-accent`,children:a?`12h`:`24h`})]})}Ff({type:`clock`,name:`Clock`,icon:N,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:ox});var sx=450,cx=10;function lx(e,t){let{open:n}=py(),r=(0,Q.useRef)(null),i=(0,Q.useRef)(null),a=(0,Q.useRef)(!1),o=()=>{e&&n(e,t)},s=()=>{r.current&&=(clearTimeout(r.current),null)};return{activationProps:{role:`button`,tabIndex:0,onClick:()=>{if(a.current){a.current=!1;return}o()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},onContextMenu:e=>{e.preventDefault(),o()},onPointerDown:e=>{e.pointerType===`touch`&&(i.current={x:e.clientX,y:e.clientY},a.current=!1,s(),r.current=setTimeout(()=>{a.current=!0,o()},sx))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>cx&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function ux({doc:e,workspaceId:t}){let n=Yr(e),{activationProps:r}=lx(e,t);return(0,$.jsxs)(`li`,{...r,title:`Open details`,className:`canvas-no-drag cursor-pointer py-1.5 min-w-0 rounded px-1 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,$.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,$.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function dx({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!1;return(async()=>{o(!0);try{let r=await t.fetchDocuments({limit:n});if(e)return;i(r.payload||[]),c(null)}catch(t){if(e)return;c(t instanceof Error?t.message:`Failed to load documents`),i([])}finally{e||o(!1)}})(),()=>{e=!0}},[t,n]),a?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,$.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,$.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,$.jsx)(ux,{doc:e,workspaceId:t.workspaceId},e.id))})}Ff({type:`recent-documents`,name:`Recent documents`,icon:xt,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:dx});function fx({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,$.jsx)(`textarea`,{value:r,readOnly:n.readOnly,onChange:n=>t({...e,text:n.target.value}),placeholder:n.readOnly?``:`Jot something down…`,className:`canvas-no-drag w-full h-full resize-none bg-transparent text-sm leading-6 outline-none`})}Ff({type:`note`,name:`Note`,icon:Kn,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:fx});var px=`data/schema/file`,mx=`data/schema/drawing`;function hx(e){return(e.schema===px||e.schema===mx)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function gx(e){return e.schema===px&&String(e.metadata?.contentType||``).startsWith(`video/`)}var _x=`data/mime/image`;function vx(e,t,n=!1){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(0),[s,c]=(0,Q.useState)(1),[l,u]=(0,Q.useState)(!0),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=ix(e,()=>c(1)),y=e.canvasSort??Qy;(0,Q.useEffect)(()=>{let r=!1,a=async()=>{u(!0),f(null);try{let a=await e.fetchDocuments({limit:t,page:s,queries:h.length?h:void 0,sortBy:y.sortBy,order:y.order,...n?{anyOf:[_x,`data/mime/video`]}:{allOf:[_x]}});if(r)return;i((a.payload||[]).filter(e=>hx(e)||n&&gx(e))),o(a.totalCount||a.count||0)}catch(e){if(r)return;i([]),o(0),f(e instanceof Error?e.message:`Failed to load images`)}finally{r||u(!1)}};return a(),window.addEventListener(`workspace:documents:refresh`,a),()=>{r=!0,window.removeEventListener(`workspace:documents:refresh`,a)}},[e,t,s,h,y.sortBy,y.order,n]);let b=(0,Q.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,Q.useCallback)(()=>{m(``),v()},[v]),S=(0,Q.useCallback)(e=>{_(e)},[_]),C=(0,Q.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,Q.useMemo)(()=>Math.max(1,Math.ceil(a/t)),[a,t]),input:p,setInput:m,submit:b,clearSearch:x,removeQuery:S,activeQueries:h,sort:y,setSort:C}}function yx({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=__(e,t.id,512,{blobFallback:!gx(t),version:t.checksumArray?.[0]??null}),c=wi(t)||`image-${t.id}`,l=Ra(t),u=l!==``&&i!==`off`;return(0,$.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-(--card-radius) border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,$.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!gx(t)&&(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,$.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-normal group-hover:scale-105`}),gx(t)&&(0,$.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,$.jsx)(xe,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,$.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,$.jsx)(`span`,{className:`pointer-events-none absolute inset-x-0 bottom-0 px-1.5 pb-1 pt-4 text-left text-[11px] leading-snug text-white bg-gradient-to-t from-black/75 via-black/45 to-transparent ${i===`reveal`?`caption-reveal`:``}`,children:(0,$.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,$.jsx)(`span`,{className:`pointer-events-none absolute right-1 top-1 rounded-full bg-black/55 p-1 text-white transition-opacity ${i===`reveal`?`hidden [@media(hover:hover)]:block [@media(hover:hover)]:group-hover:opacity-0`:``}`,title:`Has a comment`,children:(0,$.jsx)(Me,{className:`h-3 w-3`})})]})}function bx({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Fo(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!gx(a)}),l=wi(a)||`image-${a.id}`,u=Ra(a),[d,f]=(0,Q.useState)(!1);return Fp(r),(0,Q.useEffect)(()=>{let e=e=>{e.target?.closest(`video`)||(e.key===`ArrowLeft`&&n>0&&i(n-1),e.key===`ArrowRight`&&n<t.length-1&&i(n+1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,t.length,i]),(0,Ip.createPortal)((0,$.jsxs)(`div`,{"data-scheme":`dark`,className:`fixed inset-0 z-fullscreen flex flex-col bg-scrim p-0 sm:p-4`,onClick:r,children:[(0,$.jsx)(`button`,{type:`button`,onClick:r,className:`canvas-no-drag absolute right-2 top-2 z-10 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20 touch-target sm:right-4 sm:top-4`,title:`Close`,children:(0,$.jsx)(G,{className:`h-5 w-5`})}),n>0&&!d&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n-1)},className:`canvas-no-drag absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Previous`,children:(0,$.jsx)(E,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n+1)},className:`canvas-no-drag absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Next`,children:(0,$.jsx)(hr,{className:`h-6 w-6 touch-target`})}),(0,$.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,$.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,$.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),gx(a)&&(0,$.jsx)(Sx,{workspaceId:e,doc:a},a.id),o&&(0,$.jsx)(a_,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,$.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,$.jsx)(`span`,{className:`mx-auto mb-1 block max-w-2xl whitespace-pre-wrap text-sm text-foreground`,children:u}),l,` · `,n+1,`/`,t.length,!d&&!gx(a)&&(0,$.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function xx({workspaceId:e,state:t,comments:n,onToggleComments:r}){let{input:i,setInput:a,submit:o,clearSearch:s,removeQuery:c,activeQueries:l,sort:u,setSort:d,page:f,setPage:p,totalPages:m,totalCount:h,isLoading:g}=t,_=l.length>0;return(0,$.jsxs)(`div`,{className:`canvas-no-drag flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b px-1 pb-1.5`,children:[(0,$.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()},placeholder:_?`Refine: add another query (Enter)…`:`Search media (Enter)…`,className:`h-7 w-full rounded-md border bg-background pl-7 pr-7 text-xs`}),_&&(0,$.jsx)(`button`,{type:`button`,onClick:s,title:`Clear search`,className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),_&&(0,$.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,$.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,$.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(t),title:`Remove "${e}"`,className:`rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,$.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-pressed":n!==`off`,title:n===`off`?`Show comments on tiles`:`Hide comments on tiles`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border touch-target ${n===`off`?`text-muted-foreground hover:bg-accent`:`border-primary/30 bg-primary/15 text-primary hover:bg-primary/25`}`,children:(0,$.jsx)(Me,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(nb,{workspaceId:e,value:u,onChange:d}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,$.jsx)(Md,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,$.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(Math.max(1,f-1)),disabled:f<=1,title:`Previous page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,$.jsx)(E,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(Math.min(m,f+1)),disabled:f>=m,title:`Next page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,$.jsx)(hr,{className:`h-3.5 w-3.5`})})]})]})]})}function Sx({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=Uo(e,t.id);return(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`span`,{children:`Loading video…`}),i&&(0,$.jsx)(`span`,{role:`alert`,children:i}),n&&(0,$.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function Cx({config:e,setConfig:t,canvas:n}){let r=vx(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=jo()==null&&(n.interactive??!n.readOnly),[a,o]=(0,Q.useState)(new Set),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),p=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[m,h]=(0,Q.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,$.jsx)(xx,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,$.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,$.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:_?`Loading media…`:y.length?`No images or videos match your search.`:`No images or videos in this canvas' context.`}):(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(min(120px,100%),1fr))] gap-2 sm:grid-cols-[repeat(auto-fill,minmax(min(200px,100%),1fr))] sm:gap-3`,children:g.map((e,t)=>(0,$.jsxs)(`div`,{className:`relative`,onContextMenu:t=>{i&&(t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,ids:a.has(e.id)?[...a]:[e.id]}))},children:[(0,$.jsx)(yx,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select document ${e.id}`,checked:a.has(e.id),onChange:()=>p(e.id),className:`canvas-no-drag absolute left-2 top-2 h-4 w-4 accent-primary`})]},e.id))})}),d&&(0,$.jsx)(mm,{anchor:d,onClose:()=>f(null),label:`${d.ids.length} image${d.ids.length===1?``:`s`}`,items:[{id:`bulk-edit`,label:`Bulk edit… (${d.ids.length})`,icon:_e,run:()=>u(d.ids)}]}),l&&(0,$.jsx)(hg,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,$.jsx)(bx,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}Ff({type:`gallery`,name:`Gallery`,icon:Se,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Cx});var wx=150;function Tx(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function Ex(e){let t=e.metadata??{},n=e.data??{};return{w:Tx(t.width)||Tx(t.imageWidth)||Tx(n.width)||Tx(n.imageWidth),h:Tx(t.height)||Tx(t.imageHeight)||Tx(n.height)||Tx(n.imageHeight)}}function Dx(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=Ex(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 Ox({config:e,setConfig:t,canvas:n}){let r=vx(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,Q.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,$.jsx)(xx,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,$.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,$.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:s?`Loading images…`:l.length?`No images match your search.`:`No images in this canvas' context.`}):(0,$.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${wx}px, 1fr))`,gridAutoRows:`${wx}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=Dx(e,t);return(0,$.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,$.jsx)(yx,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,$.jsx)(bx,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}Ff({type:`mosaic`,name:`Mosaic`,icon:gt,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Ox});var kx=`data/schema/task`;function Ax({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=Y_(e),[a,o]=(0,Q.useState)(!1),{replicating:s,label:c}=bo(e),l=i.status===`completed`,u=i.status??`pending`,d=Z_(i),{activationProps:f,stopRowActivation:p}=lx(e,t),m=async()=>{if(!(n||a)){o(!0);try{await $_(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,$.jsxs)(`div`,{...f,title:`Open details`,className:`canvas-no-drag flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-2.5 py-2 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${s?`opacity-60`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{p(e),m()},disabled:n||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`canvas-no-drag mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${n?`cursor-default opacity-70`:``}`,children:a?(0,$.jsx)(Yn,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,$.jsx)(oe,{className:`h-3 w-3`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,$.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,$.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${X_[u]}`,children:V_[u]}),i.dueDate&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,$.jsx)(pe,{className:`h-3 w-3`}),Q_(i.dueDate)]}),typeof i.priority==`number`&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,$.jsx)(Lt,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,$.jsx)(Yn,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function jx({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!0),[c,l]=(0,Q.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,Q.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,Q.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[kx],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===Ji))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,Q.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,Q.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>Y_(e).status!==`completed`):i,v=i.filter(e=>{let t=Y_(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,$.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,$.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,$.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,$.jsx)(Ax,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}Ff({type:`todos`,name:`Todos`,icon:Vt,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:jx});function Mx(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var Nx=`context`;function Px(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:Nx,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:Nx,path:e?`/${e}`:`/`}}return{treeName:Nx,path:`/`}}function Fx(e,t,n){let r=n&&n!==Nx?`/trees/${encodeURIComponent(n)}`:``,i=Mx(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function Ix({canvas:e}){return jo()!=null||!Sd()?(0,$.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,$.jsx)(Lx,{workspaceId:e.workspaceId},e.workspaceId)}function Lx({workspaceId:e}){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(`Workspace`),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([qr(e),Ai(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),c(null)}catch{if(t||a!==r)return;n([]),c(`Workspace pins are unavailable. Check your workspace access or try again.`)}finally{!t&&a===r&&o(!1)}},s=()=>{document.visibilityState===`visible`&&a()};a(),window.addEventListener(`focus`,s),document.addEventListener(`visibilitychange`,s);let l=hd.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),l?.(),window.clearInterval(u)}},[e,l]),(0,$.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,$.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>u(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,$.jsx)(P,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,$.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,$.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=Nm(t.color),i=(0,$.jsxs)($.Fragment,{children:[n?(0,$.jsx)(W,{className:`h-5 w-5 shrink-0 text-warning`}):(0,$.jsx)(f,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,$.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,$.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,$.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-(--card-radius) border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,$.jsx)(`li`,{children:n?(0,$.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,$.jsx)(Nu,{to:Fx(e,t.path,t.tree),title:`Open ${t.tree}:${t.path}`,className:`${a} transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,style:o,children:i})},t.id)})}):(0,$.jsx)(`p`,{className:`p-2 text-sm text-muted-foreground`,children:a?`Loading pins…`:`No workspace pins yet. Pin a folder from the workspace tree menu.`})})]})}Ff({type:`workspace-pins`,name:`Workspace pins`,icon:Oe,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:Ix});function Rx({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,Q.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,$.jsxs)(`div`,{className:c?u?`absolute inset-0 z-40 flex flex-col bg-background`:`fixed inset-0 z-50 flex flex-col bg-background`:`flex flex-col h-full rounded-(--card-radius) border bg-background overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`canvas-drag-handle flex items-center gap-2 px-2 py-1 border-b bg-muted/30 select-none ${o?``:`cursor-move`}`,children:[t&&(0,$.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,$.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(zx,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:Mn}),(0,$.jsx)(zx,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:de})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-accent touch-target`,title:c?`Restore`:`Full screen`,children:c?(0,$.jsx)(lt,{className:`w-3.5 h-3.5`}):(0,$.jsx)(xn,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 touch-target`,title:`Remove widget`,children:(0,$.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,Ip.createPortal)(d,u??document.body):d}function zx({on:e,onClick:t,label:n,icon:r}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-pressed":e,title:e?`${n} (on)`:n,className:`canvas-no-drag shrink-0 p-0.5 rounded touch-target ${e?`bg-primary/15 text-primary hover:bg-primary/25`:`text-muted-foreground hover:text-foreground hover:bg-accent`}`,children:(0,$.jsx)(r,{className:`w-3.5 h-3.5`})})}var Bx=(0,Nf.WidthProvider)(Nf.default),Vx=12,Hx=80,Ux=40,Wx=[12,12],Gx=[8,8],Kx={w:!1,h:!1};function qx(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function Jx(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function Yx(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 Xx(e,t,n=0){let r=n>0?n:qx(e);return e.map(e=>{let n=t[e.i]??Kx;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?Vx:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var Zx=4;function Qx(e,t,n=Wx[1]){return Math.max(1,Math.ceil((e-n-Zx)/(t+n)))}var $x=45,eS=640;function tS(e,t,n=0,r){let i=[...Xx(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:Vx,y:a,h:n};return a+=n,i})}var nS=e=>e&&e.trim()?[e]:[];function rS(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(Yx):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=Vx,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function iS({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,metadata:a,isLocked:o=!1,readOnly:s=!1,interactive:c=!0,fetchDocuments:l,onSaved:u}){let d=!s,f=(0,Q.useMemo)(()=>rS(a),[a]),[p,m]=(0,Q.useState)(f.layout),[h,g]=(0,Q.useState)(f.widgets),[_,v]=(0,Q.useState)(f.fills),y=(0,Q.useRef)(f.fills),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(0),M=(0,Q.useRef)(0),N=(0,Q.useCallback)(e=>{y.current=e,v(e)},[]),[P,F]=(0,Q.useState)(()=>Gy(i?.sort)),I=(0,Q.useRef)(!1),[L,R]=(0,Q.useState)(()=>nS(i?.query)),z=(0,Q.useRef)(!1),ee=(0,Q.useRef)(null),te=(0,Q.useRef)(f),ne=(0,Q.useCallback)(e=>{let t=If(h[e]?.type??``)?.mobileHeight;if(!(!t||A<=0))return Math.max(1,Math.round(A*t))},[h,A]),B=(0,Q.useMemo)(()=>O?tS(p,_,A,ne):Xx(p,_,A),[p,_,O,A,ne]),re=O?Ux:Hx,ie=(0,Q.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,Q.useEffect)(()=>{let e=rS(a);m(e.layout),g(e.widgets),N(e.fills),te.current=e,F(Gy(i?.sort)),I.current=!1,R(nS(i?.query)),z.current=!1,C(!1)},[n,r]),(0,Q.useEffect)(()=>{if(!s)return;let e=rS(a);m(e.layout),g(e.widgets),N(e.fills),te.current=e},[s,ie,a,N]),(0,Q.useEffect)(()=>{let e=ee.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<eS;k(n),M.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?Gx:Wx;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&j(Qx(t,n?Ux:Hx,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let ae=(0,Q.useCallback)(e=>{F(e),I.current=!0,C(!0)},[]),oe=(0,Q.useCallback)(e=>{R(e),z.current=!0,C(!0)},[]),V=(0,Q.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:P,setCanvasSort:d?ae:void 0,canvasQueries:L,setCanvasQueries:d?oe:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await to(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 to(e,n,t,{...r,anyOf:void 0,ids:i});return{payload:a.payload||[],count:a.count??void 0,totalCount:a.totalCount??void 0}})}),[e,t,n,r,i,d,c,l,P,ae,L,oe]),H=(0,Q.useCallback)((e,t,n)=>{te.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),U=(0,Q.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:te.current.widgets,layout:te.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};te.current={...r,fills:y.current};let o=I.current||z.current?{...i||{},...I.current?{sort:P.sortBy?P:null}:{},...z.current?{query:L.join(` `).trim()||null}:{}}:void 0;await io(e,n,t,{...a||{},ui:r},o),I.current=!1,z.current=!1,C(!1),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t}})),u?.()}catch(e){let t=e instanceof Error?e.message:`Save failed`;D(t),console.error(`Failed to save canvas layout:`,e)}finally{T(!1)}}},[d,w,e,n,t,a,u,i,P,L]),se=(0,Q.useCallback)(e=>{!d||O||m(t=>{let n=e.map(e=>{let n=t.find(t=>t.i===e.i),r=y.current[e.i];return n?{...e,x:r?.w?n.x:e.x,w:r?.w?n.w:e.w,y:r?.h?n.y:e.y,h:r?.h?n.h:e.h}:e});return H(n,h),n})},[d,O,H,h]),W=(0,Q.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??Kx,i=Wx[1]+(n.y+n.h)*(Hx+Wx[1]),a={w:n.x+n.w>=Vx,h:M.current>0&&i>=M.current-$x};if(a.w||=r.w&&n.w===t.w,a.h||=r.h&&n.h===t.h,a.w===r.w&&a.h===r.h)return;let o={...y.current,[n.i]:a};N(o),H(te.current.layout,h,o)},[d,N,H,h]),ce=(0,Q.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??Kx,r={...y.current,[e]:{...n,[t]:!n[t]}};N(r),H(p,h,r)},[d,N,H,p,h]),le=(0,Q.useCallback)(e=>{let t=If(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:Jx(B),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>=Vx,h:!1}};m(l),g(u),N(d),x(!1),H(l,u,d)},[p,B,h,N,H]),ue=(0,Q.useCallback)(e=>{let t=p.filter(t=>t.i!==e),n={...h};delete n[e];let r={...y.current};delete r[e],m(t),g(n),N(r),H(t,n,r)},[p,h,N,H]),de=(0,Q.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return H(p,r),r})},[p,H]),fe=Object.keys(h);return(0,$.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,$.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>x(e=>!e),className:`flex items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:[(0,$.jsx)(sn,{className:`w-3.5 h-3.5`}),`Add`,(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,$.jsx)(`div`,{className:`absolute left-0 top-full mt-1 z-20 w-48 rounded-md border bg-popover shadow-elevation-2 py-1`,children:Lf().map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>le(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,$.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:U,disabled:!S||w,className:J(`flex shrink-0 items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs rounded-md transition-colors disabled:opacity-50`,S?`bg-primary text-primary-foreground hover:bg-primary`:`border hover:bg-accent`),children:[(0,$.jsx)(Be,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,$.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[fe.length,` widget`,fe.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,$.jsx)(`div`,{ref:ee,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:fe.length===0?(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,$.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,$.jsx)(Bx,{className:`layout`,layout:B,cols:Vx,rowHeight:re,margin:O?Gx:Wx,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:se,onResizeStop:W,compactType:`vertical`,children:fe.map(e=>{let t=h[e],n=If(t.type),r=_[e]??Kx,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,$.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,$.jsx)(Rx,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>ue(e),fill:_[e]??Kx,onToggleFill:d?t=>ce(e,t):void 0,children:(0,$.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>de(e,t),canvas:V})}):(0,$.jsx)(Rx,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>ue(e),children:(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var aS=`data/schema/file`;function oS(e){return String(e.locations?.[0]?.url||``).trim()}function sS(e){let t=oS(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function cS(e){return e.schema===aS&&String(e.metadata?.contentType||``).startsWith(`image/`)}function lS(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 uS(e){if(e.schema!==aS)return Yr(e);let t=sS(e),n=String(e.metadata?.contentType||``).trim(),r=lS(e.metadata?.size);return{...Yr(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:oS(e),schemaLabel:`file`}}function dS(e){return/^https?:\/\/[^\s]+$/i.test(e)}function fS(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return dS(t)?t:null}return t.isExternal&&dS(t.subtitle)?t.subtitle:dS(t.title)?t.title:null}function pS(e,t,n=!1){return Lo(e,t,{download:n})}function mS(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>dS(e)?(0,$.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`underline decoration-muted-foreground underline-offset-2 hover:text-primary`,children:e},`${e}-${t}`):e)}function hS(e){return e?new Date(e).toLocaleString():``}function gS(){let{code:e=``}=bl(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=(0,Q.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,Q.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=uS(t);return[t.schema,n.title,n.preview,n.subtitle,sS(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,Q.useCallback)(async()=>{if(e){i(!0);try{let t=await X.get(`${Lr}/pub/c/${encodeURIComponent(e)}`,{skipAuth:!0});n(t),o(null)}catch(e){n(null),o(e instanceof Error?e.message:`Failed to load public canvas`)}finally{i(!1)}}},[e]);(0,Q.useEffect)(()=>{p()},[p]),(0,Q.useEffect)(()=>{if(!e)return;let t=zr(`${Rr}/pub`,{transports:[`websocket`],auth:{code:e},reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1500});return t.on(`connect`,()=>c(!0)),t.on(`disconnect`,()=>c(!1)),t.on(`connect_error`,()=>c(!1)),t.on(`canvas:changed`,()=>p()),()=>{t?.disconnect(),t=null}},[e,p]);let m=(0,Q.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,Q.useCallback)(()=>{u(``)},[]),g=(0,Q.useCallback)(async e=>({payload:ri(e?.sortBy)?ki(d,e.sortBy,e?.order):d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,$.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,$.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,$.jsxs)(Ku,{className:`max-w-md bg-card`,children:[(0,$.jsx)(qu,{children:(0,$.jsx)(Ju,{children:`Canvas unavailable`})}),(0,$.jsx)(Xu,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,$.jsx)(fd,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,$.jsx)(Bo.Provider,{value:e,children:(0,$.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,$.jsxs)(Ku,{className:`bg-card shadow-elevation-3`,children:[(0,$.jsx)(qu,{className:`border-b p-3 sm:p-6`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,$.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-accent text-primary sm:mt-1 sm:h-12 sm:w-12 sm:rounded-2xl`,style:t.canvas.color?{borderLeft:`4px solid ${t.canvas.color}`}:void 0,children:(0,$.jsx)(gt,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground md:hidden`,children:[s?(0,$.jsx)(pr,{className:`h-3 w-3 text-success`}):(0,$.jsx)(w,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,$.jsx)(Ju,{className:`mt-0.5 truncate text-2xl sm:mt-1 sm:text-3xl md:text-5xl`,children:t.canvas.label||t.canvas.name||`Canvas`}),t.canvas.description&&(0,$.jsx)(`p`,{className:`mt-1.5 max-w-3xl text-sm text-muted-foreground sm:mt-3 sm:text-base`,children:t.canvas.description})]})]}),(0,$.jsxs)(`div`,{className:`hidden shrink-0 items-center gap-2 rounded-full border px-3 py-1 text-xs text-muted-foreground md:flex`,children:[s?(0,$.jsx)(pr,{className:`h-3.5 w-3.5 text-success`}):(0,$.jsx)(w,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,$.jsxs)(Xu,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,$.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,$.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,$.jsxs)(`span`,{className:`truncate`,children:[`· `,hS(t.stats.refreshedAt)]})]}),(0,$.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,$.jsx)(_S,{label:`Path`,value:t.share.path,mono:!0}),(0,$.jsx)(_S,{label:`Documents`,value:String(t.stats.documentCount)}),(0,$.jsx)(_S,{label:`Shown`,value:String(f.length)}),(0,$.jsx)(_S,{label:`Refreshed`,value:hS(t.stats.refreshedAt)})]}),v&&(0,$.jsx)(`section`,{id:`content-area`,className:`flex w-full flex-col overflow-hidden rounded-2xl border h-viewport-card min-h-[420px] md:h-viewport-pane`,children:(0,$.jsx)(iS,{workspaceId:t.workspace.name,treeName:t.share.treeName,path:t.share.path,layerId:t.canvas.id,querySpec:t.canvas.querySpec,metadata:t.canvas.metadata,readOnly:!0,interactive:!1,fetchDocuments:g},JSON.stringify(_))}),!v&&(0,$.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 border-b px-4 py-3 md:flex-row md:items-center md:justify-between`,children:[(0,$.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,$.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{type:`search`,value:l,onChange:e=>u(e.target.value),placeholder:`Search loaded documents...`,className:`w-full rounded-md border py-1.5 pl-9 pr-8 text-sm md:w-72`}),l&&(0,$.jsx)(`button`,{type:`button`,onClick:h,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:p,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,$.jsx)(P,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,$.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,$.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,$.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,$.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:l.trim()?`No loaded documents match your search.`:`No documents yet.`}):f.map(t=>{let n=uS(t),r=fS(t,n),i=t.schema===aS,a=i?pS(e,t.id):null,o=a||r;return(0,$.jsxs)(`article`,{className:`p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,$.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,$.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,$.jsxs)(`a`,{href:pS(e,t.id,!0),download:n.title,className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(qt,{className:`h-3.5 w-3.5`}),`Download`]}),(0,$.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:hS(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,$.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:mS(n.preview)}),cS(t)&&(0,$.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,$.jsx)(`img`,{src:a||void 0,alt:n.title,loading:`lazy`,className:`max-h-64 max-w-full rounded border bg-muted object-contain transition-opacity hover:opacity-90`})})]},t.id)})})]})]})]}),(0,$.jsx)(fd,{className:`mt-6 text-center`})]})})})}function _S({label:e,value:t,mono:n=!1}){return(0,$.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,$.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,$.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var vS={title:``,content:``,comment:``,tags:[]};function yS(e,t,n=`add`){let r=R_(),i=qo(`new:${n}:${e?.mode===`workspace`?`${e.workspaceName}:${e.treeName}:${e.path}`:e?.contextId??`home`}`),a=e=>async(n,i,a)=>{let o=typeof i.workspace==`string`?i.workspace:(await Ms(e)).workspaceName,s=await r.capture(),c={schema:`data/schema/note`,schemaVersion:`2.0`,comment:n.comment,data:{title:n.title.trim(),content:n.content},metadata:{features:Yo(n.tags),...s?{geo:s}:{}}},l=typeof i.id==`number`?i.id:void 0;if(l==null){let t=await ys(e,[c],{refresh:!1});if(!t.length)throw Error(`The server did not return the saved note`);l=t[0],a({id:l,workspace:o})}else await fa(o,{...c,id:l});await t?.([l]),_s(e)},o=zo(i,vS,{retainAfterSave:!0,valid:e=>!!e.content.trim(),save:e?a(e):void 0});async function s(e){await o.saveWith(a(e));let t=o.getSnapshot().meta.id;if(typeof t!=`number`)throw Error(`Write a note before saving`);return[t]}return{...o.value,status:o.status,error:o.error,storageError:o.storageError,setTitle:e=>o.update({title:e}),setContent:e=>o.update({content:e}),setComment:e=>o.update({comment:e}),setTags:e=>o.update({tags:e}),saving:o.status===`saving`,canSave:!!o.value.content.trim()&&o.status!==`saving`,save:s,finish:o.clear,retry:o.flush,geotag:r}}var bS=(0,Q.createContext)(void 0);function xS(){let e=(0,Q.useContext)(bS),t=es()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,Q.useMemo)(()=>e===void 0?n?r===`context`&&i?{mode:`context`,contextId:i}:a&&o?{mode:`workspace`,workspaceName:a,path:o,treeName:s||`context`,treeType:s===`directory`||s===`backends`?`directory`:`context`}:null:null:e,[e,n,r,i,a,o,s])}function SS({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,Q.useRef)(null),o=(0,Q.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,Q.useEffect)(()=>{o()},[e,o]),(0,$.jsx)(`textarea`,{ref:e=>{a.current=e,i?.(e)},value:e,onChange:e=>t(e.target.value),onBlur:n,placeholder:r,rows:1,spellCheck:!1,className:`w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-sm leading-relaxed text-foreground outline-none placeholder:text-muted-foreground/60`})}function CS({onLinkTo:e,onDelete:t}){return(0,$.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Link to…`,title:`Link to…`,children:(0,$.jsx)(Zt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-destructive`,"aria-label":`Delete`,title:`Delete (moves to trash)`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})}function wS({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,Q.useState)(!1);return(0,$.jsx)($p,{onClose:n,children:(0,$.jsx)(ih,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await Qr(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:Qp,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 go(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Rg(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var TS=1200;function ES(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 DS(e,t){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([Ss(n,[t]),Cs(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 Na(n,i,[t],{treeName:o,treeType:c,limit:50}).then(e=>{r(e.payload||[]),l({workspaceName:n,path:i,treeName:o,treeType:c})}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))},[e,t]),d=(0,Q.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,Q.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,Q.useEffect)(()=>{u()},[u]),(0,Q.useEffect)(()=>{let e=()=>d();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[d]),{docs:n,setDocs:r,loading:i,error:o,scope:c,reload:d,removeDoc:(0,Q.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await ai(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}function OS({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let s=No(e,t||``,!!t),{title:c,content:l,setTitle:u,setContent:d}=s,f=()=>{s.save().catch(()=>{})};return(0,$.jsxs)(`div`,{ref:t=>n(e.id,t),className:J(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[ES(e.createdAt),` · #`,e.id]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[(0,$.jsx)(Go,{...s,onRetry:s.save}),(0,$.jsx)(CS,{onLinkTo:a,onDelete:o})]})]}),(0,$.jsx)(`input`,{value:c,onChange:e=>u(e.target.value),onBlur:f,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(SS,{value:l,onChange:d,onBlur:f,innerRef:t=>r(e.id,t)})]})}function kS({target:e,onCreated:t,onCancel:n}){let r=yS(e,void 0,`applet`),{title:i,content:a,setTitle:o,setContent:s,saving:c}=r,[l,u]=(0,Q.useState)(null),d=async()=>{try{await r.save(e),r.finish(),t()}catch(e){u(e instanceof Error?e.message:`Failed to save note`)}};return(0,$.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Close note`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]}),(0,$.jsx)(`input`,{value:i,onChange:e=>o(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(SS,{value:a,onChange:s,placeholder:`Write your note…`}),(0,$.jsx)(Go,{...r,onRetry:r.retry}),l&&(0,$.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,$.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,$.jsx)(`button`,{type:`button`,onClick:d,disabled:!a.trim()||c,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:c?`Saving…`:`Done`})})]})}function AS({autoAdd:e=!1}){let t=xS(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=DS(t,ko),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(0),[f,p]=(0,Q.useState)(`desc`),[m,h]=(0,Q.useState)(e),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(new Map),y=(0,Q.useRef)(new Map),b=(0,Q.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,Q.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,Q.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await s(e.id)}catch{}},[s]),C=(0,Q.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return f===`asc`?n:-n}),e},[n,f]),w=(0,Q.useMemo)(()=>{let e=c.trim().toLowerCase();if(!e)return[];let t=[];for(let n of C){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[c,C]),T=w.length?w[Math.min(u,w.length-1)]:null;(0,Q.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,Q.useCallback)(e=>{if(!w.length)return;let t=e?(u+1)%w.length:u;e&&d(t);let n=w[t],r=y.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+c.trim().length)),v.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[w,u,c]);return t?(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),d(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),E(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),c.trim()&&(0,$.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:w.length?`${Math.min(u+1,w.length)}/${w.length}`:`0/0`})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:f===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:f===`desc`?(0,$.jsx)(Bt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(wn,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>h(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,$.jsx)(sn,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,$.jsx)(kS,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)},JSON.stringify(t)),r&&!n.length&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Yn,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,$.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,$.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),C.map(e=>(0,$.jsx)(OS,{doc:e,updateWorkspace:a?.workspaceName??null,registerEl:b,registerBody:x,highlighted:T?.docId===e.id,onLinkTo:()=>_(e.id),onDelete:()=>S(e)},e.id))]}),g!==null&&(0,$.jsx)(wS,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:js(t)})}var jS=`2.1`,MS=new Set([`completed`,`cancelled`]);function NS({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,Q.useState)(String(e.data?.title??``)),[u,d]=(0,Q.useState)(String(e.data?.description??``)),[f,p]=(0,Q.useState)(e.data?.status||`pending`),[m,h]=(0,Q.useState)(W_(e.data?.dueDate)),[g,_]=(0,Q.useState)(`idle`),{replicating:v,label:y}=bo(e),b=(0,Q.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),x=(0,Q.useRef)(null),S=(0,Q.useRef)(0),C=(0,Q.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++S.current;_(`saving`);try{let i=G_(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 fa(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,Q.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}),TS))},[C,f,m]),T=(0,Q.useCallback)(()=>{x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:m})},[C,c,u,f,m]);(0,Q.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]);let E=(0,Q.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,Q.useCallback)(e=>{h(e),x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:e})},[C,c,u,f]),O=MS.has(f);return(0,$.jsxs)(`div`,{ref:t=>n(e.id,t),className:J(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,$.jsxs)(`span`,{className:`shrink-0`,children:[ES(e.createdAt),` · #`,e.id,f!==`pending`&&(0,$.jsxs)(`span`,{children:[` · `,V_[f]??f]})]}),(0,$.jsx)(Bv,{value:m,onChange:D,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,$.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,$.jsx)(Yn,{className:`inline h-3 w-3 animate-spin`}),v&&(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,$.jsx)(oe,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,$.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,$.jsx)(CS,{onLinkTo:a,onDelete:o})]})]}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.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,$.jsx)(be,{className:`h-4 w-4 text-success`}):(0,$.jsx)(ln,{className:`h-4 w-4`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),w(e.target.value,u)},onBlur:T,placeholder:`Untitled`,spellCheck:!1,className:J(`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,$.jsx)(SS,{value:u,onChange:e=>{d(e),w(c,e)},onBlur:T,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function PS({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(K_()),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null);return(0,$.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]}),(0,$.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`What needs doing?`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(SS,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,$.jsx)(`div`,{className:`mt-2`,children:(0,$.jsx)(Bv,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,$.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,$.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await ys(e,[{schema:Ji,schemaVersion:jS,data:q_({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 FS({autoAdd:e=!1}){let t=xS(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=DS(t,Ji),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(0),[p,m]=(0,Q.useState)(`desc`),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(e),[y,b]=(0,Q.useState)(null),x=(0,Q.useRef)(new Map),S=(0,Q.useRef)(new Map),C=(0,Q.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,Q.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,Q.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete todo ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await c(e.id)}catch{}},[c]),E=(0,Q.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,Q.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!MS.has(String(e.data?.status??`pending`)));return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return p===`asc`?n:-n}),e},[n,p,h]),O=(0,Q.useMemo)(()=>n.filter(e=>MS.has(String(e.data?.status??`pending`))).length,[n]),k=(0,Q.useMemo)(()=>{let e=l.trim().toLowerCase();if(!e)return[];let t=[];for(let n of D){let r=String(n.data?.description??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[l,D]),A=k.length?k[Math.min(d,k.length-1)]:null;(0,Q.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,Q.useCallback)(e=>{if(!k.length)return;let t=e?(d+1)%k.length:d;e&&f(t);let n=k[t],r=S.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+l.trim().length)),x.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[k,d,l]);return t?(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:l,onChange:e=>{u(e.target.value),f(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),j(!0))},placeholder:`Search todos…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),l.trim()&&(0,$.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:k.length?`${Math.min(d+1,k.length)}/${k.length}`:`0/0`})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:J(`rounded-md border p-1.5 transition-colors`,h?`border-foreground text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:h?`Hide done items`:`Show done items${O?` (${O})`:``}`,"aria-label":h?`Hide done items`:`Show done items`,children:h?(0,$.jsx)(Xn,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Nt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:p===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:p===`desc`?(0,$.jsx)(Bt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(wn,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a todo`,children:[(0,$.jsx)(sn,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,$.jsx)(PS,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Yn,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,$.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,$.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:O?`Nothing pending - ${O} done item${O>1?`s`:``} hidden.`:`No todos here yet - add the first one.`}),D.map(e=>(0,$.jsx)(NS,{doc:e,updateWorkspace:o?.workspaceName??null,registerEl:C,registerBody:w,highlighted:A?.docId===e.id,onLinkTo:()=>b(e.id),onDelete:()=>T(e),onStatusSaved:E},e.id))]}),y!==null&&(0,$.jsx)(wS,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:js(t)})}var IS=(0,Q.createContext)(null);function LS(){let e=(0,Q.useContext)(IS);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function RS(e=!0){let{registerViewer:t}=LS();(0,Q.useEffect)(()=>{if(e)return t()},[e,t])}var zS=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],BS=`canvas.lens.camera`,VS={min:1,max:4,step:.1,hardware:!1};function HS(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(BS)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:zS.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function US(e,t){let n=zS.find(t=>t.id===e.resolution)??zS[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function WS(e={}){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(e.onEnded);(0,Q.useEffect)(()=>{n.current=e.onEnded});let r=(0,Q.useRef)(null),i=(0,Q.useRef)(null),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(HS),p=(0,Q.useRef)(d),[m,h]=(0,Q.useState)([]),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(1),w=(0,Q.useRef)(1),[T,E]=(0,Q.useState)(!1),D=(0,Q.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,Q.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,Q.useCallback)(async()=>{try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`&&e.deviceId);h(e.map((e,t)=>({deviceId:e.deviceId,label:e.label||`Camera ${t+1}`})))}catch{}},[]),j=(0,Q.useCallback)(()=>{D.current&&window.clearTimeout(D.current),r.current?.getTracks().forEach(e=>e.stop()),r.current=null,t.current&&(t.current.srcObject=null),c(null),o(!1),_(!1),y(null),x(null),C(1),w.current=1,E(!1)},[]),M=(0,Q.useCallback)(async(e,i)=>{r.current=e,e.getVideoTracks().forEach(e=>{e.onended=()=>{j(),n.current?.()}}),t.current&&(t.current.srcObject=e,await t.current.play().catch(()=>{}));let a=e.getVideoTracks()[0],s=a?.getSettings();if(x(s?.width&&s?.height?{width:s.width,height:s.height}:null),_(i),E(!1),i&&a){let e=a.getCapabilities?.()??{};y(e),e.focusMode?.includes(`continuous`)&&await k({focusMode:`continuous`});let t=a.getSettings().zoom;C(e.zoom?t??e.zoom.min:1),w.current=1,A()}c(e),o(!0)},[j,k,A]),N=(0,Q.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:US(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:US(e,!1),audio:!1});throw t}},[]),P=(0,Q.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Camera needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getUserMedia)return u(`Camera API not available in this browser.`),!1;try{let e=await N(p.current);return await M(e,!0),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Camera permission denied.`:t===`NotFoundError`?`No camera found.`:`Camera failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M,N]),F=(0,Q.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Screen capture needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getDisplayMedia)return u(`Screen capture API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1280},height:{ideal:720}},audio:!1});return await M(e,!1),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Screen capture cancelled.`:`Screen capture failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M]),I=(0,Q.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(BS,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]),L=(0,Q.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),R=(0,Q.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),z=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),ee=(0,Q.useCallback)(e=>{let t=v?.focusMode??[];if(!t.length)return;D.current&&window.clearTimeout(D.current);let n=navigator.mediaDevices.getSupportedConstraints(),r=e&&n.pointsOfInterest?{pointsOfInterest:[e]}:{};t.includes(`single-shot`)?(k({...r,focusMode:`single-shot`}),t.includes(`continuous`)&&(D.current=window.setTimeout(()=>void k({...r,focusMode:`continuous`}),1500))):k({...r,focusMode:`continuous`})},[v,k]),te=(0,Q.useCallback)((e=640,n=.72)=>{let r=t.current;if(!r||r.readyState<2||!r.videoWidth)return null;let a=Math.max(1,w.current),o=r.videoWidth/a,s=r.videoHeight/a,c=(r.videoWidth-o)/2,l=(r.videoHeight-s)/2,u=Math.min(1,e/Math.max(o,s)),d=Math.round(o*u),f=Math.round(s*u);i.current||=document.createElement(`canvas`);let p=i.current;p.width=d,p.height=f;let m=p.getContext(`2d`);return m?(m.drawImage(r,c,l,o,s,0,0,d,f),p.toDataURL(`image/jpeg`,n)):null},[]);return(0,Q.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:P,startScreen:F,stop:j,captureFrame:te,camera:(0,Q.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}:VS,zoom:S,setZoom:L,torchSupported:!!v?.torch,torch:T,setTorch:R,focusSupported:z,focusAt:ee}:null,[g,m,d,I,b,v,S,L,T,R,z,ee])}}async function GS(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 X.postEnvelope(`${xr.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 KS=[{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}],qS=1e3,JS=32,YS=12,XS=`canvas.lens.fit`;function ZS({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=LS(),a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,Q.useEffect)(()=>{if(!o)return;let e=window.setTimeout(()=>s(null),900);return()=>window.clearTimeout(e)},[o]);let c=r&&!r.zoomRange.hardware?r.zoom:1;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`video`,{ref:a,muted:!0,playsInline:!0,onClick:t?e=>{let t=a.current;if(!t||!r?.focusSupported||!t.videoWidth)return;let n=t.getBoundingClientRect(),o=(e.clientX-n.left)/n.width,l=(e.clientY-n.top)/n.height,u=.5+(o-.5)/c,d=.5+(l-.5)/c,f=i===`contain`?Math.min(n.width/t.videoWidth,n.height/t.videoHeight):Math.max(n.width/t.videoWidth,n.height/t.videoHeight),p=t.videoWidth*f/n.width,m=t.videoHeight*f/n.height,h=.5+(u-.5)/p,g=.5+(d-.5)/m;h<0||h>1||g<0||g>1||(r.focusAt({x:h,y:g}),s({x:o,y:l,key:Date.now()}))}:void 0,style:c===1?void 0:{transform:`scale(${c})`},className:J(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,$.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute h-10 w-10 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white/90 animate-fade-in`,style:{left:`${o.x*100}%`,top:`${o.y*100}%`}},o.key)]})}function QS({children:e}){let t=es(),n=(0,Q.useRef)(t);(0,Q.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,Q.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=WS({onEnded:()=>a.current()}),[m,h]=(0,Q.useState)(null),g=(0,Q.useRef)(m);(0,Q.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(qS),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(null),[N,P]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(null),[L,R]=(0,Q.useState)(null),z=L&&L.frame===F?L:null,ee=(0,Q.useRef)(null),[te,ne]=(0,Q.useState)(0),[B,re]=(0,Q.useState)(``),[ie,ae]=(0,Q.useState)(()=>{try{return localStorage.getItem(XS)===`cover`?`cover`:`contain`}catch{return`contain`}}),oe=(0,Q.useCallback)(e=>{ae(e);try{localStorage.setItem(XS,e)}catch{}},[]),V=(0,Q.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:qS,snapshot:!1}),H=(0,Q.useRef)([]),U=(0,Q.useRef)(new Map),se=(0,Q.useRef)(null),W=(0,Q.useRef)(null),ce=(0,Q.useRef)(null),le=(0,Q.useRef)(0),ue=(0,Q.useRef)(``),de=(0,Q.useRef)(!1),fe=(0,Q.useRef)(async()=>{}),pe=(0,Q.useRef)(()=>{});(0,Q.useEffect)(()=>{V.current.text=T,V.current.maxDistance=C===``?NaN:Number(C),V.current.rateMs=x,V.current.paused=y},[T,C,x,y]);let me=(0,Q.useCallback)(()=>(ne(e=>e+1),()=>ne(e=>Math.max(0,e-1))),[]),G=(0,Q.useCallback)(e=>{H.current=[...H.current.slice(-2),e];let t=H.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=se.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(se.current=i,n.current?.setLensIds(i))},[]),he=(0,Q.useCallback)((e,t)=>{for(let n of e)U.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);H.current=[...H.current.slice(-2),n];let r=H.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...U.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>U.current.get(e)).filter(e=>!!e);M(s.length),P(s)},[]),ge=(0,Q.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;ce.current?.abort();let a=new AbortController;ce.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await GS(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?[...Xy(o.filters.timeline),...qy(o.filters.geo),...Jy(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?YS:JS,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||V.current!==t||!t.running?!1:(le.current=0,A(Math.round(performance.now()-r)),O(null),i?he(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):G(c.ids),!0)}catch(e){return a.signal.aborted||V.current!==t||!t.running?!1:(le.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[he,G]),_e=(0,Q.useCallback)(async()=>{let e=V.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await ge(t,e)}if(V.current.running){let e=Math.max(le.current?Math.min(3e4,1e3*2**Math.min(le.current-1,5)):0,V.current.rateMs-(performance.now()-t));W.current=window.setTimeout(()=>void fe.current(),e)}},[p,ge]);(0,Q.useEffect)(()=>{fe.current=_e},[_e]);let ve=(0,Q.useCallback)(()=>{let e=V.current.consumer===`filter`;V.current.running=!1,le.current=0,V.current.consumer=null,W.current&&window.clearTimeout(W.current),ce.current?.abort(),f(),H.current=[],U.current.clear(),se.current=null,h(null),v(null),b(!1),re(``),P([]),I(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,Q.useEffect)(()=>{a.current=ve},[ve]);let K=(0,Q.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||de.current||(V.current.running&&ve(),e===`photo`&&!r.image))return!1;de.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return de.current=!1,i?(H.current=[],U.current.clear(),se.current=null,P([]),M(null),O(null),re(r.workspaceRef),V.current={...V.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`?pe.current(r.image):_e(),!0):!1},[u,d,ve,_e]),q=JSON.stringify(t?{contextId:t.state.activeContextId,path:t.state.activeContextPath,tree:t.state.activeTreeName,features:t.state.filters.features,timeline:t.state.filters.timeline,geo:t.state.filters.geo,gps:t.state.filters.lens.gps}:null);(0,Q.useEffect)(()=>{ue.current!==q&&(ue.current=q,V.current.consumer===`filter`&&(ce.current?.abort(),H.current=[],se.current=null,n.current?.setLensIds([])))},[q]);let ye=(0,Q.useCallback)(e=>{V.current.contextPath=e},[]),be=(0,Q.useCallback)(e=>{V.current.paused=e,b(e)},[]),xe=JSON.stringify([T,C,q]),Se=(0,Q.useRef)(xe);(0,Q.useEffect)(()=>{Se.current=xe});let Ce=(0,Q.useCallback)(e=>{let t=V.current;!t.running||!t.workspaceRef||(ee.current={frame:e,key:Se.current},H.current=[],U.current.clear(),se.current=null,M(null),ge(e,t))},[ge]);(0,Q.useEffect)(()=>{pe.current=Ce},[Ce]);let we=(0,Q.useCallback)(()=>{let e=V.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,I(t),Ce(t))},[p,Ce]),Te=(0,Q.useCallback)(()=>{if(V.current.running&&g.current===`photo`){ve();return}V.current.snapshot=!1,ce.current?.abort(),H.current=[],U.current.clear(),I(null)},[ve]),Ee=(0,Q.useCallback)(async(e,t,n)=>{let r=V.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,I(e),Ce(e),!0):K(`photo`,t,{...n,image:e})},[K,Ce]);(0,Q.useEffect)(()=>{if(!F)return;let e=!0,t=new Image;return t.onload=()=>{e&&R({frame:F,width:t.naturalWidth,height:t.naturalHeight})},t.src=F,()=>{e=!1}},[F]),(0,Q.useEffect)(()=>{if(!F)return;let e=ee.current;if(e&&e.frame===F&&e.key===xe)return;let t=window.setTimeout(()=>Ce(F),350);return()=>window.clearTimeout(t)},[F,xe,Ce]),(0,Q.useEffect)(()=>{!i||!V.current.running||r&&r===V.current.workspaceRef||ve()},[i,r,ve]);let De=(0,Q.useCallback)(()=>{let e=n.current;if(e){if(V.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,Q.useEffect)(()=>ve,[ve]);let Oe=(0,Q.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:ie,setFit:oe,workspaceRef:B,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:K,setContextPath:ye,stop:ve,setPaused:be,snapshot:F,takeSnapshot:we,clearSnapshot:Te,snapshotSize:z,searchPhoto:Ee,reopen:De,hasViewer:te>0,registerViewer:me}),[m,y,_,s,c,ie,oe,B,x,C,T,l,D,k,j,N,K,ye,ve,be,F,we,Te,z,Ee,De,te,me]);return(0,$.jsxs)(IS.Provider,{value:Oe,children:[e,(0,$.jsx)(`video`,{ref:o,muted:!0,playsInline:!0,"aria-hidden":!0,className:`pointer-events-none fixed bottom-0 left-0 h-px w-px opacity-0`})]})}var $S=`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`,eC=`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`,tC=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function nC({className:e}){let{camera:t,fit:n,setFit:r}=LS();if(!t)return null;let{devices:i,prefs:a,setPrefs:o,size:s,zoomRange:c,zoom:l,setZoom:u}=t,d=c.max>c.min;return(0,$.jsxs)(`div`,{className:J(`flex flex-col gap-2`,e),children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,$.jsxs)(`select`,{className:J($S,`max-w-[12rem] flex-1`),value:a.deviceId??``,onChange:e=>o({deviceId:e.target.value||null}),title:`Camera / lens. On phones with several rear cameras, pick the main or wide one if the picture is too zoomed in.`,"aria-label":`Camera`,children:[(0,$.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,$.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,$.jsx)(`select`,{className:$S,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:zS.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:eC,title:n===`contain`?`Showing the whole frame — switch to fill the preview`:`Filling the preview (edges cropped) — switch to the whole frame`,"aria-label":n===`contain`?`Fill preview`:`Fit whole frame`,children:n===`contain`?(0,$.jsx)(An,{className:`h-3.5 w-3.5`}):(0,$.jsx)(At,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,$.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:eC,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,$.jsx)(dr,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:J(eC,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,$.jsx)(Ae,{className:`h-3.5 w-3.5`}):(0,$.jsx)(v,{className:`h-3.5 w-3.5`})}),s&&(0,$.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,title:c.hardware?`Optical/sensor zoom`:`Digital zoom — crops the searched frame too`,children:[(0,$.jsx)(R,{className:`h-3.5 w-3.5 shrink-0`}),(0,$.jsx)(`input`,{type:`range`,min:c.min,max:c.max,step:c.step,value:l,onChange:e=>u(Number(e.target.value)),onDoubleClick:()=>u(c.min),className:`h-1 min-w-0 flex-1 accent-foreground`,"aria-label":`Zoom`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:tC(l)})]})]})}function rC(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=LS();return e?n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:J(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,$.jsx)(`span`,{className:`pointer-events-none absolute left-2 top-2 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-white`,children:t===`photo`?`Photo`:`Snapshot`}),(0,$.jsx)(`button`,{type:`button`,onClick:i,className:`absolute bottom-2 left-1/2 flex h-9 -translate-x-1/2 items-center gap-1.5 rounded-full bg-black/60 px-3 text-xs font-medium text-white backdrop-blur transition-colors hover:bg-black/75`,title:t===`photo`?`Close the photo and clear its matches`:`Discard the snapshot and go back to the live feed`,children:t===`photo`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(G,{className:`h-3.5 w-3.5`}),` Close`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ir,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Take a snapshot and search it`,title:`Snapshot: freeze this frame and search for similar items`,className:`absolute bottom-2 left-1/2 flex h-12 w-12 -translate-x-1/2 items-center justify-center rounded-full border-4 border-white/90 bg-white/25 text-white shadow-lg backdrop-blur transition-transform hover:bg-white/40 active:scale-90`,children:(0,$.jsx)(Xt,{className:`h-5 w-5`})}):null}async function iC(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 aC({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=LS(),o=(0,Q.useRef)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await iC(r);await a(i,e,{workspaceRef:t,contextPath:n})}catch{u(`Could not read that image.`)}finally{c(!1),o.current&&(o.current.value=``)}}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o.current?.click(),disabled:r||s||!t,className:i,title:l??`Search with a photo from the camera app or gallery`,children:[(0,$.jsx)(x,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,$.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,$.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var oC=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,sC=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function cC({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=Ei(t),{blobUrl:a}=__(e,t.id,256,{enabled:i}),o=Yr(t);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-(--card-radius) border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,$.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,$.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,$.jsx)(Gm,{document:t,size:10})}),(0,$.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,$.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function lC(){let e=xS(),t=py(),n=LS(),{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:[];RS(p);let g=p?n.snapshotSize??n.camera?.size:null,_=!!g&&g.height>g.width,v=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:y}=n;return(0,Q.useEffect)(()=>{p&&y(f)},[p,f,y]),e?.mode===`workspace`?(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,$.jsx)(`select`,{className:oC,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:KS.map(e=>(0,$.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,$.jsx)(`input`,{className:J(sC,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,$.jsx)(`input`,{className:J(sC,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:s,onChange:e=>c(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),p?(0,$.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,$.jsx)(on,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(`camera`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Ke,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(`screen`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Fn,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,$.jsx)(aC,{consumer:`applet`,workspaceRef:d,contextPath:f,disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`})]}),(0,$.jsxs)(`div`,{className:J(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,_?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[p&&(0,$.jsx)(ZS,{className:`h-full w-full`,interactive:!0}),p&&(0,$.jsx)(rC,{}),!p&&(0,$.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,$.jsx)(dt,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),p&&(0,$.jsx)(nC,{className:`shrink-0`}),(0,$.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,$.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,$.jsxs)($.Fragment,{children:[n.snapshot?`snapshot`:`live`,` · `,l==null?`searching…`:`${l} ms/frame`,` · `,h.length,` match`,h.length===1?``:`es`,f?` · scoped to ${f}`:``]}):m?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),h.length===0?(0,$.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:p?n.snapshot?`Nothing similar in the snapshot`:`Nothing matching in view`:`Matches appear here`}):(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,$.jsx)(cC,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}var uC=`data/schema/`,dC={"data/schema/file":{label:`Files`,icon:nn},"data/schema/note":{label:`Notes`,icon:Kn},"data/schema/task":{label:`Todos`,icon:Vt},"data/schema/tab":{label:`Tabs`,icon:Ye},"data/schema/message/email":{label:`Emails`,icon:bt},"data/schema/link":{label:`Links`,icon:_n},"data/schema/identity":{label:`Identities`,icon:We},"data/schema/drawing":{label:`Sketches`,icon:le}};function fC(e){return dC[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:ke}}function pC(e){return dC[e]?.icon??ke}function mC(e){return{...e,lens:Ky.lens}}function hC(e,t,n=!1){let r=n?e=>e:mC;return JSON.stringify(r(e))!==JSON.stringify(r(t??Ky))}var gC={savedGeoSelection:null,liveEnabled:!1,liveError:null,t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,addModal:!1,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null,activeContextPath:null,activeContextType:null,activeWorkspaceName:null,activeTreeName:null,activeCanvasId:null,activeContextId:null,activeAccentColor:null,filters:Ky,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function _C(e,t){switch(t.type){case`SET_VIEW`:return{...e,t1Open:t.view!==null,t1View:t.view};case`TOGGLE_VIEW`:return e.t1View===t.view?{...e,t1Open:!1,t1View:null}:{...e,t1Open:!0,t1View:t.view};case`CLOSE_T1`:return{...e,t1Open:!1,t1View:null,t2Open:!1,t2AgentId:null};case`OPEN_T2_AGENT`:return{...e,t2Open:!0,t2AgentId:t.agentId};case`CLOSE_T2`:return{...e,t2Open:!1,t2AgentId:null};case`OPEN_ADD`:return{...e,addOpen:!0,addModal:t.modal??(e.addOpen&&e.addModal),addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addModal:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,addModal:!1,addKind:null,addRelateTo:null,editDocument:t.document,editWorkspaceId:t.workspaceId};case`SET_TOOLS_TAB`:return{...e,toolsTab:t.tab};case`SET_APPS_APPLET`:return{...e,appsAppletId:t.appletId};case`SET_ACCENT_COLOR`:return e.activeAccentColor===t.color?e:{...e,activeAccentColor:t.color};case`SET_GEO_SELECTION`:return{...e,geoSelection:t.selection,isDirty:e.activeContextType===`context`?hC(e.filters,e.savedFilters,!0)||JSON.stringify(t.selection)!==JSON.stringify(e.savedGeoSelection):e.isDirty};case`SET_SAVED_GEO_SELECTION`:return{...e,savedGeoSelection:t.selection,isDirty:e.activeContextType===`context`?hC(e.filters,e.savedFilters,!0)||JSON.stringify(e.geoSelection)!==JSON.stringify(t.selection):e.isDirty};case`SET_MAP_DOCUMENTS`:return e.mapDocuments===t.documents&&e.mapWorkspaceId===t.workspaceId?e:{...e,mapDocuments:t.documents,mapWorkspaceId:t.workspaceId};case`SET_NAVIGATION`:{let n=e.activeContextType===t.contextType&&e.activeContextId===t.contextId&&e.activeCanvasId===t.canvasId;return{...e,activeWorkspaceName:t.workspaceName,activeTreeName:t.treeName,activeCanvasId:t.canvasId,activeContextId:t.contextId,activeContextType:t.contextType,activeContextPath:t.contextPath,geoSelection:null,...n?{}:{filters:Ky,savedFilters:null,savedSearchQuery:null,isDirty:!1,savedGeoSelection:null,liveEnabled:!1,liveError:null}}}case`SET_CONTEXT_SCOPE`:return e.activeContextType!==`context`||e.activeWorkspaceName===t.workspaceName&&e.activeContextPath===t.contextPath&&e.activeTreeName===t.treeId?e:{...e,activeWorkspaceName:t.workspaceName,activeContextPath:t.contextPath,activeTreeName:t.treeId};case`SET_LIVE`:return{...e,liveEnabled:t.enabled,liveError:null};case`SET_LIVE_ERROR`:return{...e,liveError:t.error};case`SET_FILTERS`:return{...e,filters:t.filters,isDirty:e.activeContextType===null?!1:hC(t.filters,e.savedFilters,e.activeContextType===`context`)||e.activeContextType===`context`&&JSON.stringify(e.geoSelection)!==JSON.stringify(e.savedGeoSelection)};case`SET_SAVED_FILTERS`:{let n=t.hydrating===!0&&e.isDirty,r=n?e.filters:t.savedFilters??Ky;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?hC(r,t.savedFilters,e.activeContextType===`context`):!1}}case`SET_SAVING`:return{...e,isSaving:t.isSaving};case`SET_BITMAPS`:return{...e,availableBitmaps:t.keys,bitmapsLoading:!1};case`SET_BITMAPS_LOADING`:return{...e,bitmapsLoading:t.loading};case`SET_TIMELINES`:return{...e,availableTimelines:t.names,timelineScales:t.scales??e.timelineScales,timelinesLoading:!1};case`SET_TIMELINES_LOADING`:return{...e,timelinesLoading:t.loading};default:return e}}var vC=`toolbox:session:filters`;function yC(){try{let e=localStorage.getItem(vC);if(!e)return null;let t=JSON.parse(e);return{...Ky,...t,features:{...Ky.features,...t.features??{}},timeline:{...Ky.timeline,...t.timeline??{}},geo:{...Ky.geo,...t.geo??{}},lens:Ky.lens,sort:Gy(t.sort)}}catch{return null}}function bC(e){try{localStorage.setItem(vC,JSON.stringify(mC(e)))}catch{}}function xC(e,t=!1){if(!e?.toolbox)return null;try{let n=e.toolbox;return{features:{allOf:n.features?.allOf??[],anyOf:n.features?.anyOf??[],noneOf:n.features?.noneOf??[]},timeline:{quickFilter:n.timeline?.quickFilter??null,customRanges:n.timeline?.customRanges??(n.timeline?.customRange?[n.timeline.customRange]:[]),indexCreated:n.timeline?.indexCreated??!0,indexUpdated:n.timeline?.indexUpdated??!0,indexDeleted:n.timeline?.indexDeleted??!1,contentEvents:n.timeline?.contentEvents??!1,selectedTimelines:n.timeline?.selectedTimelines??[]},geo:{bbox:n.geo?.bbox??null,includeUnlocated:n.geo?.includeUnlocated??!1},lens:t?{...Ky.lens,...n.lens??{}}:Ky.lens,sort:Gy(n.sort)}}catch{return null}}function SC(e,t){let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)break;return n}function CC({children:e,target:t}){let[n,r]=(0,Q.useReducer)(_C,gC),i=pl(),a=gl(),o=new URLSearchParams(i.search).get(`ownerId`)||void 0,s=(0,Q.useRef)(null),c=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{c.current=n}),(0,Q.useEffect)(()=>{let e=!1,n=i.pathname.split(`/`).filter(Boolean),a=t===void 0?n[0]===`workspaces`&&decodeURIComponent(n[1]||``)||null:t?.mode===`workspace`?t.workspaceName:null,o=t===void 0?n[0]===`contexts`&&decodeURIComponent(n[1]||``)||null:t?.mode===`context`?t.contextId:null,{path:s,treeName:l}=t?.mode===`workspace`?t:a?Px(i.pathname):{path:`/`,treeName:``},u=t=>{if(e)return;let n=t?`canvas`:o?`context`:null,i=c.current;i.activeContextType!==null&&n===null&&bC(i.filters),r({type:`SET_NAVIGATION`,workspaceName:a,treeName:a?l:null,canvasId:t,contextId:o,contextType:n,contextPath:a?s:null})};return a&&s!==`/`?(vi(a,l).then(t=>{if(e)return;let n=SC(t,s);u(n?.type===`canvas`?n.id:null)}).catch(()=>u(null)),()=>{e=!0}):(u(null),()=>{e=!0})},[i.pathname,t]),(0,Q.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_BITMAPS_LOADING`,loading:!0}),ti(e).then(e=>{r({type:`SET_BITMAPS`,keys:e})}))},[n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),Ti(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let{activeContextType:e,activeCanvasId:t,activeWorkspaceName:i,activeTreeName:a,activeContextPath:o}=n;if(e!==`context`){if(e===`canvas`&&t&&i&&o)vi(i,a||`context`).then(e=>{let t=SC(e,o),n=xC(t?.metadata);r({type:`SET_SAVED_FILTERS`,savedFilters:n,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{r({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=yC();r({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[n.activeCanvasId,n.activeContextPath,n.activeContextType,n.activeTreeName,n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let{activeContextType:e,activeContextId:t}=n;if(e!==`context`||!t)return;let l=!1;s.current=null;let u=0,d=e=>{let t=new URLSearchParams(window.location.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let n=t.toString();a(`${i.pathname}${n?`?${n}`:``}${window.location.hash}`,{replace:!0})},f=(e,t,n,i=null,a=n?[n]:[])=>{let o=e?.filters??t??Ky,c=e?.geoSelection??i;s.current=JSON.stringify({filters:o,geoSelection:c,queries:e?.queries??a}),r({type:`SET_SAVED_FILTERS`,savedFilters:t,savedSearchQuery:n}),r({type:`SET_FILTERS`,filters:o}),r({type:`SET_GEO_SELECTION`,selection:c}),r({type:`SET_SAVED_GEO_SELECTION`,selection:i}),r({type:`SET_LIVE`,enabled:e!==null}),d(e?.queries??a)},p=e=>{let n=++u;return Cs(t,o).then(t=>{if(l||n!==u)return;let i=t.metadata,a=xC(i,!0),o=typeof i?.toolboxSearchQuery==`string`?i.toolboxSearchQuery:null;if(r({type:`SET_CONTEXT_SCOPE`,workspaceName:t.workspaceName||t.workspaceId||null,contextPath:t.path||`/`,treeId:t.treeId||null}),t.liveQuery)f(t.liveQuery,a,o,i?.toolboxGeoSelection??null,t.queryOptions?.queries);else if(e){r({type:`SET_LIVE`,enabled:!1});let e=c.current.isDirty?c.current.filters:a??Ky,n=i?.toolboxGeoSelection??null;s.current=JSON.stringify({filters:e,geoSelection:n,queries:[]}),r({type:`SET_SAVED_FILTERS`,savedFilters:a,savedSearchQuery:o,hydrating:!0}),r({type:`SET_GEO_SELECTION`,selection:n}),r({type:`SET_SAVED_GEO_SELECTION`,selection:n});let l=new URLSearchParams(window.location.search),u=t.queryOptions?.queries?.length?t.queryOptions.queries:o?[o]:[];!l.has(`q`)&&!l.has(`search`)&&u.length&&d(u)}}).catch(e=>{l||n!==u||r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not load context`})})};p(!0);let m=()=>{p(!1)},h=hd.on(`context.url.set`,e=>{e?.id===t&&m()}),g=hd.on(`context.updated`,e=>{let n=e;if((n.contextId||n.id)!==t)return;if(!n.metadata){p(!0);return}++u;let r=xC(n.metadata,!0);f(n.liveQuery??null,r,typeof n.metadata.toolboxSearchQuery==`string`?n.metadata.toolboxSearchQuery:null,n.metadata.toolboxGeoSelection??null,n.queryOptions?.queries)}),_=hd.on(`connect`,()=>{p(!0)}),v=hd.on(`disconnect`,()=>{c.current.liveEnabled&&r({type:`SET_LIVE_ERROR`,error:`Disconnected — Live updates will resume when connected.`})});return window.addEventListener(`contexts:refresh`,m),()=>{l=!0,s.current=null,h(),g(),_(),v(),window.removeEventListener(`contexts:refresh`,m)}},[n.activeContextId,n.activeContextType,o]);let l=(0,Q.useMemo)(()=>{let e=new URLSearchParams(i.search),t=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),n=(e.get(`search`)||``).trim();return t.length?t:n?[n]:[]},[i.search]),u=(0,Q.useRef)(l);(0,Q.useEffect)(()=>{u.current=l},[l]);let d=(0,Q.useRef)(!1),f=(0,Q.useRef)(null),[p,m]=(0,Q.useState)(0);(0,Q.useEffect)(()=>()=>{f.current!==null&&window.clearTimeout(f.current),f.current=null},[n.activeContextType,n.activeContextId,n.liveEnabled,o]),(0,Q.useEffect)(()=>{n.activeContextType!==`context`||!n.activeContextId||o||!n.liveEnabled||s.current===null||d.current||f.current!==null||!hd.isConnected()||JSON.stringify({filters:n.filters,geoSelection:n.geoSelection,queries:l})!==s.current&&(f.current=window.setTimeout(()=>{f.current=null;let e=c.current;if(e.activeContextId!==n.activeContextId||!e.liveEnabled)return;let t=u.current,i=JSON.stringify({filters:e.filters,geoSelection:e.geoSelection,queries:t});if(i===s.current)return;let a=s.current;d.current=!0;let o={filters:e.filters,geoSelection:e.geoSelection,queries:t,binding:Zy(e.filters,e.geoSelection,t)};hd.request(`context.filters.set`,{contextId:e.activeContextId,liveQuery:o}).then(()=>{c.current.activeContextId===e.activeContextId&&s.current===a&&(s.current=i,r({type:`SET_LIVE_ERROR`,error:null}))}).catch(t=>{c.current.activeContextId===e.activeContextId&&r({type:`SET_LIVE_ERROR`,error:t instanceof Error?t.message:`Live update failed`})}).finally(()=>{d.current=!1,m(e=>e+1)})},n.liveError?1500:100))},[n.activeContextType,n.activeContextId,n.liveEnabled,n.filters,n.geoSelection,l,o,p,n.liveError]);let h=(0,Q.useCallback)(async e=>{let t=c.current;if(t.activeContextType!==`context`||!t.activeContextId||o)return;let n=l,i=e?{filters:t.filters,geoSelection:t.geoSelection,queries:n,binding:Zy(t.filters,t.geoSelection,n)}:null;try{await hd.request(`context.filters.set`,{contextId:t.activeContextId,liveQuery:i}),s.current=JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:n}),r({type:`SET_LIVE`,enabled:e})}catch(e){r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not change Live mode`})}},[o,l]);(0,Q.useEffect)(()=>{n.activeContextType===null&&bC(n.filters)},[n.filters,n.activeContextType]);let g=(0,Q.useCallback)(e=>r({type:`SET_VIEW`,view:e}),[]),_=(0,Q.useCallback)(e=>r({type:`TOGGLE_VIEW`,view:e}),[]),v=(0,Q.useCallback)(()=>r({type:`CLOSE_T1`}),[]),y=(0,Q.useCallback)(e=>r({type:`OPEN_T2_AGENT`,agentId:e}),[]),b=(0,Q.useCallback)(()=>r({type:`CLOSE_T2`}),[]),x=(0,Q.useCallback)(e=>r({type:`OPEN_ADD`,kind:e}),[]),S=(0,Q.useCallback)(e=>r({type:`OPEN_ADD`,kind:null,modal:e?.modal,relateTo:e?.fresh?null:void 0}),[]),C=(0,Q.useCallback)((e,t=!1)=>r({type:`OPEN_ADD`,kind:null,relateTo:e,modal:t}),[]),w=(0,Q.useCallback)(()=>r({type:`CLOSE_ADD`}),[]),T=(0,Q.useCallback)((e,t)=>r({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),E=(0,Q.useCallback)(e=>r({type:`SET_TOOLS_TAB`,tab:e}),[]),D=(0,Q.useCallback)(e=>r({type:`SET_APPS_APPLET`,appletId:e}),[]),O=(0,Q.useCallback)(e=>r({type:`SET_ACCENT_COLOR`,color:e}),[]),k=(0,Q.useCallback)(e=>{r({type:`SET_FILTERS`,filters:e})},[]),A=(0,Q.useCallback)((e,t)=>{let{filters:n}=c.current,i=e.startsWith(uC),a=i?n.features.allOf.filter(t=>t!==e):t?[...new Set([...n.features.allOf,e])]:n.features.allOf.filter(t=>t!==e),o=i&&t?[...new Set([...n.features.anyOf,e])]:n.features.anyOf.filter(t=>t!==e),s=n.features.noneOf.filter(t=>t!==e);r({type:`SET_FILTERS`,filters:{...n,features:{allOf:a,anyOf:o,noneOf:s}}})},[]),j=(0,Q.useCallback)((e,t)=>{let{filters:n}=c.current,i=n.features.allOf.filter(t=>t!==e),a=n.features.anyOf.filter(t=>t!==e),o=n.features.noneOf.filter(t=>t!==e);t===`allOf`?i.push(e):t===`anyOf`?a.push(e):t===`noneOf`&&o.push(e),r({type:`SET_FILTERS`,filters:{...n,features:{allOf:i,anyOf:a,noneOf:o}}})},[]),M=(0,Q.useCallback)(()=>{let{filters:e}=c.current;r({type:`SET_GEO_SELECTION`,selection:null}),r({type:`SET_FILTERS`,filters:{...Ky,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}});let t=new URLSearchParams(i.search);t.delete(`q`),t.delete(`search`),t.set(`q`,``),a({pathname:i.pathname,search:t.toString(),hash:i.hash},{replace:!0})},[i.pathname,i.search,i.hash,a]),N=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),P=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),F=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),I=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),L=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),R=(0,Q.useCallback)(e=>{r({type:`SET_GEO_SELECTION`,selection:e})},[]),z=(0,Q.useCallback)((e,t=null)=>{r({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),ee=(0,Q.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:n,activeTreeName:a,activeContextPath:s,filters:u,geoSelection:d,isSaving:f}=c.current;if(!f){r({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&n&&s){let e=a||`context`,t=SC(await vi(n,e),s),r=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await zi(n,s,{metadata:{...t?.metadata||{},toolbox:mC(u)},querySpec:{features:u.features,filters:[...Xy(u.timeline),...qy(u.geo)],query:r.trim()||void 0,sort:u.sort?.sortBy?u.sort:null}},e),Da(n,e)}else if(e===`context`&&t){let e=(await Cs(t,o)).metadata||{},n=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await ns(t,{metadata:{...e,toolbox:u,toolboxGeoSelection:d,toolboxSearchQuery:n.trim()||void 0},...Zy(u,d,l)},o)}let c=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;r({type:`SET_SAVED_FILTERS`,savedFilters:u,savedSearchQuery:c.trim()||null,hydrating:!0}),e===`context`&&r({type:`SET_SAVED_GEO_SELECTION`,selection:d})}finally{r({type:`SET_SAVING`,isSaving:!1})}}},[i.search,o,l]),te=(0,Q.useCallback)(e=>{let t=c.current.availableBitmaps.filter(t=>t!==e);r({type:`SET_BITMAPS`,keys:t});let n=c.current.filters,i={...n,features:{allOf:n.features.allOf.filter(t=>t!==e),anyOf:n.features.anyOf.filter(t=>t!==e),noneOf:n.features.noneOf.filter(t=>t!==e)}};JSON.stringify(i.features)!==JSON.stringify(n.features)&&r({type:`SET_FILTERS`,filters:i})},[]),ne=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await yo(t,e),te(e)},[te]),B=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await Vi(t,e);return te(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[te]),re=(0,Q.useCallback)(()=>{let e=c.current.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),Ti(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[]),ie=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Ri(t,e),re()},[re]),ae=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Oi(t,e);let n=c.current.availableTimelines.filter(t=>t!==e);r({type:`SET_TIMELINES`,names:n});let i=c.current.filters,a=i.timeline.selectedTimelines.filter(t=>t!==e);a.length!==i.timeline.selectedTimelines.length&&r({type:`SET_FILTERS`,filters:{...i,timeline:{...i.timeline,selectedTimelines:a}}})},[]),{features:oe,timeline:V,geo:H,lens:U}=n.filters,se=oe.allOf.length>0||oe.anyOf.length>0||oe.noneOf.length>0||V.quickFilter!==null||(V.customRanges?.length??0)>0||(V.selectedTimelines?.length??0)>0||H.bbox!==null||U.gps!==null||U.ids!==null||n.geoSelection!==null;return(0,$.jsx)(fs.Provider,{value:{state:n,setView:g,toggleView:_,closeT1:v,openAgentT2:y,closeT2:b,openAdd:x,openAddPicker:S,openAddRelated:C,closeAdd:w,openEdit:T,setToolsTab:E,openApplet:D,setAccentColor:O,setFilters:k,setFeatureToggle:A,setFeatureMode:j,clearFilters:M,hasActiveFilters:se,setTimelineFilter:P,setGeoBBox:F,setLensGps:I,setLensIds:L,setGeoSelection:R,setMapDocuments:z,setSort:N,setLiveEnabled:h,saveFilters:ee,deleteBitmap:ne,deleteDataset:B,createTimeline:ie,deleteTimeline:ae,refreshTimelines:re},children:e})}function wC(e){let t=new URLSearchParams(e),n=t.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(t.get(`search`)||``).trim();return t.has(`q`)?n:r?[r]:[]}function TC(){let{state:e,setFilters:t}=zs();return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:e.filters.geo.includeUnlocated??!1,onChange:n=>t({...e.filters,geo:{...e.filters.geo,includeUnlocated:n.target.checked}})}),`Include documents without a location`]})}var EC=p();Zo();var DC=`#8b5cf6`,OC=`#94a3b8`,kC={color:DC,weight:2,fillColor:DC,fillOpacity:.12},AC={color:DC,weight:2,dashArray:`5,5`,fillColor:DC,fillOpacity:.06},jC=e=>Math.round(e*1e6)/1e6;function MC(e){let t=e<10?32:e<100?38:44,n=`<div style="display:flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:9999px;background:${DC};color:#fff;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4);font:600 12px system-ui,sans-serif;cursor:pointer">${e}</div>`;return ag.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var NC=e=>e.replace(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e]),PC=new Map;function FC(e){let t=PC.get(e);return t??(t=(0,EC.renderToStaticMarkup)((0,Q.createElement)(pC(e),{width:13,height:13,strokeWidth:2.5})),PC.set(e,t)),t}var IC=new Map;function LC(e,t){let n=`${e}|${+!!t}`,r=IC.get(n);if(!r){let i=`<div style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:9999px;background:${t?DC:OC};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${FC(e)}</div>`;r=ag.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),IC.set(n,r)}return r}function RC(){let{state:e,setGeoSelection:t,setGeoBBox:n}=zs(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=py(),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(null),p=(0,Q.useRef)([]),m=(0,Q.useRef)(!1),[h,g]=(0,Q.useState)(`idle`),[_,v]=(0,Q.useState)(0),y=(0,Q.useRef)(h),b=(0,Q.useMemo)(()=>r.reduce((e,t)=>e+ +!!Py(t),0),[r]),x=(0,Q.useMemo)(()=>i?r.reduce((e,t)=>{let n=Py(t);return e+(n&&Iy(n.lat,n.lon,i)?1:0)},0):0,[r,i]),S=(0,Q.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&ag.default.polyline(t,AC).addTo(e),t.forEach(t=>ag.default.circleMarker(t,{radius:4,color:DC,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),C=(0,Q.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),w=(0,Q.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:jC(e.lat),lon:jC(e.lng)}))}),C(),g(`idle`)},[t,C]),T=(0,Q.useCallback)(()=>{C(),g(`idle`),t(null),n(null)},[C,t,n]);(0,Q.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=ag.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});ag.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`&copy; OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=ag.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>MC(e.getChildCount())}).addTo(t),f.current=ag.default.layerGroup().addTo(t),l.current=t;let r=t.getContainer(),i=null,a=null,o=()=>{a&&=(a.remove(),null)},s=e=>{if(y.current===`rect`){e.preventDefault(),i=t.mouseEventToLatLng(e),o();try{r.setPointerCapture(e.pointerId)}catch{}}},m=e=>{if(y.current!==`rect`||!i)return;e.preventDefault();let n=ag.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=ag.default.rectangle(n,AC).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=ag.default.latLngBounds(i,t.mouseEventToLatLng(e));i=null,o();try{r.releasePointerCapture(e.pointerId)}catch{}let s=a.getSouthWest(),c=a.getNorthEast();s.lat!==c.lat&&s.lng!==c.lng&&n({minLat:jC(s.lat),minLon:jC(s.lng),maxLat:jC(c.lat),maxLon:jC(c.lng)}),g(`idle`)};r.addEventListener(`pointerdown`,s),r.addEventListener(`pointermove`,m),r.addEventListener(`pointerup`,h),r.addEventListener(`pointercancel`,h);let _=e=>{y.current===`polygon`&&(p.current=[...p.current,e.latlng],v(p.current.length),S())};t.on(`click`,_);let b=new ResizeObserver(()=>t.invalidateSize());b.observe(e);let x=window.setTimeout(()=>t.invalidateSize(),120);return()=>{r.removeEventListener(`pointerdown`,s),r.removeEventListener(`pointermove`,m),r.removeEventListener(`pointerup`,h),r.removeEventListener(`pointercancel`,h),t.off(`click`,_),b.disconnect(),window.clearTimeout(x),t.remove(),l.current=null,u.current=null,f.current=null,d.current=null}},[t,n,S]),(0,Q.useEffect)(()=>{y.current=h;let e=l.current;if(!e)return;let t=e.getContainer();h!==`polygon`&&p.current.length&&C(),h===`rect`?(e.dragging.disable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=`none`):h===`polygon`?(e.dragging.enable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=``):(e.dragging.enable(),e.doubleClickZoom.enable(),t.style.cursor=``,t.style.touchAction=``)},[h,C]),(0,Q.useEffect)(()=>{let e=l.current,t=c.current;if(!e||!t)return;let n=new ResizeObserver(()=>e.invalidateSize());return n.observe(t),()=>n.disconnect()},[]),(0,Q.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=Py(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||Iy(t.lat,t.lon,i),c=ag.default.marker([t.lat,t.lon],{icon:LC(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(NC(Yr(e).title),{direction:`top`,offset:[0,-14]}),c.on(`click`,()=>{y.current===`idle`&&s(e,a??``)}),o.push(c)}t.addLayers(o),!m.current&&n.length&&!i&&(m.current=!0,e.fitBounds(ag.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,Q.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=ag.default.layerGroup();o&&ag.default.rectangle(ag.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),kC).addTo(t),i?.kind===`polygon`&&ag.default.polygon(i.points.map(e=>[e.lat,e.lon]),kC).addTo(t),t.addTo(e),d.current=t},[o,i]);let E=h===`rect`?`Drag a box on the map…`:h===`polygon`?`Tap to add points${_?` · ${_}`:``}`:o||i?`Area selected`:`Pan & pick an area`,D=`flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors`;return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:J(D,h===`rect`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Drag a rectangle to select an area`,children:[(0,$.jsx)(zn,{className:`h-3.5 w-3.5`}),`Box`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:J(D,h===`polygon`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Tap points to enclose an area`,children:[(0,$.jsx)(Ee,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:w,disabled:_<3,className:J(D,`border-primary bg-primary text-primary-foreground hover:bg-primary disabled:opacity-40 disabled:hover:bg-primary`),title:`Close the polygon and filter`,children:[(0,$.jsx)(oe,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,$.jsx)(`button`,{type:`button`,onClick:C,className:J(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:T,disabled:!o&&!i&&h===`idle`,className:J(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent`),title:`Clear the area selection`,children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,$.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:E})]}),(0,$.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,$.jsx)(`div`,{ref:c,className:`absolute inset-0`}),b===0&&(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,$.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border px-3 py-2 shrink-0 text-[11px] text-muted-foreground`,children:[(0,$.jsx)(tn,{className:`h-3 w-3`}),b,` of `,r.length,` located`,i&&(0,$.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,x,` in area`]})]})]})}var zC=[{label:`25 m`,m:25},{label:`100 m`,m:100},{label:`500 m`,m:500},{label:`2 km`,m:2e3},{label:`10 km`,m:1e4}],BC=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,VC=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,HC=e=>Math.round(e*1e4)/1e4;function UC(){let{state:e,setLensGps:t,setLensIds:n}=zs(),r=e.filters.lens,i=e.activeWorkspaceName,a=r.gps?.radiusM??100,[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(r.gps?.radiusM??100),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(0),[m,h]=(0,Q.useState)(`prompt`),g=(0,Q.useRef)(null),_=(0,Q.useRef)(c);(0,Q.useEffect)(()=>{_.current=c},[c]);let v=`geolocation`in navigator&&window.isSecureContext;(0,Q.useEffect)(()=>{if(!navigator.permissions?.query)return;let e=null;return navigator.permissions.query({name:`geolocation`}).then(t=>{e=t,h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`),t.onchange=()=>h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`)}).catch(()=>{}),()=>{e&&(e.onchange=null)}},[]),(0,Q.useEffect)(()=>{if(!o||!v)return;let e=navigator.geolocation.watchPosition(e=>{let n=HC(e.coords.latitude),r=HC(e.coords.longitude);t({lat:n,lon:r,radiusM:_.current})},e=>d(e.code===e.PERMISSION_DENIED?`Location permission denied.`:e.message),{enableHighAccuracy:!0,maximumAge:15e3,timeout:2e4});return g.current=e,()=>{navigator.geolocation.clearWatch(e),g.current=null}},[o,v,f,t]);let y=e=>{s(e),d(null),e||t(null)},b=()=>{d(null),s(!0),p(e=>e+1)},x=e=>{l(e),r.gps&&t({...r.gps,radiusM:e})},S=LS(),{rateMs:C,setRateMs:w,maxDistance:T,setMaxDistance:E,error:D}=S,O=S.running&&S.consumer===`filter`,k=S.running&&S.consumer!==`filter`;RS(O);let A=t=>{i&&S.start(t,`filter`,{workspaceRef:i,contextPath:e.activeContextPath})},j=O,M=S.snapshotSize??S.camera?.size,N=!!M&&M.height>M.width;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[e.activeContextType===`context`&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Point the camera at an object to find visually related content in this context. `,e.liveEnabled?`Bound devices follow your matches as you move.`:`Enable Live to show the matches on your other devices.`]}),(0,$.jsx)(TC,{}),(0,$.jsxs)(`section`,{className:`space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,disabled:!v,onChange:e=>y(e.target.checked)}),(0,$.jsx)(fn,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`span`,{children:`Track this device’s GPS`})]}),(0,$.jsx)(`select`,{className:BC,value:c,onChange:e=>x(Number(e.target.value)),disabled:!o,children:zC.map(e=>(0,$.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?m===`denied`?(0,$.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):u?(0,$.jsxs)(`span`,{className:`text-destructive`,children:[u,` `,(0,$.jsx)(`button`,{type:`button`,onClick:b,className:`underline hover:text-foreground`,children:`Request again`})]}):r.gps?`Showing documents within ${a>=1e3?`${a/1e3} km`:`${a} m`} of ${r.gps.lat}, ${r.gps.lon}.`:o?`Waiting for a position fix…`:`Resurface documents geotagged near your current position.`:`Needs a secure context (https or localhost) with location access.`})]}),(0,$.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,$.jsxs)(`button`,{type:`button`,onClick:S.stop,className:`flex h-7 items-center gap-1 rounded-md bg-destructive px-2.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,children:[(0,$.jsx)(on,{className:`h-3.5 w-3.5`}),` `,S.source===`photo`?`Close photo`:`Stop ${S.source===`camera`?`camera`:`recording`}`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>A(`camera`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Ke,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>A(`screen`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Fn,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,$.jsx)(aC,{consumer:`filter`,workspaceRef:i??``,contextPath:e.activeContextPath,disabled:k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`}),(0,$.jsx)(`select`,{className:BC,value:C,onChange:e=>w(Number(e.target.value)),disabled:!i,title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:KS.map(e=>(0,$.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,$.jsx)(`input`,{className:J(VC,`w-24`),placeholder:`max dist`,inputMode:`decimal`,value:T,onChange:e=>E(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K (loose but tunable).`})]}),(0,$.jsxs)(`div`,{className:J(`relative overflow-hidden rounded-lg border border-border bg-black/80`,j?N?`aspect-[3/4] max-h-[60vh]`:`aspect-video`:`hidden`),children:[(0,$.jsx)(ZS,{className:`h-full w-full`,interactive:!0}),(0,$.jsx)(rC,{})]}),j&&(0,$.jsx)(nC,{}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?(0,$.jsx)(`span`,{className:`text-destructive`,children:D}):j?S.snapshot?`Snapshot: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. The photo is not stored. Tap Live to resume the feed.`:`Live: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. Tap the shutter to search one still frame. Frames are ephemeral, never stored. Closing the toolbox keeps it running.`:k?`The Lens applet is using the camera. Stop it there first.`:r.ids===null?i?`Point a camera (or share a screen). The view narrows to what the feed matches.`:`Open a workspace to refine with a live feed.`:`The current view holds ${r.ids.length} camera match${r.ids.length===1?``:`es`}. Save to keep this view, or clear matches to remove the camera filter.`}),!j&&r.ids!==null&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(null),className:`min-h-10 rounded-md border border-border px-3 text-xs hover:bg-muted`,children:`Clear matches`})]})]})}var WC={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function GC(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t%360+360)%360}function KC(e){return WC[e]??`oklch(var(--data-l) var(--data-c) ${GC(e)})`}var qC=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],JC=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],YC=[`Yesterday`,`Today`,`Tomorrow`],XC=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],ZC=10,QC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function $C(e,t){let n=new Date;switch(e){case`millennium`:{let e=Math.floor(n.getFullYear()/1e3)*1e3;return new Date(e-t*1e3,0,1)}case`century`:{let e=Math.floor(n.getFullYear()/100)*100;return new Date(e-t*100,0,1)}case`decade`:{let e=Math.floor(n.getFullYear()/10)*10;return new Date(e-t*10,0,1)}case`year`:return new Date(n.getFullYear()-t,0,1);case`month`:return new Date(n.getFullYear(),n.getMonth()-t,1);case`week`:{let e=(n.getDay()+6)%7,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()-e);return r.setDate(r.getDate()-t*7),r}}}function ew(e,t){let n=new Date(t);switch(e){case`millennium`:n.setFullYear(n.getFullYear()+1e3);break;case`century`:n.setFullYear(n.getFullYear()+100);break;case`decade`:n.setFullYear(n.getFullYear()+10);break;case`year`:n.setFullYear(n.getFullYear()+1);break;case`month`:n.setMonth(n.getMonth()+1);break;case`week`:n.setDate(n.getDate()+7)}return n}function tw(e,t,n){if(n===0)return`Now`;switch(e){case`millennium`:case`century`:case`decade`:{let e=t.getFullYear();return e<=0?`${1-e} BCE`:`${e}`}case`year`:return`${t.getFullYear()}`;case`month`:return`${QC[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${QC[t.getMonth()]} – ${e.getDate()} ${QC[e.getMonth()]}`}}}function nw(e,t){return Array.from({length:t},(t,n)=>{let r=$C(e,n),i=ew(e,r);return{offset:n,label:tw(e,r,n),start:r,end:i,isNow:n===0}})}var rw={yesterday:5,today:5,tomorrow:5,lastWeek:5,thisWeek:5,nextWeek:5,lastMonth:4,thisMonth:4,nextMonth:4,lastYear:3,thisYear:3,nextYear:3,lastDecade:2,thisDecade:2,nextDecade:2,lastCentury:1,thisCentury:1,nextCentury:1,lastMillennium:0,thisMillennium:0,nextMillennium:0};function iw(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function aw(e,t){let n=uw(e);return n?(n.setDate(n.getDate()+t),iw(n)):e}function ow(e){let t=[...e].sort((e,t)=>e.start.localeCompare(t.start)),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=aw(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function sw(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return ow([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=aw(t,-1)&&r.push({start:n.start,end:aw(t,-1)}),aw(t,1)<=n.end&&r.push({start:aw(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function cw(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:iw(t.start),end:iw(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function lw({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=zs(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,Q.useState)(3),[d,f]=(0,Q.useState)(ZC),[p,m]=(0,Q.useState)(new Set),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)(e);e!==_&&(v(e),e&&rw[e]!==void 0&&u(rw[e]),m(new Set));let[y,b]=(0,Q.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=XC[l],S=nw(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,Q.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{qi(a,{names:r,buckets:nw(x.unit,d).map(e=>cw(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:qy(c.geo),applyCanvasSpec:!1}).then(t=>{e||g(t)}).catch(()=>{e||g([])})},250);return()=>{e=!0,clearTimeout(t)}},[a,o,s,x.unit,d,w,C]);let T=a&&r.length>0?h:[],E=Math.max(1,...T.map(e=>e.total)),D=e=>{u(t=>Math.max(0,Math.min(5,t+e))),f(ZC),m(new Set)},O=(0,Q.useCallback)((e,t)=>{m(r=>{let i;if(t&&r.size>0){let t=Math.min(e,...r),n=Math.max(e,...r);i=new Set(r);for(let e=t;e<=n;e++)i.add(e)}else i=new Set(r),i.has(e)?i.delete(e):i.add(e);let a=[...i].sort((e,t)=>e-t),o=[];for(let e of a){let t=o[o.length-1];t&&e===t[1]+1?t[1]=e:o.push([e,e])}return n(o.map(([e,t])=>{let n=S.find(e=>e.offset===t).start,r=new Date(S.find(t=>t.offset===e).end);return r.setDate(r.getDate()-1),{start:iw(n),end:iw(r)}})),i})},[S,n]);return(0,$.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,$.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom in (finer periods)`,children:(0,$.jsx)(R,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom out (coarser periods)`,children:(0,$.jsx)(Te,{className:`w-3.5 h-3.5`})})]})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-1.5 space-y-1 touch-target`,children:[S.map(e=>{let t=p.has(e.offset),n=T[e.offset],r=n?.total??0,i=r>0?Math.log1p(r)/Math.log1p(E):0,a=n&&r>0?`: ${r} doc${r===1?``:`s`} (${Object.entries(n.counts).map(([e,t])=>`${e}: ${t}`).join(`, `)})`:``;return(0,$.jsxs)(`button`,{type:`button`,onClick:t=>O(e.offset,t.shiftKey),title:`${e.isNow?`Now`:e.label}${a}. Click to tag, shift-click to fill range`,className:J(`w-full flex items-center gap-2 rounded-2xl px-3 py-1.5 text-xs font-medium transition-colors select-none text-left`,t?`bg-primary text-primary-foreground`:e.isNow?`bg-primary/10 text-primary hover:bg-primary/20`:`bg-card text-foreground hover:bg-muted shadow-elevation-1`),children:[e.isNow&&(0,$.jsx)(N,{className:`w-3 h-3 shrink-0`}),(0,$.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,$.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,$.jsx)(`span`,{className:J(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,$.jsx)(`span`,{className:`mt-1 flex h-[3px] overflow-hidden rounded-full`,style:{width:`${Math.max(8,i*100)}%`},children:Object.entries(n.counts).map(([e,t])=>(0,$.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:KC(e)}},e))})]})]},e.offset)}),d<200&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+ZC),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function uw(e){let t=/^(-?\d{1,6})-(\d{2})-(\d{2})$/.exec(e);return t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):null}function dw({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,Q.useState)(()=>{let t=e[0]?.start&&uw(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=e=>a(t=>{let n=new Date(t.y,t.m+e,1);return{y:n.getFullYear(),m:n.getMonth()}}),d=(e,r)=>{if(r){n(e),s(null),l(null);return}if(!o){s(e);return}let[i,a]=o<=e?[o,e]:[e,o];t(i,a),s(null),l(null)},f=new Date(i.y,i.m,1),p=new Date(f);p.setDate(p.getDate()-(f.getDay()+6)%7);let m=Array.from({length:42},(e,t)=>{let n=new Date(p);return n.setDate(n.getDate()+t),n}),[h,g]=o?c&&c!==o?o<=c?[o,c]:[c,o]:[o,o]:[null,null],_=t=>e.some(e=>t>=e.start&&t<=e.end),v=t=>e.some(e=>t===e.start||t===e.end),y=iw(r);return(0,$.jsxs)(`div`,{className:`select-none`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(-12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous year`,children:(0,$.jsx)(Fe,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous month`,children:(0,$.jsx)(E,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>a({y:r.getFullYear(),m:r.getMonth()}),className:`text-xs font-semibold text-foreground hover:text-primary transition-colors`,title:`Jump to current month`,children:[QC[i.m],` `,i.y]}),(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next month`,children:(0,$.jsx)(hr,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next year`,children:(0,$.jsx)(ge,{className:`w-3.5 h-3.5`})})]})]}),(0,$.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,$.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,$.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=iw(e),n=e.getMonth()===i.m,r=h!==null&&g!==null&&t>=h&&t<=g,a=t===h||t===g,s=!o&&_(t),c=a||s&&v(t);return(0,$.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:J(`h-6 text-[11px] tabular-nums transition-colors`,c?`bg-primary text-primary-foreground rounded-md`:r||s?`bg-primary/15 text-foreground`:n?`text-foreground hover:bg-muted rounded-md`:`text-muted-foreground/40 hover:bg-muted rounded-md`,t===y&&!c&&`font-bold text-primary`),children:e.getDate()},t)})}),(0,$.jsx)(`p`,{className:`mt-1.5 text-[10px] text-muted-foreground/70`,children:o?`From ${o}: pick the end date`:`Click start + end. Ctrl+click adds/removes single days.`})]})}function fw({label:e,checked:t,onChange:n,color:r}){return(0,$.jsxs)(`div`,{role:`switch`,"aria-checked":t,tabIndex:0,onClick:()=>n(!t),onKeyDown:e=>(e.key===` `||e.key===`Enter`)&&n(!t),className:`flex items-center justify-between gap-3 cursor-pointer select-none outline-none focus-visible:ring-2 focus-visible:ring-ring rounded`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,$.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,$.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,$.jsx)(`div`,{className:J(`relative w-10 h-5 rounded-full transition-colors shrink-0`,!t&&`bg-accent dark:bg-muted-foreground`),style:t?{backgroundColor:r}:void 0,children:(0,$.jsx)(`div`,{className:J(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function pw(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=zs(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(`quick`),[_,v]=(0,Q.useState)(!1),{showToast:y}=Vr(),b=new Set(a.selectedTimelines??[]),x=(0,Q.useMemo)(()=>{let e=[];return a.indexCreated&&e.push(`crud:created`),a.indexUpdated&&e.push(`crud:updated`),a.indexDeleted&&e.push(`crud:deleted`),a.contentEvents&&e.push(`content`),e.push(...a.selectedTimelines??[]),e.length>0?e:[`crud:created`]},[a.indexCreated,a.indexUpdated,a.indexDeleted,a.contentEvents,a.selectedTimelines]),S=e=>{let n=new Set(b);n.has(e)?n.delete(e):n.add(e),t({selectedTimelines:[...n]})},C=async()=>{let e=l.trim();if(e){f(!0);try{await n(e),u(``),y({title:`Timeline created`,description:e})}catch(e){y({title:`Failed to create timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{f(!1)}}},w=async e=>{if(window.confirm(`Delete timeline "${e}"?\n\nThis removes all interval data for this timeline.`)){m(e);try{await r(e),y({title:`Timeline deleted`,description:e})}catch(e){y({title:`Failed to delete timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{m(null)}}},T=o.filter(e=>!e.startsWith(`crud:`)&&e!==`content`),E=Yy(a),D=E.length>0,O=(0,Q.useCallback)(e=>{t({customRanges:e,customRange:null,...e.length>0?{quickFilter:null}:{}})},[t]),k=e=>{t({quickFilter:a.quickFilter===e?null:e,customRanges:[],customRange:null})},A=e=>{t({customRanges:E.filter((t,n)=>n!==e),customRange:null})},j=(e,t)=>(0,$.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,$.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!D;return(0,$.jsx)(`button`,{type:`button`,onClick:()=>k(e),className:J(`text-xs px-1.5 py-1 rounded-md transition-colors truncate`,r?`bg-primary text-primary-foreground font-medium`:`bg-muted/50 text-foreground hover:bg-muted`),title:e,children:t?YC[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,$.jsx)(lw,{quickFilterKey:a.quickFilter,activeRangeCount:E.length,onSelectRanges:O,histogramNames:x}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,$.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:J(`px-2 py-0.5 transition-colors`,h===`quick`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Quick filters`,children:(0,$.jsx)(H,{className:`w-3 h-3`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:J(`px-2 py-0.5 transition-colors`,h===`calendar`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Calendar range picker`,children:(0,$.jsx)(B,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,$.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,$.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),qC.map((e,t)=>j(e,t===0)),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),className:`flex items-center gap-1 text-[11px] text-muted-foreground/70 hover:text-muted-foreground pt-1 transition-colors`,children:[(0,$.jsx)(Xe,{className:J(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&JC.map(e=>j(e,!1))]}):(0,$.jsx)(dw,{ranges:E,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:sw(E,e),customRange:null,quickFilter:null})}),D&&(0,$.jsx)(`div`,{className:`mt-2 space-y-1`,children:E.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-md bg-primary/10 border border-primary/30 px-2.5 py-1.5`,children:[(0,$.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>A(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,$.jsx)(G,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(fw,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:KC(`crud:created`)}),(0,$.jsx)(fw,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:KC(`crud:updated`)}),(0,$.jsx)(fw,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:KC(`crud:deleted`)}),(0,$.jsx)(fw,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:KC(`content`)})]}),(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,$.jsx)(P,{className:`w-3 h-3`})})]}),c?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):T.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,$.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:T.map(e=>{let t=b.has(e),n=KC(e);return(0,$.jsxs)(`div`,{className:J(`flex items-center gap-2.5 group rounded-md px-2 py-1.5 cursor-pointer transition-colors`,t?`bg-muted/60`:`hover:bg-muted/30`),onClick:()=>S(e),children:[(0,$.jsx)(`div`,{className:J(`shrink-0 w-4 h-4 rounded border-2 flex items-center justify-center transition-colors`,!t&&`border-muted-foreground/40 bg-transparent group-hover:border-muted-foreground/70`),style:t?{backgroundColor:n,borderColor:n}:void 0,children:t&&(0,$.jsx)(`svg`,{className:J(`w-2.5 h-2.5`,Pm(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,$.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,$.jsx)(`span`,{className:`shrink-0 text-[10px] px-1 py-0.5 rounded bg-muted text-muted-foreground select-none`,title:`Observed granularity for "${e}" — each entry is indexed at its own precision (a bare year at year cells, a full date at day cells)`,children:(s[e]??[]).join(`·`)}),(0,$.jsx)(`button`,{type:`button`,disabled:p===e,onClick:t=>{t.stopPropagation(),w(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:`Delete timeline "${e}"`,children:p===e?(0,$.jsx)(Yn,{className:`w-3 h-3 animate-spin`}):(0,$.jsx)(nt,{className:`w-3 h-3`})})]},e)})}),(0,$.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,$.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&C(),placeholder:`New timeline (e.g. wikipedia, trips)…`,title:`A timeline is a named time axis. Entries index at their own precision — a bare year at year granularity, a full date at day granularity — nothing to configure.`,className:`flex-1 px-2 py-1 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`}),(0,$.jsx)(`button`,{type:`button`,onClick:C,disabled:d||!l.trim(),className:`shrink-0 p-1.5 rounded-md bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 touch-target`,title:`Create timeline`,children:d?(0,$.jsx)(Yn,{className:`w-3.5 h-3.5 animate-spin`}):(0,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]})]})]})]})}var mw={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},hw=`data/dataset/default`;function gw(e){let t=new Map;for(let n of e){let e=n.startsWith(`data/backend/`)?`data/backend`:n.startsWith(`data/mime/`)?`data/mime`:n.startsWith(`data/dataset/`)?`data/dataset`:n.split(`/`)[0];t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}var _w=[`off`,`anyOf`,`allOf`,`noneOf`];function vw(e){return _w[(_w.indexOf(e)+1)%_w.length]}var yw=[{m:`anyOf`,label:`any`,on:`bg-info text-info-foreground`},{m:`allOf`,label:`all`,on:`bg-success text-success-foreground`},{m:`noneOf`,label:`not`,on:`bg-destructive text-destructive-foreground`}];function bw({mode:e,onSet:t}){return(0,$.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:yw.map(n=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:J(`px-2 py-0.5 text-[11px] font-medium transition-colors`,e===n.m?n.on:`bg-transparent text-muted-foreground hover:bg-muted hover:text-foreground`),title:`${n.label}: ${n.m}`,children:n.label},n.m))})}function xw({keys:e,modeOf:t,onCycle:n}){return e.length?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=fC(e),a=t(e),o=yw.find(e=>e.m===a);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:J(`relative flex flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border p-3 min-h-[4.5rem] transition-colors select-none`,a===`off`?`border-border bg-muted/40 text-foreground hover:bg-muted`:a===`anyOf`?`border-info bg-info/10 text-foreground`:a===`allOf`?`border-success bg-success/10 text-foreground`:`border-destructive bg-destructive/10 text-foreground`),children:[o&&(0,$.jsx)(`span`,{className:J(`absolute right-1.5 top-1.5 rounded px-1 py-0.5 text-[9px] font-semibold leading-none`,o.on),children:o.label}),(0,$.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function Sw(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=zs(),{availableBitmaps:o,bitmapsLoading:s,filters:c}=e,l=new Set(c.features.allOf),u=new Set(c.features.anyOf),d=new Set(c.features.noneOf),f=e=>l.has(e)?`allOf`:u.has(e)?`anyOf`:d.has(e)?`noneOf`:`off`,[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(null),{showToast:_}=Vr(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==hw){let t=e.slice(13);if(!window.confirm(`Drop dataset "${t}"?\n\nALL documents stamped with this dataset will be PERMANENTLY DELETED. Documents in other datasets (or the default dataset) are unaffected. Re-ingesting recreates the dataset from scratch.`))return;g(e);try{let n=await a(e);_({title:`Dataset dropped`,description:`"${t}": ${n} document(s) deleted`})}catch(e){_({title:`Dataset drop failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}return}if(!e.startsWith(`data/`)&&window.confirm(`Delete bitmap "${e}"?\n\nThis removes the bitmap from the database. Documents are unaffected, but any features/filters relying on this bitmap will lose their grouping.`)){g(e);try{await i(e),_({title:`Bitmap deleted`,description:e})}catch(e){_({title:`Delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}}};if(s)return(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Yn,{className:`w-4 h-4 animate-spin text-muted-foreground`})});let y=[...c.features.allOf,...c.features.anyOf,...c.features.noneOf],b=[...new Set([...o,...y])];if(!b.length)return(0,$.jsx)(`div`,{className:`p-4 text-xs text-muted-foreground text-center py-10`,children:`No feature bitmaps found`});let x=p.trim().toLowerCase(),S=x?b.filter(e=>e.toLowerCase().includes(x)):b,C=S.filter(e=>e.startsWith(uC)).sort((e,t)=>{let n=Object.keys(dC),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=gw(S.filter(e=>!e.startsWith(uC))),T=w.get(`data/dataset`);return T&&!T.includes(hw)&&(!x||hw.includes(x))&&T.unshift(hw),(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(tr,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,$.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:`Search features…`,className:`w-full pl-7 pr-3 py-1.5 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:n,disabled:!r,className:`flex items-center gap-1.5 w-full justify-center px-2.5 py-1.5 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,$.jsx)(G,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,$.jsx)(xw,{keys:C,modeOf:f,onCycle:e=>t(e,vw(f(e)))}),w.size===0&&C.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:mw[e]??e}),(0,$.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===hw,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,$.jsxs)(`div`,{onClick:()=>t(e,vw(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,vw(o)))},className:J(`flex items-center gap-2 group rounded-md pl-2 pr-1.5 py-1 border-l-2 transition-colors cursor-pointer select-none`,n%2==0?`bg-muted/50`:`bg-transparent`,`hover:bg-muted`,o===`off`?`border-l-transparent`:o===`anyOf`?`border-l-blue-500 !bg-info/10`:o===`allOf`?`border-l-emerald-500 !bg-success/10`:`border-l-rose-500 !bg-destructive/10`),children:[(0,$.jsxs)(`span`,{className:`flex-1 min-w-0 text-xs font-mono text-foreground truncate`,title:i?`Virtual dataset: documents not stamped with any dataset. Included by default; "not" hides them, "all" shows only them.`:e,children:[e,i&&(0,$.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,$.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,$.jsx)(bw,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,$.jsx)(`button`,{type:`button`,disabled:h===e,onClick:t=>{t.stopPropagation(),v(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:a?`Drop dataset "${e.slice(13)}" (DELETES its documents)`:`Delete bitmap "${e}" from database`,"aria-label":a?`Drop dataset ${e}`:`Delete bitmap ${e}`,children:h===e?(0,$.jsx)(Yn,{className:`w-3.5 h-3.5 animate-spin`}):(0,$.jsx)(nt,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function Cw(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i,setLiveEnabled:a}=zs(),{toolsTab:o,isDirty:s,isSaving:c,activeContextType:l,savedSearchQuery:u}=e,d=pl(),f=(new URLSearchParams(d.search).has(`q`)||new URLSearchParams(d.search).has(`search`)?wC(d.search):u?[u]:[])[0]||``,p=l!==null&&f.trim()!==(u||``),m=e.filters.sort??Ky.sort,h=m.sortBy!==Ky.sort.sortBy||m.order!==Ky.sort.order,g=i||!!f.trim()||h,_=(0,$.jsxs)($.Fragment,{children:[g&&(0,$.jsxs)(`button`,{type:`button`,onClick:r,title:`Clear all active filters`,className:`flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(G,{className:`h-3 w-3`}),`Clear`]}),l!==null&&g&&(s||p)&&(0,$.jsxs)(`button`,{type:`button`,onClick:n,disabled:c,className:`flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary disabled:opacity-60`,children:[c?(0,$.jsx)(Yn,{className:`h-3 w-3 animate-spin`}):(0,$.jsx)(Be,{className:`h-3 w-3`}),`Save filters`]})]});return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex border-b border-border shrink-0`,children:[{id:`features`,label:`Features`},{id:`timeline`,label:`Timeline`},{id:`map`,label:`Map`},{id:`lens`,label:`Lens`}].map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:J(`flex-1 py-2.5 text-xs transition-colors`,o===e.id?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),l===`context`&&(0,$.jsxs)(`div`,{className:`shrink-0 space-y-1 border-b border-border px-3 py-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex min-h-8 flex-wrap items-center justify-between gap-x-3 gap-y-1`,children:[(0,$.jsxs)(`label`,{className:`flex min-h-8 cursor-pointer items-center gap-2 text-sm font-medium`,title:`Live view updates every device bound to this context. Save filters to keep the current view.`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 accent-current`,checked:e.liveEnabled,disabled:new URLSearchParams(d.search).has(`ownerId`),onChange:e=>{a(e.target.checked)}}),`Live view`]}),(0,$.jsx)(`div`,{className:`ml-auto flex items-center gap-2`,children:_})]}),e.liveError&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-destructive`,children:e.liveError})]}),l!==`context`&&g&&(0,$.jsx)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:_}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[o===`features`&&(0,$.jsx)(Sw,{}),o===`timeline`&&(0,$.jsx)(pw,{}),o===`map`&&(0,$.jsx)(RC,{}),o===`lens`&&(0,$.jsx)(UC,{})]})]})}function ww(){let e=xS(),t=es()?.state,n=!!t&&(e?.mode===`context`?t.activeContextType===`context`&&t.activeContextId===e.contextId:e?.mode===`workspace`?t.activeContextType!==`context`&&t.activeWorkspaceName===e.workspaceName&&t.activeTreeName===e.treeName&&t.activeContextPath===e.path:!t.activeWorkspaceName&&!t.activeContextId),r=!n&&e?.mode===`context`?e.contextId:null;return(0,Q.useEffect)(()=>{if(!r)return;let e=`context:${r}`,t=()=>hd.emit(`subscribe`,{channel:e}),n=hd.on(`connect`,t);return t(),()=>{n(),hd.emit(`unsubscribe`,{channel:e})}},[r]),n?(0,$.jsx)(Cw,{}):(0,$.jsx)(CC,{target:e,children:(0,$.jsx)(QS,{children:(0,$.jsx)(Cw,{})})})}function Tw({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=__(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,$.jsxs)(`div`,{className:`group relative overflow-hidden rounded-(--card-radius) border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,$.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,$.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,$.jsx)(le,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,$.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:ES(e.updatedAt||e.createdAt)})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Delete ${o}`,className:`absolute right-1.5 top-1.5 rounded-md bg-background/80 p-1 opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})}function Ew({autoAdd:e}){let t=xS(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=DS(t,Mi),[c,l]=(0,Q.useState)(e?`new`:null),{showErrorToast:u}=Wr();return t?(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,$.jsx)(Tw,{doc:e,scope:a,onOpen:()=>l(e),onRemove:()=>{confirm(`Delete "${String(e.data?.title??`Sketch`)}"?`)&&s(e.id).catch(e=>u(e instanceof Error?e.message:`Failed to delete sketch`))}},`${e.id}:${e.checksumArray?.[0]??``}`))}),c&&a&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,$.jsx)(by,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var Dw=[{id:`filters`,label:`Filters`,icon:Un,modes:[`context`,`global`],description:`Search and filter a workspace or a live context`,Component:ww},{id:`notes`,label:`Notes`,icon:Kn,modes:[`context`],description:`All notes in the current context, editable in place`,Component:AS},{id:`todo`,label:`Todos`,icon:Vt,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:FS},{id:`sketch`,label:`Sketch`,icon:le,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:Ew},{id:`lens`,label:`Lens`,icon:cr,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:lC}];function Ow(e){return Dw.filter(t=>t.modes.includes(e))}function kw({target:e,children:t}){return(0,$.jsx)(bS.Provider,{value:e,children:t})}function Aw({children:e}){let[t,n]=(0,Q.useState)(null),r=(0,Q.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,Q.useCallback)(()=>n(null),[]),a=(0,Q.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,$.jsxs)(dy.Provider,{value:a,children:[e,(0,$.jsx)(Hy,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var jw=`universe`;function Mw(){let{appletId:e}=bl(),[t,n]=zu(),r=Dw.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||jw,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,Q.useMemo)(()=>i?{mode:`context`,contextId:i}:{mode:`workspace`,workspaceName:a,path:o,treeName:s,treeType:s===`directory`?`directory`:`context`},[i,a,o,s]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{Ni().then(d).catch(()=>d([])),ps().then(p).catch(()=>p([]))},[]);let[m,h]=(0,Q.useState)(o),[g,_]=(0,Q.useState)(o);g!==o&&(_(o),h(o));let v=e=>{let r=new URLSearchParams(t);r.delete(`add`);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r,{replace:!0})};if(!r)return(0,$.jsxs)(`div`,{className:`flex h-viewport flex-col items-center justify-center gap-3 surface-desk`,children:[(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,$.jsx)(`div`,{className:`flex gap-2`,children:Dw.map(e=>(0,$.jsx)(Nu,{to:`/apps/${e.id}`,className:`rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted`,children:e.label},e.id))})]});let y=i?`context`:`path`;return(0,$.jsx)(Aw,{children:(0,$.jsx)(QS,{children:(0,$.jsxs)(`div`,{className:`flex h-viewport flex-col surface-desk p-shell gap-shell`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 rounded-xl border bg-card px-3 py-2 shadow-elevation-2`,children:[(0,$.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,$.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:J(`px-2.5 py-1 text-xs capitalize transition-colors`,y===e?`bg-foreground text-background`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:e},e))}),y===`path`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`select`,{value:a,onChange:e=>v({workspace:e.target.value,path:`/`}),className:`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Workspace`,children:[!u.some(e=>e.name===a)&&(0,$.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,$.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,$.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),onBlur:()=>{let e=m.trim()||`/`;e!==o&&v({path:e})},onKeyDown:e=>{e.key===`Enter`&&e.target.blur()},spellCheck:!1,placeholder:`/`,className:`h-7 w-40 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,"aria-label":`Path`})]}):(0,$.jsxs)(`select`,{value:i??``,onChange:e=>v({context:e.target.value}),className:`h-7 max-w-56 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Context`,children:[!i&&(0,$.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,$.jsx)(`div`,{className:`grow`}),(0,$.jsx)(Nu,{to:`/home`,className:`flex items-center gap-1 rounded-md p-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Open the full Canvas app`,children:(0,$.jsx)(ve,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-elevation-2`,children:y===`context`&&!i?(0,$.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:[`Pick a context above to bind `,r.label,` to it.`]}):(0,$.jsx)(kw,{target:l,children:(0,$.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})})})}var Nw=`false`,Pw=`false`,Fw=Nw===`true`,Iw=Pw===`true`;function Lw(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,Fw||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await g(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!Iw){if(Fw)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 Rw=new Set,zw=!1,Bw=Lw({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){zw=!0,Rw.forEach(e=>e())}});function Vw(e){return Rw.add(e),zw&&e(),()=>{Rw.delete(e)}}function Hw(){Bw(!0)}function Uw(){let[e,t]=(0,Q.useState)(!1),[n,r]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>Vw(()=>t(!0)),[]),!e||n?null:(0,$.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,$.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>Hw(),className:`flex items-center gap-1 rounded-full bg-foreground px-3 py-1 text-xs font-medium text-background hover:bg-foreground/90`,children:[(0,$.jsx)(P,{className:`h-3 w-3`}),` Reload`]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(!0),"aria-label":`Not now`,className:`rounded-full p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})})}var Ww;function Gw(){let[e,t]=(0,Q.useState)({local:!1});return(0,Q.useEffect)(()=>{Ww??=fetch(`${Lr}/runtime/capabilities`).then(async e=>e.ok?(await e.json()).payload:{local:!1}).catch(()=>({local:!1}));let e=!0;return Ww.then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Kw(e){return e.isShared||e.type===`shared`?e.id:e.name}function qw({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=gl();return(0,$.jsxs)(`div`,{className:J(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,$.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>i?i():s(r),"aria-label":`Back`,title:`Back`,className:`mt-1 shrink-0 text-muted-foreground transition-colors hover:text-foreground touch-target`,children:(0,$.jsx)(Jn,{className:`h-5 w-5`})}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h1`,{className:J(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,$.jsx)(`p`,{className:J(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(`/`),"aria-label":`Close`,title:`Close`,className:`order-2 flex h-9 w-9 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-4 w-4`})}),n&&(0,$.jsx)(`div`,{className:`order-3 flex w-full items-center gap-2 max-sm:flex-wrap sm:order-1 sm:w-auto`,children:n})]})}function Jw({className:e}){let t=gl();return(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:J(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,e),children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})}function Yw({onBack:e,title:t=`Back`,className:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:J(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,n),children:(0,$.jsx)(Jn,{className:`h-4 w-4`})})}var Xw=180;function Zw({x:e,y:t,current:n,onChange:r,onClose:i}){Fp(i);let[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)({q:``,list:[]}),[d,p]=(0,Q.useState)(!0),m=(0,Q.useRef)(null),h=(0,Q.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&i(),h.current={name:e,t}};(0,Q.useEffect)(()=>{m.current?.focus()},[]),(0,Q.useEffect)(()=>{let e=!0;return gm().then(t=>{e&&(c(t),p(!1))}),()=>{e=!1}},[]),(0,Q.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{_m(e).then(t=>{u({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=l.q===_,y=_!==``&&!v,b=(0,Q.useMemo)(()=>(_?v?l.list:[]:s).slice(0,Xw),[_,v,l.list,s]),x=(0,Q.useRef)(null),[S,C]=(0,Q.useState)({x:e,y:t});return(0,Q.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,Ip.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,$.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,$.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,$.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[vm.map(e=>(0,$.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:J(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,$.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:J(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,$.jsx)(G,{className:`w-3 h-3`})}),(0,$.jsx)(`label`,{title:`Custom color`,className:J(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!vm.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!vm.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,$.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,$.jsx)(`input`,{ref:m,value:a,onChange:e=>o(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),d||y?(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,$.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,$.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:J(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,$.jsx)(G,{className:`w-4 h-4`})}),b.map(e=>(0,$.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:J(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,$.jsx)(f,{icon:e,width:18,height:18,color:n.color})},e))]}),!d&&!y&&b.length===0&&(0,$.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function Qw(e,t,n){let r=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{r.current=n}),(0,Q.useEffect)(()=>{if(!e)return;e.emit(`subscribe`,{channel:t});let n=Object.keys(r.current).map(t=>{let n=(...e)=>{r.current[t]?.(...e)};return e.on(t,n),[t,n]});return()=>{e.emit(`unsubscribe`,{channel:t});for(let[t,r]of n)e.off(t,r)}},[e,t])}function $w({title:e,onClose:t,children:n}){return(0,$.jsxs)(`div`,{className:`space-y-4 rounded-(--card-radius) border bg-card p-4 shadow-elevation-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),n]})}function eT({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,Q.useState)(!1),l=e.status===`active`,u=e.type===`universe`||e.name===`universe`,d=e.status===`error`,f=e.status===`not_found`,p=e.isShared===!0||e.type===`shared`,m=e.ownerEmail||e.owner,h=typeof e.sharedVia==`object`&&e.sharedVia?e.sharedVia:null,g=h?.permissions||[],_=g.includes(`admin`)?`admin`:g.includes(`write`)?`read/write`:`read-only`,v=h?.type===`group`?`via group ${h.principal}`:h?.type===`user`?`shared with you`:``,y=e.origin===`remote`,b=e.status===`offline`,x=Nm(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(Ku,{className:`relative ${S}`,style:C,children:[(0,$.jsx)(qu,{children:(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,$.jsx)(Ju,{className:`truncate`,children:e.label||e.name}),(0,$.jsx)(Yu,{children:p?`Shared from ${m}`:e.description||``})]}),(0,$.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>n(Kw(e)),title:`Stop Workspace`,disabled:d||f,children:(0,$.jsx)(zn,{className:`h-4 w-4`})}):(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>t(Kw(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,$.jsx)(xe,{className:`h-4 w-4`})}),l&&(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>r(Kw(e)),title:`Enter Workspace`,disabled:d||f,children:(0,$.jsx)(_t,{className:`h-4 w-4`})}),a&&(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:Op(e)?`Workspace settings`:`Workspace settings require admin access`,"aria-label":`Workspace settings`,disabled:f||!Op(e),children:(0,$.jsx)(yn,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,$.jsx)(rn,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,$.jsxs)(Ir,{open:s,onOpenChange:c,children:[(0,$.jsx)(kr,{asChild:!0,children:(0,$.jsx)(Z,{variant:`outline`,size:`icon`,title:y?`Remove remote workspace reference`:`Delete Workspace`,disabled:l&&!y,className:`text-destructive hover:text-destructive hover:bg-destructive/10`,children:(0,$.jsx)(nt,{className:`h-4 w-4`})})}),(0,$.jsxs)(Or,{children:[(0,$.jsxs)(Fr,{children:[(0,$.jsx)(Cr,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,$.jsx)(Sr,{children:y?(0,$.jsxs)($.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,$.jsx)(`br`,{}),(0,$.jsx)(`br`,{}),`The workspace itself stays untouched on `,e.remote?.url||e.host,`; only the stored share token and the local cache entry are dropped.`]}):(0,$.jsxs)($.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,$.jsx)(`br`,{}),(0,$.jsx)(`br`,{}),(0,$.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,$.jsxs)(Mr,{children:[(0,$.jsx)(Pr,{children:`Cancel`}),(0,$.jsx)(jr,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,$.jsx)(Xu,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`div`,{className:`h-3 w-3 rounded-full ${(()=>{switch(e.status){case`active`:return`bg-success`;case`inactive`:case`available`:return`bg-muted-foreground`;case`error`:case`offline`:return`bg-destructive`;case`not_found`:return`bg-muted-foreground`;default:return`bg-accent`}})()}`}),(0,$.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:(()=>{switch(e.status){case`active`:return`Active`;case`inactive`:return`Inactive`;case`error`:return`Error`;case`not_found`:return`Not Found`;case`available`:return`Available`;case`removed`:return`Removed`;case`destroyed`:return`Destroyed`;case`offline`:return`Offline`;default:return e.status}})()}),u&&(0,$.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,$.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:e.remote?.url?`${e.remote.url} (${(e.remote.permissions||[]).join(`, `)||`no permissions`})`:void 0,children:[`Remote · `,e.host]}),p&&(0,$.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:[v,`${_} access`].filter(Boolean).join(` · `),children:[`Shared · `,_]})]})})]})})}function tT(){let[e,t]=zu(),n=e.get(`create`)===`1`,[r,i]=(0,Q.useState)(n),[a,o]=(0,Q.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,Q.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var nT=`canvas:lastPath`,rT=200;function iT(){try{let e=localStorage.getItem(nT);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function aT(e){try{localStorage.setItem(nT,JSON.stringify(e))}catch{}}function oT(e,t,n){if(!e)return;let r=iT(),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>rT)for(let e of a.slice(0,a.length-rT))delete r[e];aT(r)}function sT(e){let t=iT()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function cT(e){let t=sT(e);return t?Fx(e,t.path,t.tree):`/workspaces/${e}`}var lT=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:V,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:or,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:mr,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:Re,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:Fn,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:Dn,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:jn,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:ie,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:mn,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/auth`,icon:k,label:`Authentication`,description:`Configure sign-in backends: local passwords, LDAP and IMAP.`},{path:`/admin/embedding`,icon:Dn,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:fr,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:ur,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:rt,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:ct,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:F,label:`About Canvas`,description:`View versions and information about this installation.`}]}],uT=[`/settings`,...lT.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function dT(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var fT=[{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.`}],pT=`canvas:layout`;function mT(){try{return localStorage.getItem(pT)===`strip`?`strip`:`classic`}catch{return`classic`}}var hT=mT(),gT=new Set;function _T(){for(let e of gT)e()}function vT(){return hT}function yT(e){try{e===`strip`?localStorage.setItem(pT,e):localStorage.removeItem(pT)}catch{}hT=e,_T()}function bT(e){gT.add(e);let t=t=>{(t.key===pT||t.key===null)&&(hT=mT(),e())};return window.addEventListener(`storage`,t),()=>{gT.delete(e),window.removeEventListener(`storage`,t)}}function xT(){return(0,Q.useSyncExternalStore)(bT,vT,()=>`classic`)}var ST=[{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.`}],CT=`canvas:layout-nav`;function wT(){try{let e=localStorage.getItem(CT);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var TT=wT(),ET=new Set;function DT(){return TT}function OT(e){try{e===`shift`?localStorage.removeItem(CT):localStorage.setItem(CT,e)}catch{}TT=e;for(let e of ET)e()}function kT(e){ET.add(e);let t=t=>{(t.key===CT||t.key===null)&&(TT=wT(),e())};return window.addEventListener(`storage`,t),()=>{ET.delete(e),window.removeEventListener(`storage`,t)}}function AT(){return(0,Q.useSyncExternalStore)(kT,DT,()=>`shift`)}function jT(e,t){let n=e.ctrlKey||e.metaKey;switch(t){case`shift`:return e.shiftKey&&!e.altKey&&!n;case`alt`:return e.altKey&&!e.shiftKey&&!n;case`ctrl`:return n&&!e.shiftKey&&!e.altKey;case`none`:return!e.shiftKey&&!e.altKey&&!n}}function MT(){return window.matchMedia(`(max-width: 767px)`).matches&&vT()!==`strip`}var NT=(0,Q.createContext)(null);function PT(){let e=(0,Q.useContext)(NT);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function FT(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`||uT.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function IT(e,t){let n=pl(),r=gl(),i=(0,Q.useRef)(!1),a=(0,Q.useRef)(e);return(0,Q.useEffect)(()=>{a.current=e},[e]),(0,Q.useLayoutEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=FT(n.pathname);if(e===null&&n.pathname!==`/`&&vT()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=MT(),c=s?n.state?.canvasMenu:void 0;t(c?{type:`RESTORE_MENU`,menu:c}:{type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,n.state,t]),{navigateToEntity:(0,Q.useCallback)(e=>{i.current=!0,r(e)},[r])}}function LT(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=zr(xr.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 RT=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function zT(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await Aa(e,`/${n}`,!0,a);let t=Tm(`/${n}`);t&&await zi(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return Da(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function BT(){let[e,t]=(0,Q.useState)(new Set),[n,r]=(0,Q.useState)(`context`);return{selected:e,setSelected:t,tree:n,setTree:r,toggle:e=>{t(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}}}function VT({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,$.jsx)(`div`,{className:`mt-3 grid gap-1.5 ${o?`grid-cols-1`:`grid-cols-2 sm:grid-cols-3 md:grid-cols-4`}`,children:RT.map(n=>{let r=ym[n.toLowerCase()];return(0,$.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded border px-2 py-1.5 text-sm hover:bg-accent/50`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,$.jsx)(f,{icon:r.icon,width:16,height:16,color:r.color}),(0,$.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var HT=[{value:`full`,icon:ne,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:Pe,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 UT({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,$.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:HT.map(i=>{let a=e===i.value,o=i.icon;return(0,$.jsxs)(`button`,{id:`${r}-${i.value}`,type:`button`,role:`radio`,"aria-checked":a,disabled:n,onClick:()=>t(i.value),className:`flex w-full gap-2 rounded-md border p-2.5 text-left transition-colors disabled:opacity-50 ${a?`border-primary bg-accent/40`:`hover:bg-accent/20`}`,children:[(0,$.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,$.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,$.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,$.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function WT(){let[e,t]=(0,Q.useState)(`full`),[n,r]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let e=!0;return X.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 GT({disabled:e}){let[t,n]=(0,Q.useState)(0),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),d=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=!0;return d.current?.id!==t&&(d.current={id:t,promise:Ma()}),d.current.promise.then(t=>{if(!e)return;let n=[...t.discovered,...t.adopted];o(e=>[...new Map([...e,...n].map(e=>[e.id,e])).values()]),c(t),(n.length||t.updated.length||t.missing.length)&&window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}).catch(t=>{e&&u(t instanceof Error?t.message:`Workspace scan failed`)}).finally(()=>{e&&i(!1)}),()=>{e=!1}},[t]),(0,$.jsxs)(`section`,{className:`space-y-2 rounded-md border p-3`,"aria-label":`Find workspace folders`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`text-sm font-medium`,children:`Workspaces folder`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copied a workspace folder here? Scan to add it to your workspaces.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:e||r,onClick:()=>{i(!0),u(``),n(e=>e+1)},children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${r?`animate-spin`:``}`}),r?`Scanning…`:`Rescan`]})]}),r&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Looking for workspace folders…`}),!r&&!l&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:a.length?`Found ${a.length} ${a.length===1?`workspace`:`workspaces`}. Added to your workspace list.`:`No new workspace folders found.`}),a.length>0&&(0,$.jsx)(`ul`,{className:`space-y-2`,children:a.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(Nu,{className:`text-sm font-medium underline underline-offset-2`,to:`/workspaces/${encodeURIComponent(e.name)}`,children:e.label||e.name}),(0,$.jsx)(`p`,{className:`break-all text-xs text-muted-foreground`,children:e.dir})]},e.id))}),l&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:l}),!!s?.skipped.length&&(0,$.jsxs)(`details`,{className:`text-sm text-muted-foreground`,children:[(0,$.jsxs)(`summary`,{children:[s.skipped.length,` `,s.skipped.length===1?`folder could`:`folders could`,` not be added`]}),(0,$.jsx)(`ul`,{className:`mt-1 space-y-1`,children:s.skipped.map(e=>(0,$.jsxs)(`li`,{className:`break-all`,children:[e.dir,`: `,e.reason]},e.dir))})]})]})}function KT({name:e,label:t,setName:n,setLabel:r,disabled:i=!1}){return(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace name`,(0,$.jsx)(Y,{required:!0,pattern:`[a-zA-Z0-9]([a-zA-Z0-9_]|-)*`,placeholder:`my-workspace`,value:e,onChange:e=>n(e.target.value),disabled:i}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Used in addresses. Archive imports also use it as the folder name.`})]}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Display label`,(0,$.jsx)(Y,{required:!0,placeholder:`My Workspace`,value:t,onChange:e=>r(e.target.value),disabled:i})]})]})}function qT({onImported:e,disabled:t=!1}){let[n,r]=(0,Q.useState)(`upload`),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(null),b=t||f,x=async t=>{t.preventDefault(),p(!0),_(``),y(null),h(`Starting…`);let r={name:c.trim(),label:u.trim()},a=e=>h(Ka[e.phase]||e.phase);try{let t=n===`upload`?await wa(i,e=>h(e<1?`Uploading… ${Math.round(e*100)}%`:`Extracting…`),a,r):await eo(o.trim(),r,a);y(t),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e?.(t)}catch(e){_(e instanceof Error?e.message:`Workspace import failed`)}finally{p(!1)}};return(0,$.jsxs)(`form`,{className:`space-y-3`,onSubmit:e=>void x(e),children:[(0,$.jsx)(GT,{disabled:b}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Import from`,(0,$.jsxs)(`select`,{value:n,disabled:b,onChange:e=>r(e.target.value),className:`rounded-md border bg-background p-2`,children:[(0,$.jsx)(`option`,{value:`upload`,children:`Upload an archive`}),(0,$.jsx)(`option`,{value:`path`,children:`Path on this server`})]})]}),n===`upload`?(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace archive`,(0,$.jsx)(Y,{required:!0,type:`file`,accept:`.tar.gz,.tgz,.tar.bz2,.tbz2,.tbz`,disabled:b,onChange:e=>a(e.target.files?.[0]||null)})]}):(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Server path`,(0,$.jsx)(Y,{required:!0,placeholder:`/tmp/workspace.tar.gz`,value:o,disabled:b,onChange:e=>s(e.target.value)}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`An archive or workspace folder on the server. Archives are extracted into your Workspaces directory.`})]}),(0,$.jsx)(KT,{name:c,label:u,setName:l,setLabel:d,disabled:b}),(0,$.jsxs)(Z,{type:`submit`,disabled:b||!c.trim()||!u.trim()||(n===`upload`?!i:!o.trim()),children:[f?(0,$.jsx)(P,{className:`mr-2 h-4 w-4 animate-spin`}):(0,$.jsx)(Qe,{className:`mr-2 h-4 w-4`}),f?`Importing…`:`Import workspace`]}),f&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:m}),g&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),v&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Imported `,v.label||v.name,`.`]})]})}function JT(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 YT(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function XT(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 ZT(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function QT(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(Am()),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(``),[_,v]=WT(),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),E=Gw(),[D,O]=tT(),k=BT(),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(!1),[R,z]=(0,Q.useState)(null),{showToast:ee}=Vr(),te=gl(),ne=l_(),{openM2Drawer:B}=PT(),re=LT();Qw(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,Q.useEffect)(()=>{let e=async()=>{try{r(!0);let e=await Ni();t(JT(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),ee({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}};e();let n=()=>{e()};return window.addEventListener(`workspaces:refresh`,n),()=>{window.removeEventListener(`workspaces:refresh`,n)}},[re,ee]);let ie=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await da({name:o,description:c||void 0,color:u,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),k.selected.size>0){try{await so(e.name);let{ok:t,failed:n}=await zT(e.name,Array.from(k.selected),k.tree);n&&ee({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),ee({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}k.setSelected(new Set)}s(``),l(``),d(Am()),m(null),g(``),ee({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),O(!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`}ee({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},ae=async e=>{if(e.preventDefault(),R)try{let e={label:R.label,description:R.description,color:R.color,icon:R.icon??null};await Eo(R.name,e),t(t=>t.map(t=>t.id===R.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),ee({title:`Success`,description:`Workspace '${R.label}' details updated.`}),z(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;ee({title:`Error`,description:t,variant:`destructive`})}},oe=e=>{z(e)},V=async e=>{try{await no(e.name),t(t=>t.filter(t=>t.id!==e.id)),ee({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;ee({title:`Error`,description:t,variant:`destructive`})}},H=async e=>{try{let n=await so(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),ee({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`}ee({title:`Error`,description:t,variant:`destructive`})}},U=async e=>{try{let n=await ha(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),ee({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`}ee({title:`Error`,description:t,variant:`destructive`})}},se=e=>{te(cT(e))},{rowProps:W,handleProps:ce,draggingIndex:le,insertLineClass:ue}=ZT((n,r)=>{let i=YT(e,n,r);t(i),XT(i,(e,t)=>Eo(Kw(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&ee({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{variant:`outline`,onClick:()=>j(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>F(e=>!e),children:`Import workspace`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>N(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>L(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!E.local&&!D&&(0,$.jsxs)(Z,{onClick:()=>O(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,$.jsx)(sn,{className:`h-4 w-4 sm:mr-2`}),(0,$.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),!E.local&&D&&(0,$.jsx)($w,{title:`Create New Workspace`,onClose:()=>O(!1),children:(0,$.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,$.jsx)(Y,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,disabled:C,onClick:e=>b({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:p||`ph:stack-fill`,width:22,height:22,color:Nm(u)})}),(0,$.jsx)(Y,{id:`workspace-color`,type:`color`,value:u,onChange:e=>d(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>d(Am()),disabled:C,children:`Randomize`})]}),y&&(0,$.jsx)(Zw,{x:y.x,y:y.y,current:{icon:p??void 0,color:u},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&d(e.color)},onClose:()=>b(null)}),(0,$.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,$.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`How the workspace directory is laid out on disk. Fixed once created.`}),(0,$.jsx)(UT,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,$.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,$.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,$.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`Ticked folders are created right after the workspace, with matching icons and colors.`}),(0,$.jsx)(VT,{selected:k.selected,onToggle:k.toggle,tree:k.tree,onTreeChange:k.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,$.jsxs)(Z,{type:`submit`,disabled:C||!o.trim(),children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),A&&(0,$.jsx)(eE,{}),I&&(0,$.jsx)(tE,{onClose:()=>L(!1),onChanged:async()=>{try{t(JT(await Ni()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),P&&(0,$.jsx)($w,{title:`Import workspace`,onClose:()=>F(!1),children:(0,$.jsx)(qT,{onImported:()=>F(!1)})}),M&&(0,$.jsx)($T,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),N(!1)},onClose:()=>N(!1)}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,$.jsx)(`div`,{className:`text-center text-destructive`,children:(0,$.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,$.jsx)(`div`,{className:`grid gap-4`,children:e.map((t,n)=>{let r={...t,createdAt:t.createdAt,updatedAt:t.updatedAt,color:t.color===null?void 0:t.color},i=Nm(t.color);return(0,$.jsxs)(`div`,{...W(n),className:`flex items-stretch rounded-lg ${ue(n,e.length)||``} ${le===n?`opacity-60`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,...ce(n),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:`hidden w-5 shrink-0 cursor-grab items-center justify-center rounded-l-lg active:cursor-grabbing md:flex ${i?``:`bg-muted`}`,style:i?{backgroundColor:i}:void 0,children:(0,$.jsx)(T,{className:`h-4 w-4 ${Pm(i)}`})}),(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,$.jsx)(eT,{workspace:r,onStart:H,onStop:U,onEnter:se,onEdit:oe,onSettings:e=>{ne?B(`workspaces`,`settings`,Kw(e)):te(`/workspaces/${Kw(e)}/settings/general`)},onDestroy:V})})]},t.id)})})]}),R&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,R.label]}),(0,$.jsxs)(`form`,{onSubmit:ae,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,$.jsx)(Y,{id:`edit-label`,value:R.label,onChange:e=>z(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`edit-description`,value:R.description||``,onChange:e=>z(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>S({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:R.icon||`ph:stack-fill`,width:22,height:22,color:Nm(R.color)})}),(0,$.jsx)(Y,{id:`edit-workspace-color`,type:`color`,value:R.color||`#FFFFFF`,onChange:e=>z(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>z(e=>e?{...e,color:Am()}:null),children:`Randomize Color`})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:!R.label?.trim(),children:`Save Changes`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>z(null),children:`Cancel`})]})]}),x&&(0,$.jsx)(Zw,{x:x.x,y:x.y,current:{icon:R.icon??void 0,color:R.color??void 0},onChange:e=>{z(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 $T({onImported:e,onClose:t}){let{showToast:n}=Vr(),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(``);return(0,$.jsx)($w,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,$.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault();let i;try{i=new URL(r.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}if(!a.trim().startsWith(`canvas-`)){n({title:`Error`,description:`Invalid access token (expected canvas-...)`,variant:`destructive`});return}f(!0),m(`Starting…`);try{let t=await Ga(i,a.trim(),e=>{m(Ka[e.phase]||e.phase)},{name:s.trim(),label:l.trim()});n({title:`Success`,description:`Workspace '${t.label||t.name}' imported from ${i}.`}),e(t)}catch(e){let t=e,r=t?.message||t?.payload?.message||`Failed to import remote workspace`;n({title:`Error`,description:r,variant:`destructive`})}finally{f(!1),m(``)}},className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:d}),(0,$.jsx)(Y,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:d}),(0,$.jsx)(Z,{type:`submit`,disabled:d||!r.trim()||!a.trim()||!s.trim()||!l.trim(),children:d?`Importing…`:`Import Workspace`})]}),(0,$.jsx)(KT,{name:s,label:l,setName:c,setLabel:u,disabled:d}),d&&p&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,$.jsx)(`strong`,{children:`copy`}),` of the workspace from the remote canvas-server into this one, where it then lives independently. The remote workspace is stopped while it is packed, and large workspaces can take several minutes — progress is shown above.`]})]})})}function eE(){let{showToast:e}=Vr(),[t,n]=(0,Q.useState)(``),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,$.jsx)(Y,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,$.jsx)(Z,{onClick:async()=>{if(!s(t.trim())){e({title:`Error`,description:`Invalid URL`,variant:`destructive`});return}if(!r.trim().startsWith(`canvas-`)){e({title:`Error`,description:`Invalid access token`,variant:`destructive`});return}o(!0);try{sessionStorage.setItem(`sharedToken:last`,r.trim());let e=new URLSearchParams({url:t.trim()}).toString();window.location.href=`/shared?${e}`}catch(t){e({title:`Error`,description:t instanceof Error?t.message:`Failed to open shared resource`,variant:`destructive`})}finally{o(!1)}},disabled:a||!t.trim()||!r.trim(),children:`Open`})]}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`We use your provided URL and token to fetch via the remote's public API.`})]})}function tE({onClose:e,onChanged:t}){let{showToast:n}=Vr(),r=gl(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)([]),f=(0,Q.useCallback)(async()=>{try{d(await wo())}catch{d([])}},[]);(0,Q.useEffect)(()=>{f()},[f]);let p=async e=>{e.preventDefault();let r;try{r=new URL(i.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}l(!0);try{let e=await 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 yi(e.id),await f(),t?.()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to remove remote workspace`,variant:`destructive`})}};return(0,$.jsxs)($w,{title:`Open a remote Workspace`,onClose:e,children:[(0,$.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,$.jsx)(Y,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,$.jsx)(Z,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,$.jsx)(`code`,{className:`font-mono text-xs`,children:`name@host`}),` — nothing is copied. Every call you make to it is forwarded to the remote with the share token (its permissions apply); document content and thumbnails are cached locally so they stay readable when the remote is offline. Use “Import remote…” if you want an independent local copy instead.`]})]}),u.length>0&&(0,$.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,$.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,$.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`remote`})]}),(0,$.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}var nE={membership:`keep`,propagation:`never`,targets:[],acceptPropagatedDeletions:!1},rE=e=>`/workspaces/${encodeURIComponent(e)}/trash/operations`,iE=(e,t)=>X.get(`${rE(e)}?${new URLSearchParams(Object.entries(t).map(([e,t])=>[e,String(t)]))}`),aE=(e,t,n,r={})=>X.post(`${rE(e)}/${n}`,{ids:t,...r}),oE=(e,t,n,r)=>X.patch(`/workspaces/${encodeURIComponent(e)}/backends/imap/${encodeURIComponent(t)}/containers/${encodeURIComponent(n)}`,{removalPolicy:r});function sE(e){let t=pb(`backends`,e.path)?.backend;return(0,$.jsx)(cE,{...e},JSON.stringify([e.workspace,t]))}function cE({workspace:e,path:t,onNavigate:n}){let r=pb(`backends`,t),i=r.backend,a=r.prefix,[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)(null),x=(0,Q.useCallback)(()=>g(e=>e+1),[]),[S,C]=(0,Q.useState)(t);S!==t&&(C(t),v(new Set),b(null),m(null),f(null));let w=o?.revision!==h,T=w?[]:o.items,E=w?[]:o.backends,D=o?.days;(0,Q.useEffect)(()=>{let t=!1;return(i?_b(e,i).then(e=>({...e,backends:[]})):pa(e).then(e=>({items:[],days:null,backends:e.filter(e=>e.driver===`file`&&e.enabled!==!1)}))).then(e=>{t||s({...e,revision:h,error:null})}).catch(e=>{t||s({revision:h,items:[],backends:[],days:null,error:e instanceof Error?e.message:String(e)})}),()=>{t=!0}},[e,i,h]),(0,Q.useEffect)(()=>{let t=null,n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==`backends`||(t||=setTimeout(()=>{t=null,x()},500))};return window.addEventListener(`workspace:trash:refresh`,n),window.addEventListener(`workspace:tree:refresh`,n),()=>{window.removeEventListener(`workspace:trash:refresh`,n),window.removeEventListener(`workspace:tree:refresh`,n),t&&clearTimeout(t)}},[e,x]);let O=hb(T,a),k=async(t,n)=>{if(!(!i||u.current||w||!n.length)&&!(t===`discard`&&!Sb(i,n))){u.current=!0,l(t),f(null),m(null),b(null);try{let r=await(t===`restore`?vb:yb)(e,i,[...n].sort((e,t)=>t.deletedAt-e.deletedAt).map(e=>e.id)),a=r.filter(e=>!e.ok);m(`${r.length-a.length} item(s) ${t===`restore`?`restored to their original paths`:`permanently deleted`}.`),a.length&&f(`${a.length} item(s) remain in Trash. ${a.slice(0,3).map(e=>`${e.key||`Item`}: ${e.reason===`precondition-failed`||e.reason===`target-exists`?`original path is occupied`:e.message||e.reason}`).join(`; `)}`),v(new Set)}catch(e){f(e instanceof Error?e.message:String(e))}finally{u.current=!1,l(null),x()}}},A=(e,t,n)=>b({x:e,y:t,row:n});return(0,$.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col bg-background`,"aria-label":`Backend Trash`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 border-b px-4 py-3`,children:[(0,$.jsx)(nt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(Km,{items:qm(t,e).map((e,t)=>t===2&&i?{...e,label:i}:e),onNavigate:n,className:`basis-48`}),(0,$.jsxs)(`div`,{className:`ml-auto flex max-w-full flex-wrap items-center gap-2`,children:[_.size>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`restore`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,$.jsx)(ir,{className:`h-3.5 w-3.5`}),`Restore selected`]}),(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),`Delete selected`]})]}),i&&O.length>0&&(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.flatMap(e=>e.items)),children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),a?`Empty this folder`:`Empty Trash`]}),(0,$.jsx)(`button`,{title:`Refresh Trash`,"aria-label":`Refresh Trash`,className:`rounded p-2 hover:bg-accent`,disabled:!!c||w,onClick:x,children:(0,$.jsx)(P,{className:`h-4 w-4 ${w?`animate-spin`:``}`})})]})]}),(0,$.jsxs)(`div`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`Restore files and folders to their original paths. Existing files are kept.`,D?` Deleted items are kept for ${D} days.`:``]}),p&&(0,$.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:p}),(d||o?.error)&&(0,$.jsx)(`p`,{role:`alert`,className:`px-4 py-2 text-sm text-destructive`,children:d||o?.error}),c&&(0,$.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:c===`restore`?`Restoring…`:`Deleting permanently…`}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:w?(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Loading Trash…`}):i?O.length===0?(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`This Trash folder is empty.`}):(0,$.jsxs)(`table`,{className:`w-full text-left text-sm`,children:[(0,$.jsx)(`thead`,{className:`border-b text-xs text-muted-foreground`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`w-8 p-2`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all visible items`,checked:O.length>0&&O.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(O.map(e=>e.id)):new Set)})}),(0,$.jsx)(`th`,{className:`p-2`,children:`Name`}),(0,$.jsx)(`th`,{className:`p-2 max-sm:hidden`,children:`Original path`}),(0,$.jsx)(`th`,{className:`p-2 max-md:hidden`,children:`Deleted`}),(0,$.jsx)(`th`,{className:`p-2`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsx)(`tbody`,{children:O.map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-border/50 hover:bg-accent/50`,onContextMenu:t=>{t.preventDefault(),A(t.clientX,t.clientY,e)},onDoubleClick:()=>e.navigable&&n(mb(i,e.key)),children:[(0,$.jsx)(`td`,{className:`p-2`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.name}`,checked:_.has(e.id),disabled:!!c,onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,$.jsx)(`td`,{className:`p-2`,children:(0,$.jsxs)(`button`,{className:`flex items-center gap-2 text-left`,onClick:()=>e.navigable&&n(mb(i,e.key)),children:[e.directory?(0,$.jsx)($e,{className:`h-4 w-4 shrink-0`}):(0,$.jsx)(Rn,{className:`h-4 w-4 shrink-0`}),(0,$.jsxs)(`span`,{children:[e.name,e.navigable&&(0,$.jsxs)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.items.length,` items`]})]})]})}),(0,$.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-sm:hidden`,children:e.key}),(0,$.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-md:hidden`,children:new Date(e.items.reduce((e,t)=>Math.max(e,t.deletedAt),0)).toLocaleString()}),(0,$.jsx)(`td`,{className:`p-2 text-right`,children:(0,$.jsx)(`button`,{title:`Actions for ${e.name}`,"aria-label":`Actions for ${e.name}`,disabled:!!c,className:`rounded p-2 hover:bg-accent`,onClick:t=>A(t.clientX,t.clientY,e),children:(0,$.jsx)(vn,{className:`h-4 w-4`})})})]},e.id))})]}):(0,$.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[E.map(e=>(0,$.jsxs)(`button`,{onClick:()=>n(mb(e.address)),className:`flex items-center gap-3 rounded-lg border p-4 text-left hover:bg-accent`,children:[(0,$.jsx)(nt,{className:`h-6 w-6 text-muted-foreground`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:e.label||e.address}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.address})]})]},e.address)),!E.length&&(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`No file backends are available.`})]})}),y&&(0,$.jsxs)(em,{x:y.x,y:y.y,onClose:()=>b(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[y.row.navigable&&(0,$.jsxs)(`button`,{className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent`,onClick:()=>{n(mb(i,y.row.key)),b(null)},children:[(0,$.jsx)($e,{className:`h-4 w-4`}),`Open folder`]}),(0,$.jsxs)(`button`,{disabled:!!c,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent disabled:opacity-50`,onClick:()=>void k(`restore`,y.row.items),children:[(0,$.jsx)(ir,{className:`h-4 w-4`}),`Restore `,y.row.directory?`folder`:`file`]}),(0,$.jsxs)(`button`,{disabled:!!c||w,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-destructive hover:bg-destructive/10 disabled:opacity-50`,onClick:()=>void k(`discard`,y.row.items),children:[(0,$.jsx)(nt,{className:`h-4 w-4`}),`Delete permanently`]})]})]})}function lE({value:e,backends:t,source:n,onSave:r,destination:i=!0}){let[a,o]=(0,Q.useState)({...nE,...e}),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=`rounded border bg-background px-2 py-1.5 text-xs w-full`,f=async()=>{c(!0),u(``);try{await r(a),u(`Removal policy saved.`)}catch(e){u(e instanceof Error?e.message:`Could not save policy`)}finally{c(!1)}};return(0,$.jsxs)(`details`,{className:`border-t pt-3 text-xs`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:`Source removals and Trash`}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`A completed scan removes missing locations from the backend tree. Items with no remaining locations go to Trash until you purge them.`}),(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`space-y-1 block`,children:[`When an item disappears from this source`,(0,$.jsxs)(`select`,{className:d,value:a.membership,disabled:s,onChange:e=>o({...a,membership:e.target.value}),children:[(0,$.jsx)(`option`,{value:`keep`,children:`Keep in managed trees`}),(0,$.jsx)(`option`,{value:`review`,children:`Review removal in Trash`}),(0,$.jsx)(`option`,{value:`trash`,children:`Move to Trash automatically`})]})]}),(0,$.jsxs)(`label`,{className:`space-y-1 block`,children:[`Remove tracked copies from other backends`,(0,$.jsxs)(`select`,{className:d,value:a.propagation,disabled:s,onChange:e=>o({...a,propagation:e.target.value}),children:[(0,$.jsx)(`option`,{value:`never`,children:`Never`}),(0,$.jsx)(`option`,{value:`review`,children:`Review in Trash`}),(0,$.jsx)(`option`,{value:`automatic`,children:`Automatically, retaining recovery copies`})]})]})]}),a.propagation!==`never`&&(0,$.jsxs)(`fieldset`,{className:`space-y-2`,children:[(0,$.jsx)(`legend`,{className:`mb-1 font-medium`,children:`Destinations`}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:a.targets===`all`,disabled:s,onChange:e=>o({...a,targets:e.target.checked?`all`:[]})}),`All eligible backends`]}),a.targets!==`all`&&t.filter(e=>e.address!==n&&e.kind===`storage`).map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:s||e.config?.propagatedRemovalSupported!==!0,checked:a.targets.includes(e.address),onChange:t=>o({...a,targets:t.target.checked?[...a.targets,e.address]:a.targets.filter(t=>t!==e.address)})}),String(e.config?.label||e.address),e.config?.propagatedRemovalSupported===!0?!e.config?.removalPolicy?.acceptPropagatedDeletions&&` · protected`:` · recovery removal unavailable`]},e.address)),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`Only tracked, Canvas-owned copies are eligible. Protected destinations refuse propagated deletion. Recovery removal currently supports filesystem and workspace blob storage; remote destinations remain protected.`})]}),i&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:s,checked:a.acceptPropagatedDeletions,onChange:e=>o({...a,acceptPropagatedDeletions:e.target.checked})}),`Accept propagated deletions on this backend`]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>void f(),children:s?`Saving…`:`Save removal policy`}),(0,$.jsx)(`span`,{role:`status`,children:l})]})]})]})}function uE({workspaceName:e,canWrite:t}){let{showToast:n}=Vr(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(!1),d=(0,Q.useCallback)(async()=>{o(!0);try{i(await Bi(e))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to load the trash`,variant:`destructive`})}finally{o(!1)}},[e]);(0,Q.useEffect)(()=>{d()},[d]);let f=(0,Q.useCallback)(e=>s.includes(e),[s]),p=async(e,t)=>{c(t=>[...t,...e]);try{await t()}finally{c(t=>t.filter(t=>!e.includes(t)))}},m=t=>p([t.id],async()=>{try{let r=await ba(e,[t.id]);r.failed?.length?n({title:`Not restored`,description:r.failed[0]?.error||`No restore target recorded`,variant:`destructive`}):(n({title:`Restored`,description:`Document put back where it was.`}),i(e=>e.filter(e=>e.id!==t.id)))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to restore`,variant:`destructive`})}}),h=t=>p([t.id],async()=>{try{let r=await mi(e,[t.id]);if(r.failed?.length)throw Error(`The item could not be purged. Refresh and retry.`);n({title:`Cleared from Trash`,description:r.preserved?.length?`Existing backend copies remain indexed.`:`Document permanently deleted.`}),i(e=>e.filter(e=>e.id!==t.id))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to delete`,variant:`destructive`})}}),g=async()=>{if(!l){u(!0);return}u(!1);try{let t=await mi(e);n({title:`Trash emptied`,description:`${t.destroyed?.length??0} document(s) purged. ${t.preserved?.length??0} item(s) cleared with backend copies preserved.`}),await d()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to empty the trash`,variant:`destructive`})}},_=(0,Q.useMemo)(()=>r.map(e=>{let t=Yr(e),n=(e.trashed?.placements??[]).flatMap(e=>e.paths.map(t=>`${e.tree}:${t}`));return{document:e,title:t.title,origin:n,trashedAt:e.trashed?.trashedAt||null}}),[r]);return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-medium`,children:`Managed-tree items`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 max-w-2xl`,children:`Restore managed-tree placements or permanently purge these items. Pending removals require separate approval. Backend copies are managed below.`})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 max-sm:flex-wrap`,children:[(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>d(),disabled:a,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${a?`animate-spin`:``}`}),`Refresh`]}),(0,$.jsxs)(Z,{variant:l?`destructive`:`outline`,size:`sm`,onClick:g,onBlur:()=>u(!1),disabled:!t||r.length===0,children:[(0,$.jsx)(nt,{className:`mr-2 h-3.5 w-3.5`}),l?`Click again to delete everything`:`Empty trash`]})]})]}),a&&r.length===0&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading…`}),!a&&r.length===0&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The trash is empty.`}),_.length>0&&(0,$.jsx)(`div`,{className:`border rounded-md divide-y`,children:_.map(({document:e,title:n,origin:r,trashedAt:i})=>(0,$.jsxs)(`div`,{className:`flex items-center gap-3 px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm`,children:n}),(0,$.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[r.length>0?`from ${r.join(`, `)}`:`no recorded origin`,i?` · ${new Date(i).toLocaleString()}`:``]})]}),(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>m(e),disabled:!t||f(e.id)||r.length===0,title:r.length===0?`Nothing recorded to restore to`:`Put it back where it was`,children:[(0,$.jsx)(ir,{className:`mr-2 h-3.5 w-3.5`}),`Restore placements`]}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>h(e),disabled:!t||f(e.id),title:`Delete permanently`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]},e.id))})]})}function dE({workspaceName:e}){return(0,$.jsx)(fE,{workspaceName:e},e)}function fE({workspaceName:e}){let[t,n]=(0,Q.useState)(`pending`),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(0),[l,u]=(0,Q.useState)(0),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)({}),[x,S]=(0,Q.useState)(`/Trash`),[C,w]=(0,Q.useState)([]),[T,E]=(0,Q.useState)({write:!1,admin:!1});(0,Q.useEffect)(()=>{let t=!0;return qr(e).then(e=>{let n=e.remote?.permissions||e.access?.permissions||(typeof e.sharedVia==`object`?e.sharedVia?.permissions:[])||[],r=Op(e);t&&E({admin:r,write:r||n.includes(`write`)})}).catch(()=>{}),()=>{t=!1}},[e]);let[D,O]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let t=!0;return pa(e).then(e=>{t&&w(e)}).catch(()=>{}),()=>{t=!1}},[e]),(0,Q.useEffect)(()=>{let n=!1,i=()=>iE(e,{view:t,search:r,...a?{backend:a}:{},offset:s}).then(e=>{n||(f(e),m(``))}).catch(e=>{n||m(e instanceof Error?e.message:`Could not load Trash`)});i();let o=setInterval(()=>{h||i()},5e3);return()=>{n=!0,clearInterval(o)}},[e,t,r,a,s,l,h]);let k=d?.operations||[],A=()=>{v(new Set),u(e=>e+1)},j=()=>{Da(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e}}))},M=async(t,n=[..._])=>{if(!(!n.length||h)&&!(t===`purge`&&!window.confirm(`Permanently delete retained recovery copies for ${n.length} operation(s)?`))){g(!0),m(``);try{let r=(t===`approve`?(await Promise.all(n.map(n=>aE(e,[n],t,y[n])))).flatMap(e=>e.results):(await aE(e,n,t)).results).filter(e=>!e.ok||e.operation?.state===`failed`);r.length&&m(r.map(e=>e.error||e.operation?.error||`A destination could not be changed. Expand the item for details.`).join(` `)),j(),A()}catch(e){m(e instanceof Error?e.message:`Trash action failed`)}finally{g(!1)}}},N=e=>{n(e),c(0),f(null),v(new Set),b({})};return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:`Workspace Trash`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Review source removals, recover items, and see what automatic policies changed.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,role:`tablist`,"aria-label":`Trash views`,children:[[[`pending`,`Pending removal`],[`trashed`,`In Trash`],[`activity`,`Activity`]].map(([e,n])=>(0,$.jsx)(Z,{role:`tab`,"aria-selected":t===e,size:`sm`,variant:t===e?`default`:`outline`,onClick:()=>N(e),children:n},e)),(0,$.jsxs)(Z,{size:`sm`,variant:`ghost`,className:`ml-auto`,onClick:A,disabled:h,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),t===`trashed`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(uE,{workspaceName:e,canWrite:T.write},l),(0,$.jsxs)(`details`,{className:`rounded border p-3`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:`Browse backend recovery copies`}),(0,$.jsx)(`div`,{className:`mt-3 min-h-48`,children:(0,$.jsx)(sE,{workspace:e,path:x,onNavigate:S})})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(Y,{"aria-label":`Filter Trash items`,placeholder:`Filter by item or path…`,className:`max-w-xs`,value:r,onChange:e=>{i(e.target.value),f(null),c(0),v(new Set)}}),(0,$.jsx)(Y,{"aria-label":`Filter by backend`,placeholder:`Backend name…`,className:`max-w-56`,value:a,onChange:e=>{o(e.target.value),f(null),c(0),v(new Set)}}),_.size>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsxs)(`span`,{children:[_.size,` selected`]}),t===`pending`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{size:`sm`,disabled:h,onClick:()=>void M(`approve`),children:`Approve selected`}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`keep`),children:`Keep selected`}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`retry`),children:`Retry`})]}),t===`trashed`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`restore`),children:`Restore copies`}),(0,$.jsx)(Z,{size:`sm`,variant:`destructive`,disabled:h,onClick:()=>void M(`purge`),children:`Purge copies`})]})]})]}),D&&(0,$.jsxs)(`div`,{className:`rounded border p-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Removal policy · `,D.source.account||D.source.backend,D.source.folder?` / ${D.source.folder}`:``]}),(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,onClick:()=>O(null),children:`Close`})]}),(0,$.jsx)(lE,{source:D.source.backend,backends:C,destination:!1,value:{...nE,...C.find(e=>e.address===D.source.backend)?.config?.removalPolicy,membership:y[D.id]?.membership??D.membership!==`keep`?`review`:`keep`,propagation:D.targets.length?`review`:`never`,targets:[...new Set(D.targets.filter(e=>!y[D.id]||y[D.id].targets.includes(JSON.stringify([e.backend,e.key]))).map(e=>e.backend))]},onSave:async t=>{D.source.driver===`imap`?await oE(e,D.source.account,D.source.folder,t):await _o(e,D.source.driver,D.source.backend,{removalPolicy:t}),w(await pa(e))}},D.id)]}),p&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p}),(0,$.jsxs)(`div`,{className:`overflow-x-auto rounded border`,children:[(0,$.jsxs)(`table`,{className:`w-full text-left text-xs`,children:[(0,$.jsx)(`thead`,{className:`bg-muted`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`p-3 w-8`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select visible operations`,disabled:!T.write||h||!k.length||t===`activity`,checked:k.length>0&&k.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(k.map(e=>e.id)):new Set)})}),(0,$.jsx)(`th`,{className:`p-3`,children:`Item and affected copies`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Source`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Status`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Detected`})]})}),(0,$.jsx)(`tbody`,{children:k.map(e=>{let n=y[e.id]||{targets:e.targets.filter(e=>e.state!==`kept`).map(e=>JSON.stringify([e.backend,e.key])),membership:e.membership!==`keep`};return(0,$.jsxs)(`tr`,{className:`border-t align-top`,children:[(0,$.jsx)(`td`,{className:`p-3`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.title}`,disabled:!T.write||h||t===`activity`,checked:_.has(e.id),onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,$.jsx)(`td`,{className:`p-3 min-w-64`,children:(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:e.title}),(0,$.jsxs)(`div`,{className:`mt-2 space-y-2 text-muted-foreground`,children:[(0,$.jsx)(`p`,{children:e.orphan?`No remaining byte locations. Restore placements only unless recovery bytes are available.`:`${e.remainingLocations.length} remaining location(s) when detected.`}),e.placements.map(e=>(0,$.jsxs)(`p`,{children:[e.tree,`: `,e.paths.join(`, `)]},e.tree)),e.membership!==`keep`&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:n.membership,disabled:h||t!==`pending`||e.membershipApplied,onChange:t=>b({...y,[e.id]:{...n,membership:t.target.checked}})}),e.membershipApplied?`Managed placements moved to Trash`:`Move managed placements to Trash`]}),e.targets.map(r=>{let i=JSON.stringify([r.backend,r.key]);return(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:h||t!==`pending`||!!r.trashId,checked:n.targets.includes(i),onChange:t=>b({...y,[e.id]:{...n,targets:t.target.checked?[...n.targets,i]:n.targets.filter(e=>e!==i)}})}),(0,$.jsxs)(`span`,{className:`break-all`,children:[r.backend,`:`,r.key,` · `,r.state,r.error&&(0,$.jsx)(`span`,{className:`block text-destructive`,children:r.error})]})]},i)}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:!T.admin,onClick:()=>O(e),children:`Use these choices as a source policy`}),e.remainingLocations.map(e=>(0,$.jsx)(`p`,{className:`break-all`,children:e.url},e.url))]})]})}),(0,$.jsxs)(`td`,{className:`p-3 break-all`,children:[e.source.account||e.source.backend,e.source.folder&&(0,$.jsx)(`span`,{className:`block text-muted-foreground`,children:e.source.folder})]}),(0,$.jsxs)(`td`,{className:`p-3`,children:[e.state,e.error&&(0,$.jsx)(`p`,{className:`mt-1 max-w-xs text-destructive`,children:e.error})]}),(0,$.jsx)(`td`,{className:`p-3 whitespace-nowrap text-muted-foreground`,children:new Date(e.createdAt).toLocaleString()})]},e.id)})})]}),!k.length&&(0,$.jsx)(`p`,{className:`p-5 text-center text-sm text-muted-foreground`,children:d?`No matching operations.`:`Loading…`})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[d?.total??0,` operation(s)`]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:!s||h,onClick:()=>{c(Math.max(0,s-200)),v(new Set)},children:`Previous`}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:s+k.length>=(d?.total??0)||h,onClick:()=>{c(s+200),v(new Set)},children:`Next`})]})]})]})}function pE({workspaceName:e,children:t}){let n=e,[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(0),[d,f]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{let t=!1,r=0,a,s=!1,c=async()=>{if(s||t)return;s=!0;let c=++r;try{let s=a?await co(e):await qr(e);!t&&c===r&&(`id`in s&&(a=s.id,f({identity:n,allowed:Op(s)})),i({identity:n,state:Tr()||s.status===`active`?`active`:s.status===`inactive`?`stopped`:`unavailable`}),o(``))}catch(e){if(!t&&c===r){let t=e instanceof Error?e.message:`Unable to check workspace status`,r=wr(t);i(e=>r&&e?.identity===n&&e.state===`active`?e:{identity:n,state:r?`offline`:`unavailable`}),o(t)}}finally{s=!1}},l=t=>{let s=t.detail?.refs;!s?.includes(e)&&!(a&&s?.includes(a))||(r++,i({identity:n,state:`stopped`}),o(``))},u=t=>{let s=t.workspaceId||t.id;!s||s!==e&&s!==a||!t.status||(r++,i({identity:n,state:t.status===`active`?`active`:t.status===`inactive`?`stopped`:`unavailable`}),o(``))};c(),window.addEventListener(`workspaces:refresh`,c),window.addEventListener(`workspace:stopped`,l),window.addEventListener(`focus`,c);let d=hd.on(`connect`,c);hd.on(`workspace:status:changed`,u),hd.on(`workspace.status.changed`,u);let p=Nr(e=>{e||c()});return()=>{t=!0,d?.(),p(),hd.off(`workspace:status:changed`,u),hd.off(`workspace.status.changed`,u),window.removeEventListener(`workspaces:refresh`,c),window.removeEventListener(`workspace:stopped`,l),window.removeEventListener(`focus`,c)}},[e,n,l]),r?.identity!==n)return(0,$.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`});if(r.state===`active`)return t;let p=r.state===`stopped`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`font-medium`,children:p?`Workspace stopped`:r.state===`offline`?`Server unreachable`:`Workspace unavailable`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p?`Start this workspace to view its content.`:r.state===`offline`?`Reconnect to load this workspace. Previously loaded content stays available offline.`:`Unable to check this workspace. Try again or check its settings.`}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(Z,{disabled:s,onClick:async()=>{c(!0),o(``);try{p&&await so(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?p?`Starting…`:`Checking…`:p?`Start workspace`:`Retry`}),d?.identity===n&&d.allowed&&(0,$.jsx)(Nu,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]})}function mE({workspaceId:e,workspaceName:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,Q.useEffect)(()=>{let t=!1,n=!1,i=!1,a=0,o=new Map,s=new Map,c=(e,t)=>{let n=e.filter(e=>e.address!==t.backend);if(!t.resyncing)return n;let r=e.find(e=>e.address===t.backend)||s.get(t.backend);return[...n,{address:t.backend,config:r?.config,resyncStartedAt:r?.resyncStartedAt||new Date().toISOString(),progress:t.progress??r?.progress}]},l=async()=>{if(n){i=!0;return}n=!0;let u=a;try{let n=await pa(e);if(!t){s=new Map(n.map(e=>[e.address,e]));let e=n.filter(e=>e.resyncing);for(let t of o.values())t.version>u&&(e=c(e,t.event));r(e)}}catch{}finally{n=!1,i&&!t&&(i=!1,l())}},u=t=>{t.workspaceId!==e||!t.backend||typeof t.resyncing!=`boolean`||(o.set(t.backend,{version:++a,event:t}),r(e=>c(e,t)))},d=t=>{t.workspaceId===e&&l()};l();let f=hd.on(`connect`,l);return hd.on(`backend.resync.changed`,u),hd.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),hd.off(`backend.resync.changed`,u),hd.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,$.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,$.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,$.jsx)(Yn,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,$.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,$.jsx)(G,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,$.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:i}),(0,$.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,$.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}function hE({navigationTabs:e,navigationActions:t,onBack:n,accentColor:r,frameContent:i=!0,urlType:a,urlDisplay:o,contextPath:s,treeName:c,workspaceId:l,workspaceLabel:u,workspaceIcon:d,documentSchema:f,documents:p,isLoading:m,totalCount:h,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:M,disablePurgeDocuments:N,canvasInfo:P,isCanvasPinned:F,onTogglePinCanvas:I,onSaveAsCanvas:L,onShareCanvas:R,onUnshareCanvas:z,onDeleteCanvas:ne,isSharingCanvas:B,isDeletingCanvas:re,isCanvasShared:ie,isCanvasLocked:ae,backendSearchQueries:oe,onBackendSearch:V,onRemoveBackendQuery:H,serverSort:U,onServerSortChange:se,scope:W,onScopeChange:ce,canSaveChanges:le,isSavingChanges:ue,onSaveChanges:de,onBrowseWorkspaces:fe,onBrowseTree:pe,onNavigatePath:me,linkTree:G,children:he,contentBanner:ge,folders:_e,onOpenFolder:ve}){let K=a===`canvas`,{state:q,toggleView:ye,hasActiveFilters:be,openAddPicker:xe}=zs(),Se=Eg(),[Ce,we]=(0,Q.useState)(``),Te=JSON.stringify([l,c,s,f]),[Ee,De]=(0,Q.useState)(Te);Ee!==Te&&(De(Te),we(``));let ke=(0,$.jsxs)($.Fragment,{children:[t,L&&(0,$.jsx)(`button`,{type:`button`,onClick:L,title:`Save as canvas`,"aria-label":`Save as canvas`,className:`flex h-control-sm w-control-sm shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent touch-target`,children:(0,$.jsx)(Ft,{className:`h-4 w-4`})})]});return(0,$.jsxs)(`div`,{className:`flex flex-col h-full min-h-0 bg-background`,children:[e&&(0,$.jsx)(Xg,{accentColor:r,children:e}),(0,$.jsxs)(`div`,{className:`canvas-surface-body${i?` is-framed`:``}`,children:[(0,$.jsx)(Zg,{workspaceIcon:d,workspace:u||l||o.split(`://`)[0]||`Workspace`,tree:c?`${c}${a.endsWith(`-layer`)?`:layer`:``}`:a.replace(`-layer`,``),path:s,accentColor:r,onBack:Se.location?Se.location.section===`view`?Se.close:()=>Se.update?.({section:`view`}):n,section:Se.location?`document/${Se.location.documentId}/${Se.location.section}`:void 0,onSection:Se.location?()=>Se.update?.({section:`view`}):void 0,onBrowseWorkspaces:fe,onBrowseTree:pe,onNavigatePath:me,onFilter:()=>ye(`tools`),filtersActive:be,filtersOpen:q.t1Open&&q.t1View===`tools`,onAdd:e=>xe({modal:e.shiftKey,fresh:!0}),search:V||!he?{queries:oe||[],onSearch:V??we,localOnly:!V,onRemoveQuery:H,scope:W,onScopeChange:ce}:void 0,onDraftChange:he?void 0:we}),K&&P?(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[P.color&&(0,$.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:P.color}}),(0,$.jsx)(gt,{className:`w-4 h-4 shrink-0 text-primary`}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:P.label||o.split(`://`)[1]||`Canvas`}),P.description&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:P.description})]}),le&&de&&(0,$.jsxs)(`button`,{type:`button`,onClick:de,disabled:ue,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:`Save filters`,children:[(0,$.jsx)(Be,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:ue?`Saving...`:`Save filters`})]}),I&&(0,$.jsxs)(`button`,{type:`button`,onClick:I,"aria-pressed":!!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`,title:F?`Unpin from home`:`Pin to home`,children:[F?(0,$.jsx)(ee,{className:`w-3 h-3`}):(0,$.jsx)(Oe,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:F?`Unpin`:`Pin`})]}),R&&(0,$.jsxs)(`button`,{type:`button`,onClick:R,disabled:B||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:ie?`Copy public link`:`Share canvas`,children:[(0,$.jsx)(jn,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:B?`Sharing...`:ie?`Copy link`:`Share`})]}),ie&&z&&(0,$.jsxs)(`button`,{type:`button`,onClick:z,disabled:B||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,$.jsx)(te,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),ne&&(0,$.jsxs)(`button`,{type:`button`,onClick:ne,disabled:re||ae&&!ie,title:ae&&!ie?`Unlock this canvas before deleting it`:`Delete canvas`,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,$.jsx)(nt,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:re?`Deleting…`:`Delete`})]})]})}):null,he&&(L||t)&&(0,$.jsx)(`div`,{className:`flex items-center gap-2 border-b px-3 py-1`,children:ke}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[ge,he||(0,$.jsx)(rx,{externalSearchQuery:Ce,toolbarActions:ke,documents:f?p.filter(e=>e.schema===f):p,isLoading:m,folders:f?void 0:_e,onOpenFolder:ve,contextPath:s,treeName:c,workspaceId:l,totalCount:h,viewMode:f?`card`:`table`,allowViewToggle:!0,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:f?void 0:M,disablePurgeDocuments:N,backendSearchQueries:oe,onBackendSearch:V,serverSort:U,onServerSortChange:se,onRemoveBackendQuery:H,scope:W,onScopeChange:ce,canSaveChanges:!K&&le,isSavingChanges:ue,onSaveChanges:de,linkTree:G},f??`documents`)]})]})]})}var gE=[{id:`todos`,label:`Todo list`},{id:`todo-app`,label:`Todo App`},{id:`notes`,label:`Notes list`},{id:`notes-app`,label:`Notes App`},{id:`sketch`,label:`Sketch`}];function _E(e){return e?.kind===`app`&&e.app===`notes`?`data/schema/note`:void 0}var vE={id:`default`,name:`All`,kind:`documents`};function yE(){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 bE(e){let t=e?.views;if(!Array.isArray(t))return[vE];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`&&(gE.some(e=>e.id===t.app)||t.app===`filters`||t.app===`lens`)});return n.length>0?n:[vE]}var xE={todos:Vt,"todo-app":Vt,notes:Kn,"notes-app":Kn,filters:Un,sketch:le,lens:cr};function SE({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=v.current;if(!e)return;let t=t=>{if(t.ctrlKey||e.scrollWidth<=e.clientWidth)return;let n=Math.abs(t.deltaX)>Math.abs(t.deltaY)?t.deltaX:t.deltaY,r=t.deltaMode===1?16:t.deltaMode===2?e.clientWidth:1;t.preventDefault(),e.scrollLeft+=n*r};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[]),(0,Q.useEffect)(()=>{v.current?.querySelector(`[aria-pressed="true"], input`)?.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,c]);let y=()=>{h(null),_(null)},b=()=>{if(m&&g&&m!==g.id){let t=e.find(e=>e.id===m),n=e.filter(e=>e.id!==m),i=n.findIndex(e=>e.id===g.id);t&&i>=0&&(n.splice(g.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!c)return;let t=u.trim();t&&r(e.map(e=>e.id===c?{...e,name:t}:e)),l(null)},S=(t,n)=>{p(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?gE.find(e=>e.id===n)?.label??`App`:`List`,o=t===`columns`?{id:i,name:a,kind:t,columns:yE()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),l(i),d(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[vE],n===t?i[0]?.id??vE.id:void 0)};return(0,$.jsxs)(`div`,{className:J(`relative flex h-full min-w-0 items-end`,a),children:[(0,$.jsx)(`div`,{ref:v,className:`flex min-w-0 items-end gap-0.5 overflow-x-auto overscroll-x-contain pt-1 [scrollbar-width:none]`,children:e.map(r=>{let a=r.id===t,f=r.kind===`columns`?rr:r.kind===`app`&&r.app?xE[r.app]:Kt;return c===r.id?(0,$.jsx)(`input`,{autoFocus:!0,"aria-label":`Tab name`,value:u,onChange:e=>d(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&l(null)},className:J(`relative h-[2.3rem] w-28 shrink-0 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs outline-none ring-0`,a?J(`z-[2] bg-background font-medium`,o?Fm(o):`text-foreground`):`bg-muted text-muted-foreground`),style:{backgroundColor:a?o:void 0}},r.id):(0,$.jsxs)(`button`,{type:`button`,"aria-pressed":a,onClick:()=>n(r.id),onDoubleClick:()=>{i||(l(r.id),d(r.name))},title:i?r.name:`${r.name}: double-click to rename, drag to reorder`,draggable:!i,onDragStart:e=>{e.dataTransfer.setData(`text/plain`,r.name),e.dataTransfer.effectAllowed=`move`,h(r.id)},onDragOver:e=>{if(!m||m===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;_(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:J(`group relative flex h-[2.3rem] shrink-0 items-center gap-1.5 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs transition-colors`,a?J(`z-[2] bg-background font-medium`,o?Fm(o):`text-foreground`):`bg-muted text-muted-foreground hover:bg-accent hover:text-foreground`,m===r.id&&`opacity-50`),style:{backgroundColor:a?o:void 0,boxShadow:g?.id===r.id?`inset ${g.before?`2px`:`-2px`} 0 0 var(--primary)`:void 0},children:[(0,$.jsx)(f,{className:`h-3 w-3 shrink-0`}),(0,$.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,$.jsx)(Ze,{className:`h-3 w-3 shrink-0 opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-60`,"aria-label":`Open to the side`,onClick:e=>{e.stopPropagation(),s(r.id)}}),!i&&e.length>1&&(0,$.jsx)(G,{className:J(`h-3 w-3 shrink-0 transition-opacity hover:text-destructive`,a?`opacity-60 hover:opacity-100`:`opacity-0 group-hover:opacity-100`),onClick:e=>{e.stopPropagation(),C(r.id)}})]},r.id)})}),!i&&(f?(0,$.jsxs)(`span`,{className:`absolute left-0 top-full z-30 flex w-full min-w-64 flex-wrap items-center gap-2 rounded-b-xl border bg-card p-2 shadow-lg`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(Kt,{className:`h-3 w-3`}),` List`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(rr,{className:`h-3 w-3`}),` Board`]}),gE.map(e=>{let t=xE[e.id];return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(t,{className:`h-3 w-3`}),` `,e.label]},e.id)}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]}):(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(!0),title:`Add view`,"aria-label":`Add view`,className:`relative ml-1 flex h-[2.3rem] w-10 shrink-0 items-center justify-center rounded-md pb-1 text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,$.jsx)(sn,{className:`h-3.5 w-3.5`})}))]})}function CE(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let o=!1;return to(e,n,t,{limit:200,allOf:[r],...i?{sortBy:i,order:`asc`}:{}}).then(e=>{o||l({key:a,docs:e.payload||[]})}).catch(()=>{o||l({key:a,docs:[]})}),()=>{o=!0}},[a,o]);let u=c?.key===a?c.docs:[],d=c?.key!==a;return(0,Q.useEffect)(()=>{let e=()=>s(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]),{docs:u,isLoading:d,refresh:(0,Q.useCallback)(()=>s(e=>e+1),[])}}function wE({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=CE(e,t,n,Ji,`tasks`),[o,s]=(0,Q.useState)(!1),c=o?r.filter(e=>e.data?.status!==`completed`):r,l=r.filter(e=>{let t=e.data?.status;return t!==`completed`&&t!==`cancelled`}).length;return(0,$.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,$.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,$.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,$.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,$.jsx)(Ax,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function TE({app:e,contextId:t,...n}){let r=t&&e!==`lens`?{mode:`context`,contextId:t}:{mode:`workspace`,workspaceName:n.workspaceId,treeName:n.treeName,path:n.path,treeType:n.treeName===`directory`||n.treeName===`backends`?`directory`:`context`},i=e===`todo-app`?`todo`:e===`notes-app`?`notes`:e,a=Dw.find(e=>e.id===i);return(0,$.jsx)(kw,{target:r,children:e===`todos`?(0,$.jsx)(wE,{...n}):a?(0,$.jsx)(a.Component,{}):null})}var EE=[{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 DE(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function OE({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)({}),[d,f]=(0,Q.useState)({}),p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1),g=(0,Q.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,Q.useEffect)(()=>{let e=p.current;if(!e)return;let t=new ResizeObserver(()=>g());return t.observe(e),()=>t.disconnect()},[g]);let _=(e,t)=>{e.preventDefault();let i=e.currentTarget.parentElement;if(!i)return;let a=e.clientX,o=i.getBoundingClientRect().width,s=o,c=e=>{s=Math.min(900,Math.max(220,o+e.clientX-a)),f(e=>({...e,[t]:s}))},l=()=>{window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),r(n.map(e=>e.id===t?{...e,width:Math.round(s)}:e))};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l)},v=e=>{f(t=>{let n={...t};return delete n[e],n}),r(n.map(t=>t.id===e?{...t,width:void 0}:t))},y=e=>{let t=l[e];if(t===void 0)return;let i=n.find(t=>t.id===e);i&&(i.filter||``)!==t&&r(n.map(n=>n.id===e?{...n,filter:t||void 0}:n))},b=EE.filter(e=>!n.some(t=>t.id===e.id));return(0,$.jsxs)(`div`,{className:`relative h-full`,children:[(0,$.jsx)(`div`,{ref:p,onScroll:g,className:`flex h-full snap-x snap-mandatory gap-3 overflow-x-auto overscroll-x-contain p-2`,"data-testid":`schema-columns-board`,children:n.map(t=>{let a=(l[t.id]??t.filter??``).toLowerCase(),s=e.filter(e=>DE(e,t.schemas)).filter(e=>{if(!a)return!0;let t=Yr(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,$.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-(--card-radius) border bg-muted/20 ${c?`sm:basis-[var(--col-w)]`:`sm:basis-[48%] lg:basis-[32%] xl:basis-[24%]`}`,style:c?{"--col-w":`${c}px`}:void 0,children:[!i&&(0,$.jsx)(`div`,{onPointerDown:e=>_(e,t.id),onDoubleClick:()=>v(t.id),title:`Drag to resize; double-click to reset`,className:`absolute right-0 inset-y-0 z-10 w-2 cursor-col-resize touch-none rounded-r-lg transition-colors hover:bg-primary/25 active:bg-primary/40 max-sm:hidden`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,$.jsx)(`span`,{className:`flex-1`}),!i&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(n.filter(e=>e.id!==t.id)),title:`Remove column`,className:`rounded-sm p-0.5 text-muted-foreground hover:text-destructive`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(`div`,{className:`px-3 pb-2`,children:(0,$.jsx)(`input`,{value:l[t.id]??t.filter??``,onChange:e=>u(n=>({...n,[t.id]:e.target.value})),onBlur:()=>y(t.id),onKeyDown:e=>{e.key===`Enter`&&y(t.id)},placeholder:`Filter…`,readOnly:i,className:`h-7 w-full rounded-md border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})}),(0,$.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=Yr(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o(e),className:`w-full min-w-0 rounded-md border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(Gm,{document:e,size:3.5}),(0,$.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,$.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,$.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground/70`,children:new Date(e.updatedAt||e.createdAt).toLocaleDateString()})]},e.id)}),s.length===0&&(0,$.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground/60`,children:`Empty`})]})]},t.id)})}),(!i&&b.length>0||m)&&(0,$.jsxs)(`div`,{className:`pointer-events-none absolute inset-y-0 right-0 z-20 flex w-7 flex-col items-end bg-gradient-to-l from-background via-background/60 to-transparent py-2`,children:[!i&&b.length>0&&(0,$.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(e=>!e),title:`Add column`,"aria-label":`Add column`,className:`flex h-7 w-6 items-center justify-center rounded-l-md border border-r-0 bg-background text-muted-foreground shadow-elevation-1 hover:bg-accent hover:text-foreground`,children:(0,$.jsx)(sn,{className:`h-3.5 w-3.5`})}),s&&(0,$.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,$.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>{c(!1),r([...n,{...e}])},className:`w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:e.label},e.id)),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`mt-1 w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/60 hover:bg-accent/50`,children:`Cancel`})]})]}),m&&(0,$.jsx)(hr,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,$.jsx)(Hy,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var kE=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function AE(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function jE(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>jE(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:AE(e)}];let r=kE(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:AE(e)}))}function ME(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 NE(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 PE(e,t,n=new Map){let r=kE(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:AE(n)}],ids:ME(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...jE(r.context,`context`,n),...jE(r.directory,`directory`,n)],a=kE(r.changed);a&&i.push(...jE(a.context,`context`,n),...jE(a.directory,`directory`,n));let o=ME(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 FE(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function IE(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>AE(e).split(`/`).filter(Boolean).map(e=>e.normalize(`NFKC`).trim().replace(/\s+/g,` `).replace(/[^\p{L}\p{N}\p{M} .+_@-]/gu,`_`).replace(/_+/g,`_`).toLowerCase()||`_`),r=new Set(n(e.path)),i=n(t.path);return r.size===0||i.length===0||i.some(e=>r.has(e))}return FE(e.path,t.path)}function LE(e){return PE(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function RE(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>IE(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 zE=(0,Q.createContext)(null);function BE(){let e=(0,Q.useContext)(zE);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function VE(e,t,n={}){return hd.request(td,{workspace:e,specs:t,opts:n})}function HE(e,t,n){return hd.request(nd,{sessionId:e,label:t,spec:n})}function UE(e){return hd.request(rd,{sessionId:e})}function WE(e,t={}){return hd.request(id,{sessionId:e,...t})}function GE(e){return hd.request(ad,{sessionId:e})}function KE(e){return hd.on(od,e)}var qE=100;function JE({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),f=(0,Q.useRef)([]),p=(0,Q.useRef)(new Map),m=(0,Q.useRef)(null),h=(0,Q.useRef)(null),g=(0,Q.useRef)(null),_=(0,Q.useRef)({}),v=(0,Q.useRef)(null),y=(0,Q.useMemo)(()=>JSON.stringify(t),[t]),b=(0,Q.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,Q.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,Q.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=qE){let i=e.slice(r,r+qE),a=await Na(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,Q.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),x(),r.length===0)return;let a=await S(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}x()},[S,x]),w=(0,Q.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await C(a,[],t)},[C]);(0,Q.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await VE(e,JSON.parse(y),JSON.parse(b));if(t){GE(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=hd.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&GE(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,Q.useEffect)(()=>{if(!c)return;let e=KE(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,Q.useCallback)(async()=>{let e=m.current;if(e)try{let t=await UE(e);await w(t.ids,t.count)}catch{}},[w]),E=(0,Q.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await HE(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await w(r.ids,r.count)},[w]),D=(0,Q.useCallback)(async(e,t={})=>{let n=m.current;if(!n)throw Error(`No open query session`);if(g.current=e,_.current=t,e===null){await T();return}let r=await WE(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,Q.useEffect)(()=>{v.current=D},[D]);let O=(0,Q.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await WE(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 HE(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 YE=`canvas:query-debug`,XE=`canvas:query-debug-changed`;function ZE(){try{return localStorage.getItem(YE)===`1`}catch{return!1}}function QE(e){try{e?localStorage.setItem(YE,`1`):localStorage.removeItem(YE)}catch{}window.dispatchEvent(new CustomEvent(XE,{detail:e}))}function $E(){let[e,t]=(0,Q.useState)(ZE);return(0,Q.useEffect)(()=>{let e=()=>t(ZE());return window.addEventListener(XE,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(XE,e),window.removeEventListener(`storage`,e)}},[]),e}function eD({data:e,className:t}){let[n,r]=(0,Q.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,Q.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,$.jsxs)(`div`,{className:J(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let s=a>0?i[a].distance:null;return(0,$.jsxs)(`div`,{className:J(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,$.jsx)(Xe,{className:`h-3.5 w-3.5`}):(0,$.jsx)(hr,{className:`h-3.5 w-3.5`}),`Query debug`,(0,$.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,$.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,s===null?(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,$.jsxs)($.Fragment,{children:[` A jump at `,(0,$.jsx)(`span`,{className:`font-mono`,children:s.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,$.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,$.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,$.jsx)(`tbody`,{children:i.map((e,t)=>(0,$.jsxs)(`tr`,{className:J(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,$.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,$.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,$.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,$.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}function tD(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 nD=new Map;function rD(e,t,n){return`${e}\0${t}\0${n}`}function iD(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${rD(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function aD(e,t,n){let r=rD(e,t,n);for(let e of nD.keys())e.startsWith(r)&&nD.delete(e)}function oD(e,t){let n=`${e}\0`;for(let[e,r]of nD){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);RE(t,{tree:i,kind:ka(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&nD.delete(e)}}function sD(e,t){oD(t?.workspaceName??e,LE(t))}function cD(){let{workspaceName:e}=bl();return e?(0,$.jsx)(pE,{workspaceName:e,children:(0,$.jsx)(lD,{})}):null}function lD(){let{workspaceName:e,treeName:t}=bl(),n=pl(),r=gl(),{showToast:i,showProgress:a}=Vr(),o=new URLSearchParams(n.search),s=(()=>{let e=o.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(o.get(`search`)||``).trim();return t?[t]:[]})(),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(!0),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(0),v=$E(),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(v);x!==v&&(S(v),v||b(null));let[C,w]=(0,Q.useState)(`path`),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(``),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),[z,ee]=(0,Q.useState)(null),[te,ne]=(0,Q.useState)(1),[B,re]=(0,Q.useState)(50),[ie,ae]=(0,Q.useState)(s),[oe,V]=(0,Q.useState)(null),{state:H,saveFilters:U,setSort:se,setAccentColor:W,setMapDocuments:ce}=zs(),le=H.filters.features.allOf,ue=H.filters.features.anyOf,de=H.filters.features.noneOf,fe=Xy(H.filters.timeline),pe=qy(H.filters.geo),me=Jy(H.filters.lens,H.filters.geo.includeUnlocated),G=H.filters.lens.ids,he=[...fe,...pe,...me],ge=H.filters.sort??Wy,_e=JSON.stringify({a:le,b:ue,c:de,d:he,i:G,s:ge}),ve=JSON.stringify({a:le,b:ue,c:de,d:he,s:ge}),K=Px(n.pathname).path,q=t??`context`,ye=q===`backends`,[be,xe]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{!ye||!e||pa(e).then(xe).catch(()=>xe([]))},[ye,e]);let Se=ye?oo(K,be):null,[Ce,we]=(0,Q.useState)(!1),Te=`${q}\0${K}`,[Ee,De]=(0,Q.useState)(Te);Ee!==Te&&(De(Te),we(!1));let Oe=o.get(`layer`)===`1`,ke=o.get(`layerId`)||null,[Ae,je]=(0,Q.useState)(null),[Me,Ne]=(0,Q.useState)(null),Pe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{Pe.current=Me},[Me]);let[Fe,Ie]=(0,Q.useState)(`left`),[Le,Re]=(0,Q.useState)([]),{openM1Drawer:ze,openM2Drawer:Be,goBack:Ve}=PT(),[He,Ue]=(0,Q.useState)([]),We=(0,Q.useMemo)(()=>{if(!Ae||K===`/`||Oe)return null;let e=K.split(`/`).filter(Boolean),t=Ae;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Ae,K,Oe]),Ge=We?.type===`canvas`?`canvas`:null,Ke=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{!e||!Ae||Oe||Ke.current===`${e}/${q}`&&(K!==`/`&&!We||oT(e,q,K))},[e,Ae,Oe,K,We,q]);let qe=(0,Q.useMemo)(()=>Oe||C===`workspace`||ie.length>0||ka(q)!==`directory`?[]:tD(Ae,K),[Ae,K,q,Oe,C,ie]),Je=Oe?null:K===`/`?Ae:We,Ye=`${q}\0${K}`,[Xe,Ze]=(0,Q.useState)(null),Qe=Xe?.key===Ye?Xe.views:bE(Je?.metadata),$e=Xe?.key===Ye?Xe.activeId:Qe[0]?.id??vE.id,et=Qe.find(e=>e.id===$e)??Qe[0]??vE,tt=ye?void 0:_E(et),nt=tt?[...le,tt]:le,rt=e=>{ne(1),Re([]),Ze({key:Ye,views:Qe,activeId:e})},it=(t,n)=>{n&&n!==$e&&(ne(1),Re([])),Ze({key:Ye,views:t,activeId:n??$e}),zi(e,K,{metadata:{...Je?.metadata??{},views:t}},q).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},at=Ge===`canvas`&&typeof We?.querySpec?.query==`string`?We.querySpec.query:``,ot=Ge===`canvas`?{label:We?.label,description:We?.description,color:We?.color}:null,{isPinned:st,pin:ct,unpin:lt,pins:ut}=BE(),dt=c?.name,ft=(0,Q.useMemo)(()=>dt&&Ge===`canvas`&&!Oe?{workspaceName:dt,treeName:q,path:K}:null,[dt,Ge,Oe,q,K]),pt=ft?st(ft):!1,mt=We?.id,ht=We?.label,gt=(0,Q.useCallback)(async()=>{if(ft)try{let e=ut.find(e=>e.workspaceName===ft.workspaceName&&e.treeName===ft.treeName&&e.path===ft.path);e?await lt(e.id):await ct({...ft,layerId:mt,label:ht})}catch(e){console.error(`Failed to update home pins:`,e)}},[ft,ut,ct,lt,mt,ht]),_t=e?`${e}://${K===`/`?``:K.replace(/^\//,``)}`:``,vt=Nm(c?.color)||null;(0,Q.useEffect)(()=>(W(vt),()=>W(null)),[vt,W]);let yt=(0,Q.useCallback)(async t=>{let n=G;if(t?.anyOf?.length&&ue.length&&(n=((await to(e,K,q,{limit:0,anyOf:ue,ids:G,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await to(e,K,q,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...le,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:ue,noneOf:de,filters:he,ids:n,queries:[...ie,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,K,q,_e,ie]);(0,Q.useEffect)(()=>{e&&(async()=>{d(!0);try{let t=await X.get(`${xr.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,l(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;i({title:`Error`,description:n,variant:`destructive`}),l(null)}finally{d(!1)}})()},[e,i]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&l(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let bt=(G?.length??0)>0&&!Oe&&!(Ce&&Se)&&ie.length<=1,{documents:xt,count:St,ready:Ct,setCue:wt,resync:Tt,rank:Et}=JE({workspaceRef:e,specs:(0,Q.useMemo)(()=>{let e={features:{allOf:nt,anyOf:ue,noneOf:de},filters:he};return C!==`workspace`&&(ka(q)===`directory`?e.directory={tree:q,path:K}:e.context=K),[{label:`scope`,spec:e}]},[ve,K,q,C,tt]),opts:(0,Q.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:bt}),Dt=bt&&Ct,Ot=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{Ot.current=Dt},[Dt]);let kt=ie.length===1?ie[0].trim():``;(0,Q.useEffect)(()=>{Ct&&Et(kt?{text:kt}:null,{limit:B,offset:(te-1)*B}).catch(()=>{})},[Ct,kt,B,te,Et]);let At=(G??[]).join(`,`);(0,Q.useEffect)(()=>{Ct&&wt(`lens`,{ids:G??[]}).catch(()=>{})},[Ct,At,wt,G]);let jt=Dt?xt:f,Mt=Dt?St:g,Nt=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{Nt.current=new Set(jt.map(e=>Number(e.id)))},[jt]);let Pt=H.geoSelection;(0,Q.useEffect)(()=>{ce(jt,c?.name??null)},[jt,c?.name,ce]),(0,Q.useEffect)(()=>()=>ce([]),[ce]);let Ft=(0,Q.useMemo)(()=>Pt?jt.filter(e=>Ly(e,Pt,H.filters.geo.includeUnlocated)):jt,[jt,Pt,H.filters.geo.includeUnlocated]),It=Sa(K,nt,{treeName:q,treeType:ka(q),scope:C,queries:ie,anyOf:ue,noneOf:de,filters:he,ids:G,layerId:Oe&&ke?ke:void 0}),Lt=JSON.stringify([e,It]),[Rt,zt]=(0,Q.useState)(``),[Bt,Vt]=(0,Q.useState)(!1),Ht=(0,Q.useRef)(!1),Ut=m||Bt||Rt!==Lt||Dt||!!Pt,Wt=(0,Q.useRef)(0),Gt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{Wt.current++,Gt.current=null},[]);let Kt=(0,Q.useRef)(``),qt=(0,Q.useCallback)(async t=>{if(!e)return;if(pb(q,K)){Wt.current++,Gt.current=null,Kt.current=``,p([]),_(0),h(!1);return}if(Ot.current)return;let n=`${Ce&&Se?`${C}:unfiled`:C}:${tt??``}`,r=(G?.length??0)>0,a=iD(e,q,K,te,B,ie.join(`␟`),ve,Oe&&ke?ke:``,n),o=r&&a===Kt.current;Kt.current=a;let s=iD(e,q,K,te,B,ie.join(`␟`),_e,Oe&&ke?ke:``,n),c=`${s}\0${v}`;if(t?.silent&&Gt.current?.key===c){Gt.current.refreshPending=!0;return}let l=++Wt.current,u=t?.silent||r||v?void 0:nD.get(s);u&&(p(u.documents),_(u.totalCount),zt(Lt),h(!1)),(t?.silent??(o||!!u))||h(!0);let d={key:c,refreshPending:!1};Gt.current=d;try{let t;t=Ce&&Se?await vo(e,Se.driver,Se.address,{linked:!1,limit:B,offset:(te-1)*B}):Oe&&ke&&C!==`workspace`?await ua(e,q,ke,{limit:B,page:te,queries:ie,allOf:nt,anyOf:ue,noneOf:de,filters:he,ids:G,sortBy:ge.sortBy||void 0,order:ge.order}):await Na(e,K,nt,{limit:B,page:te,treeName:q,treeType:q===`directory`||q===`backends`?`directory`:`context`,queries:ie,anyOf:ue,noneOf:de,filters:he,ids:G,sortBy:ge.sortBy||void 0,order:ge.order,scope:C,debug:v&&ie.length>0,debugLimit:200});let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&nD.set(s,{documents:n,totalCount:i}),l!==Wt.current)return;let a=t.debug,c=a?.imageDistances??a?.distances??null;b(c?{query:ie[ie.length-1]??``,distances:c}:null),p(o?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),_(i),zt(Lt)}catch(e){if(l!==Wt.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),p([]),_(0)}finally{Gt.current===d&&(Gt.current=null),l===Wt.current&&h(!1),l===Wt.current&&d.refreshPending&&qt({silent:!0})}},[e,K,q,ke,Oe,te,B,c?.status,ie,_e,C,Ce,v,tt]);(0,Q.useEffect)(()=>{qt()},[qt]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Ne({treeName:n.treeName||`context`,path:Mx(n.path||`/`)}),Ie(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,q,K]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&sD(e,n),RE(LE(n),{tree:q,kind:ka(q),path:K,wholeWorkspace:C===`workspace`}))){if(e&&aD(e,q,K),Ot.current){Tt();return}qt({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[qt,e,K,q,C,Tt]);let Jt=c?.name,Yt=c?.id;(0,Q.useEffect)(()=>{if(!e||!Jt&&!Yt)return;let t=[Jt,Yt].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>hd.emit(`subscribe`,{channel:e}));n();let r=hd.on(`connect`,n),i=new Map,a=!1,o=()=>{Di(e).then(e=>{a||(i=NE(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,Ot.current){Tt();return}qt({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=PE(t,n,i);oD(e,r);let a={tree:q,kind:ka(q),path:K,wholeWorkspace:C===`workspace`},f=Pe.current;f&&RE(r,{tree:f.treeName,kind:ka(f.treeName),path:f.path})&&(u=f),RE(r,a,Nt.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.inserted.batch`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>hd.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>hd.off(e,t))}},[e,Yt,Jt,q,K,C,qt,Tt]);let Xt=`${K}\0${q}\0${ke??``}\0${C}`,[Zt,Qt]=(0,Q.useState)(Xt);Zt!==Xt&&(Qt(Xt),ne(1),V(null));let $t=`${K}\0${q}\0${ke??``}`,[en,tn]=(0,Q.useState)($t);en!==$t&&(tn($t),w(`path`));let nn=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;M(n),A({parentPath:e,captureView:t})},rn=o.get(`createCanvas`)===`1`,[an,on]=(0,Q.useState)(!1);an!==rn&&(on(rn),rn&&nn(K,!1)),(0,Q.useEffect)(()=>{if(!rn)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[rn,K]);let sn=(0,Q.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let i=t.toString();r(`${n.pathname}${i?`?${i}`:``}${n.hash}`)},[n.pathname,n.search,n.hash,r]),cn=JSON.stringify([o.has(`q`),...s]),[ln,un]=(0,Q.useState)(cn);ln!==cn&&(un(cn),ae(s),ne(1));let dn=`${cn}\0${Ge??``}\0${at}\0${K}\0${oe??``}`,[fn,pn]=(0,Q.useState)(dn);fn!==dn&&(pn(dn),o.has(`q`)||s.length>0||Ge!==`canvas`||oe===K||(ae(at?[at]:[]),ne(1)));let mn=(0,Q.useCallback)(e=>{let t=e.trim();t&&(V(null),ae(e=>{if(e.includes(t))return e;let n=[...e,t];return sn(n),ne(1),n}))},[sn,V,ae,ne]),hn=(0,Q.useCallback)(e=>{ae(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&V(K),sn(n),ne(1),n})},[sn,K,V,ae,ne]),gn=ie.join(` `).trim(),_n=!!H.activeContextType&&(H.isDirty||gn!==(Ge===`canvas`?at:H.savedSearchQuery||``));!e&&Ae!==null&&je(null),(0,Q.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&Da(e,q),vi(e,q).then(i=>{!t&&a===n&&(r=!0,Ke.current=`${e}/${q}`,je(i))}).catch(()=>{!t&&a===n&&!r&&je(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==q||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=Ab(e,Yt);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,q,Yt]),!(e&&Ge===`canvas`&&!Oe)&&z!==null&&ee(null),(0,Q.useEffect)(()=>{let t=!1;if(!(!e||Ge!==`canvas`||Oe))return ra(e,K,q).then(e=>{t||ee(e)}).catch(()=>{t||ee(null)}),()=>{t=!0}},[e,K,q,Ge,Oe]);let vn=async()=>{if(c){E(!0);try{let t=await so(e||c.id);l(t),i({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;i({title:`Error`,description:t,variant:`destructive`})}finally{E(!1)}}},yn=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`Document from "${K}"`});try{await _i(e||c.id,[t],K,[],q,Dn,{trashIfOrphaned:!0}),aD(e||c.id,q,K),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document removed from workspace path.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},bn=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`Document from "${K}"`});try{await ai(e||c.id,[t],K,[],q,Dn),aD(e||c.id,q,K),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},xn=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`${t.length} document(s) from "${K}"`});try{await _i(e||c.id,t,K,[],q,Dn,{trashIfOrphaned:!0}),aD(e||c.id,q,K),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Sn=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`${t.length} document(s)`});try{await ai(e||c.id,t,K,[],q,Dn),aD(e||c.id,q,K),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Cn=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await La(e||c.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},wn=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await La(e||c.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);p(e=>e.filter(e=>!i.has(e.id))),_(e=>Math.max(0,e-i.size));let a=[r.successful?.length?`${r.successful.length} destroyed`:null,r.failed?.length?`${r.failed.length} failed`:null].filter(Boolean).join(`, `);r.failed?.length?n.fail({title:`Destroy incomplete`,description:a,variant:`destructive`}):n.done({title:`Destroyed`,description:a||`No documents destroyed`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},Tn=e=>{O({documentIds:e,operation:`copy`,sourcePath:K,sourceTreeName:q}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},En=e=>{O({documentIds:e,operation:`cut`,sourcePath:K,sourceTreeName:q}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Dn=ka(q),On=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??q,o=r.targetTreeType??Dn,s=r.move??D?.operation===`cut`,c=a({title:s?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let a=await Qr(e,t,n,i,o);if(a){aD(e,i,t);let a=r.sourceTreeName||D?.sourceTreeName,o=r.sourcePath||D?.sourcePath;if((r.move??D?.operation===`cut`)&&o&&a){let t=ka(a);await _i(e,n,o,[],a,t),aD(e,a,o),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:o,treeName:a}}))}c.done({title:`Success`,description:`${n.length} document(s) ${s?`moved`:`pasted`} to "${t}"`}),O(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await qt(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else c.done();return a}catch(e){return c.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},kn=async(t,n)=>{if(!e)return!1;try{let r=(await ya(e,n,t,q,Dn)).length>0;return r&&(kb(e,q,n),i({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},An=async()=>{if(!c||Mt===0||Ut||Ht.current||window.prompt(`Type PURGE to permanently delete all ${Mt} matching documents across all pages.`)!==`PURGE`)return;Ht.current=!0,Vt(!0);let t=a({title:`Purging…`,description:`${Mt} matching document(s)`});try{let n=await pi(e||c.id,It,Mt);n.deleted===n.requested?t.done({title:`Success`,description:`${n.deleted} document(s) purged.`}):t.fail({title:`Purge incomplete`,description:`${n.deleted} of ${n.requested} document(s) purged. Refresh and review the remaining results before retrying.`})}catch(e){t.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}finally{aD(e||c.id,q,K),await qt({silent:!0}),Ht.current=!1,Vt(!1)}},jn=()=>nn(K,!0),Mn=async()=>{if(!(!e||!k||!j.trim())){P(!0);try{let t=j.trim(),n=k.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`,a={...H.filters,features:{...H.filters.features,allOf:nt}};await So(e,i,q,k.captureView?{metadata:{toolbox:a},querySpec:{features:a.features,filters:[...Xy(H.filters.timeline),...qy(H.filters.geo)],query:gn||void 0,sort:H.filters.sort?.sortBy?H.filters.sort:null}}:{}),A(null),Da(e,q);try{let t=await vi(e,q,{force:!0});je(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(Fx(e,i,q))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{P(!1)}}},Nn=async()=>{if(!(!e||Ge!==`canvas`)){I(!0);try{let t=z||await To(e,K,q);ee(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)}}},Pn=async()=>{if(z){I(!0);try{await $r(z.code),ee(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:q}})),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)}}},Fn=async()=>{if(!e||Ge!==`canvas`||K===`/`)return;let t=ot?.label||K.split(`/`).pop()||`canvas`,n=z?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){R(!0);try{if(z)await $r(z.code),ee(null);else if(We?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await na(e,K,!1,q);let n=K.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:q}})),r(Fx(e,a,q)),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{R(!1)}}},In=(0,Q.useCallback)(async t=>{if(!e||!Me)return;let n={treeName:q,path:K},r=Fe===`left`?n:Me,o=Fe===`left`?Me:n,s=Fe===`left`?Le:He;if(s.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let c=ka(o.treeName),l=a({title:t?`Moving…`:`Copying…`,description:`${s.length} document(s) → "${o.path}"`});try{if(!await Qr(e,o.path,s,o.treeName,c)){l.done();return}if(aD(e,o.treeName,o.path),t){let t=ka(r.treeName);await _i(e,s,r.path,[],r.treeName,t),aD(e,r.treeName,r.path)}[r,o].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),l.done({title:t?`Moved`:`Copied`,description:`${s.length} document(s) → "${o.path}"`})}catch(e){l.fail({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,Me,Fe,q,K,Le,He,i,a]);if((0,Q.useEffect)(()=>{if(!Me)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),In(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Me,In]),u)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!c)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let Ln=Ge===`canvas`&&!Oe&&!!We,Rn=!Ln&&!ye&&Je?(0,$.jsx)(SE,{views:Qe,activeId:$e,onSelect:rt,onSave:it,accentColor:Nm(c.color),onOpenToSide:e=>{Ne({treeName:q,path:K,viewId:e}),Ie(`right`)}}):void 0,zn=Se||c.status!==`active`?(0,$.jsxs)($.Fragment,{children:[Se&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{we(!Ce),ne(1)},"aria-pressed":Ce,className:J(`min-h-10 rounded-md border px-2 text-xs`,Ce&&`bg-warning/15 text-warning`),children:`Unfiled only`}),c.status!==`active`&&(0,$.jsx)(`button`,{type:`button`,onClick:vn,disabled:T,className:`min-h-10 rounded-md border px-2 text-xs`,children:T?`Starting…`:`Start`})]}):void 0,Bn=pb(q,K)?K===`/Trash`?(0,$.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,$.jsx)(dE,{workspaceName:e||c.id})}):(0,$.jsx)(sE,{workspace:e||c.id,path:K,onNavigate:t=>r(Fx(e,t,`backends`))},e):(0,$.jsx)(hE,{navigationTabs:Rn,navigationActions:zn,onBack:Ve,accentColor:Nm(c.color),urlType:Oe?ka(q)===`directory`?`${q}-layer`:`context-layer`:Ge===`canvas`?`canvas`:ka(q)===`directory`?q:`context`,urlDisplay:_t,contextPath:K,treeName:q,workspaceId:e||c.id,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,documentSchema:tt,documents:Ft,isLoading:m,totalCount:Mt,currentPage:te,pageSize:B,onPageChange:ne,onPageSizeChange:e=>{re(e),ne(1)},onRemoveDocument:K===`/`?void 0:yn,onDeleteDocument:bn,onDestroyDocument:Cn,onRemoveDocuments:K===`/`?void 0:xn,onDeleteDocuments:Sn,onDestroyDocuments:wn,onCopyDocuments:Tn,onCutDocuments:En,onPasteDocuments:ye?void 0:On,onImportDocuments:ye?void 0:kn,onSelectionChange:Re,onBrowseTree:()=>Be(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>ze(`workspaces`),onNavigatePath:t=>r(Fx(e,t,q)),folders:qe,onOpenFolder:t=>r(Fx(e,Mx(t),q)),scope:C,onScopeChange:w,pastedDocumentIds:D?.documentIds,linkTree:Ae,onPurgeDocuments:ye?void 0:An,disablePurgeDocuments:Ut,canvasInfo:ot??void 0,isCanvasPinned:pt,onTogglePinCanvas:ft?gt:void 0,onSaveAsCanvas:Ae&&Ge!==`canvas`&&!Oe&&!ye?jn:void 0,onShareCanvas:Ge===`canvas`&&!Oe?Nn:void 0,onUnshareCanvas:z?Pn:void 0,onDeleteCanvas:Ge===`canvas`&&!Oe?Fn:void 0,isSharingCanvas:F,isDeletingCanvas:L,isCanvasShared:!!z,isCanvasLocked:!!We?.locked,backendSearchQueries:ie,onBackendSearch:mn,serverSort:H.filters.sort,onServerSortChange:se,onRemoveBackendQuery:hn,canSaveChanges:_n,isSavingChanges:H.isSaving,onSaveChanges:U,contentBanner:v&&y?(0,$.jsx)(eD,{data:y,className:`mb-3`}):null,children:Ln&&We?(0,$.jsx)(iS,{workspaceId:e||c.id,treeName:q,path:K,layerId:We.id,querySpec:We.querySpec,metadata:We.metadata,isLocked:!!We.locked,fetchDocuments:H.isDirty?yt:void 0}):!ye&&et.kind===`columns`?(0,$.jsx)(OE,{documents:Ft,workspaceId:e||c.id,columns:et.columns??[],onColumnsChange:e=>it(Qe.map(t=>t.id===et.id?{...t,columns:e}:t))}):!ye&&et.kind===`app`&&et.app&&et.app!==`notes`?(0,$.jsx)(TE,{app:et.app,workspaceId:e||c.id,treeName:q,path:K}):null});return(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0`,children:[(0,$.jsx)(mE,{workspaceId:c.id,workspaceName:c.label||c.name},c.id),pb(q,K)&&(0,$.jsx)(Zg,{workspace:c.label||c.name,workspaceIcon:c.icon,tree:q,path:K,onBack:Ve,onBrowseTree:()=>Be(`workspaces`,`detail`,e||c.id),onBrowseWorkspaces:()=>ze(`workspaces`),onNavigatePath:t=>r(Fx(e,t,q)),accentColor:Nm(c.color)}),k&&(0,$.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,$.jsx)($w,{title:`New canvas`,onClose:()=>A(null),children:(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Mn()},className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,$.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:j,onChange:e=>M(e.target.value),onKeyDown:e=>{e.key===`Escape`&&A(null)},autoFocus:!0})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,$.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:k.parentPath===`/`?`/`:k.parentPath})]})]}),(0,$.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:k.captureView,onChange:e=>A({...k,captureView:e.target.checked})}),(0,$.jsxs)(`span`,{children:[`Capture the current view`,(0,$.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:!j.trim()||N,children:N?`Creating…`:`Create canvas`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})})}),(0,$.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,$.jsx)(`div`,{"data-canvas-pane":!0,className:J(`flex-1 min-w-0 bg-background overflow-hidden`,Me&&(Fe===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||Ie(`left`)},children:Bn}),Me&&e&&(0,$.jsx)(dD,{workspaceName:e,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,pane:Me,isFocused:Fe===`right`,clipboard:D,setClipboard:O,onFocus:()=>Ie(`right`),onSelectionChange:Ue,onNavigate:e=>Ne(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Ne(null),Ie(`left`),Ue([])}})]})]})}function uD(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 dD({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:u}){let{openM1Drawer:d,openM2Drawer:f}=PT(),{showToast:p,showProgress:m}=Vr(),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(0),[C,w]=(0,Q.useState)(1),[T,E]=(0,Q.useState)(50),D=ka(r.treeName),O=uD(h,r.path),k=O?.type===`canvas`,A=(0,Q.useMemo)(()=>D===`directory`?tD(h,r.path):[],[h,r.path,D]),j=r.viewId?bE(O?.metadata).find(e=>e.id===r.viewId)??null:null,M=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,N=_E(j),P=(0,Q.useCallback)(async()=>{if(pb(r.treeName,r.path)){v([]),S(0),b(!1);return}let t=iD(e,r.treeName,r.path,C,T,``,N??``),n=nD.get(t);if(n){v(n.documents),S(n.totalCount);return}b(!0);try{let n=await Na(e,r.path,N?[N]:[],{limit:T,page:C,treeName:r.treeName,treeType:D}),i=n.payload||[],a=n.totalCount||n.count||0;v(i),S(a),nD.set(t,{documents:i,totalCount:a})}catch(e){p({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),v([]),S(0)}finally{b(!1)}},[e,r.path,r.treeName,D,T,C,p,N]);(0,Q.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&Da(e,r.treeName),vi(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,g(e))}).catch(()=>{!t&&o===n&&!i&&g(null)})};a(!1);let o=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==r.treeName||a(!n?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{t=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,r.treeName]),(0,Q.useEffect)(()=>{P()},[P]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(sD(e,n),RE(LE(n),{tree:r.treeName,kind:ka(r.treeName),path:r.path})&&(aD(e,r.treeName,r.path),P()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[P,e,r.treeName,r.path]);let F=(0,Q.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??D,l=i.move??a?.operation===`cut`,u=m({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await Qr(e,t,n,s,c);if(r){aD(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=ka(c);await _i(e,n,r,[],c,t),aD(e,c,r),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:r,treeName:c}}))}u.done({title:`Success`,description:`${n.length} document(s) ${l?`moved`:`pasted`} to "${t}"`}),o(null),await P(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:s}}))}else u.done();return r}catch(e){return u.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,r.treeName,D,P,m,a,o]),I=(0,Q.useCallback)(()=>{aD(e,r.treeName,r.path),P()},[e,r.treeName,r.path,P]),L=(0,Q.useCallback)(async t=>{let n=m({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await _i(e,t,r.path,[],r.treeName,D),I(),n.done({title:`Removed`,description:`${t.length} document(s) removed from "${r.path}"`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,I,m]),R=(0,Q.useCallback)(async t=>{let n=m({title:`Deleting…`,description:`${t.length} document(s)`});try{await ai(e,t,r.path,[],r.treeName,D),I(),n.done({title:`Deleted`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,I,m]),z=(0,Q.useCallback)(async t=>{let n=m({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await La(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}I();let i=`${r.successful?.length??0} document(s) destroyed${r.failed?.length?` · ${r.failed.length} failed`:``}.`;r.failed?.length?n.fail({title:`Destroy incomplete`,description:i,variant:`destructive`}):n.done({title:`Destroyed`,description:i})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,I,m]);return(0,$.jsxs)(`div`,{className:J(`relative flex-1 min-w-0 rounded-(--sheet-radius) border bg-background overflow-hidden`,i?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||s()},children:[u&&(0,$.jsx)(`button`,{type:`button`,onClick:u,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),pb(r.treeName,r.path)?r.path===`/Trash`?(0,$.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,$.jsx)(dE,{workspaceName:e})}):(0,$.jsx)(sE,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,$.jsx)(hE,{frameContent:!1,onBrowseWorkspaces:()=>d(`workspaces`),onBrowseTree:()=>f(`workspaces`,`detail`,e),urlType:k?`canvas`:D===`directory`?r.treeName:`context`,urlDisplay:M,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:N,documents:_,isLoading:y,totalCount:x,currentPage:C,pageSize:T,onPageChange:w,onPageSizeChange:e=>{E(e),w(1)},onRemoveDocument:r.path===`/`?void 0:e=>L([e]),onRemoveDocuments:r.path===`/`?void 0:L,onDeleteDocument:e=>R([e]),onDeleteDocuments:R,onDestroyDocument:e=>z([e]),onDestroyDocuments:z,onCopyDocuments:e=>{o({documentIds:e,operation:`copy`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{o({documentIds:e,operation:`cut`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:r.treeName===`backends`?void 0:F,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:h,folders:A,onOpenFolder:l,onNavigatePath:l,canvasInfo:k?{label:O?.label,description:O?.description,color:O?.color}:void 0,children:j?.kind===`columns`?(0,$.jsx)(OE,{documents:_,workspaceId:e,columns:j.columns??[],onColumnsChange:()=>{},readOnly:!0}):j?.kind===`app`&&j.app&&j.app!==`notes`?(0,$.jsx)(TE,{app:j.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}function fD(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(!e)return;let t=!1,r=()=>{qr(e).then(r=>{t||n({ref:e,workspace:r})}).catch(()=>{})};return r(),window.addEventListener(`workspaces:refresh`,r),()=>{t=!0,window.removeEventListener(`workspaces:refresh`,r)}},[e]),t?.ref===e?t?.workspace:void 0}function pD(){let{workspaceName:e}=bl();return e?(0,$.jsx)(pE,{workspaceName:e,children:(0,$.jsx)(mD,{})}):(0,$.jsx)(`p`,{role:`alert`,className:`p-6`,children:`Workspace not specified.`})}function mD(){let{workspaceName:e=``,documentId:t=``,algo:n=``,checksum:r=``}=bl(),i=gl(),a=pl(),{goBack:o,openM1Drawer:s,openM2Drawer:c}=PT(),l=fD(e),u=!!n&&!!r,d=u?`${n}/${r}`:t,f=JSON.stringify([e,t,n,r]),p=Number(t),m=/^\d+$/.test(t)&&Number.isSafeInteger(p)&&p>0,h=u||m,[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(null),b=v?.identity===f?v:null,x=h&&(!b||b.revision!==g);(0,Q.useEffect)(()=>{let t=!1;if(h)return(u?ao(e,n,r):Ja(e,p)).then(e=>{t||y({identity:f,revision:g,document:e||null,missing:!e,error:``})}).catch(e=>{t||y({identity:f,revision:g,document:null,missing:e?.statusCode===404,error:e instanceof Error?e.message:`Unable to retrieve this document.`})}),()=>{t=!0}},[e,p,f,g,h,u,n,r]);let S={workspace:l?.label||e,workspaceIcon:l?.icon,path:`/`,tree:`context`,document:b?.document?Yr(b.document).title:`Document ${d}`,onBack:o,onBrowseWorkspaces:()=>s(`workspaces`),onBrowseTree:()=>c(`workspaces`,`detail`,e),onNavigatePath:t=>i(Fx(e,t,`context`))},C=a.hash.slice(1),w=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`].includes(C)?C:`view`;return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[!b?.document&&(0,$.jsx)(Zg,{...S}),b?.document?(0,$.jsx)(By,{document:b.document,workspaceId:e,onChanged:()=>_(e=>e+1),navigation:S,initialTab:w,onTabChange:e=>i(`${a.pathname}${a.search}#${e}`,{replace:!0}),tabActions:(0,$.jsx)(Z,{variant:`ghost`,disabled:x,onClick:()=>_(e=>e+1),children:`Refresh`})},f):x?(0,$.jsx)(`p`,{role:`status`,className:`p-6 text-sm text-muted-foreground`,children:`Loading document…`}):(0,$.jsxs)(`div`,{role:`alert`,className:`space-y-2 p-6 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium`,children:b?.missing?`Document ${d} not found`:`Unable to load document`}),h&&(0,$.jsx)(Z,{variant:`outline`,onClick:()=>_(e=>e+1),children:`Retry`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:h?b?.missing?`This record is no longer available in this workspace. Subtree exports skip missing records and report their IDs.`:b?.error:`Document ID must be a positive integer.`})]})]})}function hD(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 gD={id:`sketch`,label:`Sketch`,icon:le,schemas:[Mi],canCreate:!0,canEdit:e=>e.schema===Mi,createUrl(e){let t=hD(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=hD(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},_D=[{kind:`message`,label:`New Message`,icon:b},{kind:`note`,label:`Note`,icon:Kn},{kind:`link`,label:`Link`,icon:_n},{kind:`todo`,label:`Todo`,icon:Vt},{kind:`identity`,label:`Identity`,icon:We},{kind:`sketch`,label:`Sketch`,icon:le},{kind:`plaintext`,label:`Plaintext file`,icon:nn},{kind:`file`,label:`File`,icon:Qe},{kind:`photo`,label:`Photo/Video`,icon:Ke},{kind:`existing`,label:`Existing document`,icon:En},{kind:`folder`,label:`Folder`,icon:st}];function vD(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?_D:_D.filter(e=>e.kind!==`photo`)}function yD({onSelect:e,variant:t=`list`,omit:n}){let r=vD().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,$.jsx)($.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex items-center gap-2 rounded-full bg-card px-3 py-1.5 text-sm font-medium shadow-elevation-3 transition-transform hover:scale-105`,children:[n,(0,$.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,$.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted`,children:[(0,$.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}function bD(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 xD({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,Q.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{role:`switch`,"aria-checked":e.enabled,"aria-disabled":i,"aria-label":`Geotag this document`,"aria-describedby":`${t}-hint`,tabIndex:i?-1:0,onClick:()=>!i&&e.setEnabled(!e.enabled),onKeyDown:t=>{i||(t.key===` `||t.key===`Enter`)&&(t.preventDefault(),e.setEnabled(!e.enabled))},className:J(`flex flex-1 items-center justify-between gap-3 select-none outline-none rounded focus-visible:ring-2 focus-visible:ring-ring`,i?`cursor-not-allowed opacity-50`:`cursor-pointer`),children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,$.jsx)(Yn,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,$.jsx)(tn,{className:J(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,$.jsx)(`div`,{className:J(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,$.jsx)(`div`,{className:J(`absolute top-[2px] h-4 w-4 rounded-full bg-background shadow-elevation-1 transition-transform`,e.enabled?`translate-x-[22px]`:`translate-x-[2px]`)})})]}),(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(!0),title:`Pick a point on the map`,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(Ln,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.setManual(null),"aria-label":`Remove custom pin`,title:`Remove custom pin`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]}),(0,$.jsx)(`p`,{id:`${t}-hint`,className:J(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:bD(e)}),n&&(0,$.jsx)(dg,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}function SD(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 CD({title:e,icon:t,onClose:n,onSave:r,navigateAfterSave:i=!1,canSave:a=!1,saving:o=!1,saveProgress:s,successMessage:c=`Saved`,lockedWorkspaceName:l,fillParent:u=!1,fullWidthContent:d=!1,relationSubjectId:f,frame:p,children:m,maximized:h,onMaximizedChange:g}){let _=gl(),[v,y]=(0,Q.useState)(`portrait`),[b,x]=(0,Q.useState)(!1),S=h??b,C=e=>{x(e),g?.(e)},[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),A=o||O;Fp(()=>T(!1),w&&!A),Fp(()=>C(!1),S&&!w);let M=(0,Q.useRef)(null),N=l_(),{showSuccessToast:P,showErrorToast:F}=Wr(),I=N&&!u&&!S,[L,R]=(0,Q.useState)(!1),z=!u&&!S&&!p&&!L;(0,Q.useEffect)(()=>{w&&M.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[w]);let ee=async(e,t)=>{if(!(!r||A)){k(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>Qr(t.workspaceName,e,a,t.treeName,t.treeType))),P(c),n(),i&&_(SD({...t,path:e[0]}),{replace:!0})}catch(e){F(e instanceof Error?e.message:`Failed to save`)}finally{k(!1)}}},te=async e=>{if(!(!f||!l||e.targetIds.length===0)){D(!0);try{await go(l,f,e.predicate,e.targetIds,e.direction),P(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Rg(),T(!1)}catch(e){F(e instanceof Error?e.message:`Failed to create relations`)}finally{D(!1)}}},ne=S?w?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:I?void 0:v===`portrait`?{aspectRatio:`0.707 / 1`,height:`calc(var(--viewport-h) * 0.85)`,width:`auto`,maxWidth:`min(90vw, 100%)`,flexShrink:0}:{aspectRatio:`1 / 0.707`,width:`min(90vw, 900px)`,maxWidth:`100%`,height:`auto`,maxHeight:`calc(var(--viewport-h) * 0.85)`,flexShrink:0},B=!!(f&&l),re=r&&w&&(0,$.jsx)(ih,{onClose:()=>T(!1),onConfirm:ee,fixedWorkspaceName:l,saving:A||E,savingContent:s,tabs:B?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:B?te:void 0,relationWorkspaceName:l,relationExcludeIds:B?new Set([f]):void 0,sizeClassName:p?`h-full max-h-full w-full min-w-0 rounded-none border-0 shadow-none`:u?`h-full max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`:void 0}),ie=(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>y(e=>e===`portrait`?`landscape`:`portrait`),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground max-md:hidden touch-target`,"aria-label":`Toggle orientation`,title:`Toggle orientation`,children:(0,$.jsx)(j,{className:`h-4 w-4`})}),r&&(typeof m==`function`?(0,$.jsx)(`button`,{type:`button`,onClick:()=>T(!0),disabled:!a||A,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":A?`Saving…`:`Add relations / Link to…`,title:`Add relations / Link to…`,children:(0,$.jsx)(Zt,{className:`h-4 w-4`})}):(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:()=>T(!0),disabled:!a||A,children:A?`Saving…`:`Save / Link to…`})),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p&&!S?p.onToggleExpanded():C(!S),className:J(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`,!S&&!p&&`max-md:hidden`),"aria-label":p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,title:p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,children:S||p?.expanded?(0,$.jsx)(lt,{className:`h-4 w-4`}):(0,$.jsx)(xn,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{type:`button`,onClick:n,disabled:A,className:J(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`),"aria-label":`Close`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),ae=(0,$.jsxs)(`div`,{style:{...p&&!S?{width:`100%`,height:`100%`,minWidth:0}:ne,"--document-reading-width":S&&!d?`48rem`:`100%`},onAnimationEnd:e=>{z&&e.target===e.currentTarget&&R(!0)},className:J(`flex flex-col overflow-hidden`,p&&!S?`strip-document-card`:`rounded-(--card-radius) border bg-card shadow-elevation-4 transition-[width,height]`,u&&!S&&!p&&`w-full`,I&&`fixed inset-2 z-40 shadow-elevation-5`,z&&`animate-card-in`),children:[typeof m!=`function`&&(0,$.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,$.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate`,children:e})]}),ie]}),(0,$.jsx)(zg.Provider,{value:()=>C(!S),children:(0,$.jsx)(`div`,{className:J(`min-h-0 flex-1 overflow-y-auto`,S&&!d&&typeof m!=`function`&&`mx-auto w-full max-w-3xl`),children:p&&re?re:typeof m==`function`?m(ie):m})})]});return S?(0,Ip.createPortal)((0,$.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[ae,re&&(0,$.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:re})]}),document.body):(0,$.jsxs)($.Fragment,{children:[ae,!p&&re&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!A&&T(!1),"aria-hidden":!0}),(0,$.jsx)(`div`,{ref:M,className:`relative shrink-0 md:z-panel md:ml-2 md:pr-2 max-md:fixed max-md:bottom-2 max-md:left-2 max-md:right-2 max-md:top-2 max-md:z-card-overlay max-md:animate-fade-in`,children:re})]})]})}function wD({onClose:e,initialData:t,draftId:n}){let r=yS(void 0,void 0,`home-card:${n}`);return(0,Q.useEffect)(()=>{t?.title&&r.setTitle(t.title),t?.content&&r.setContent(t.content)},[]),(0,$.jsx)(CD,{title:`New Note`,icon:Kn,onClose:e,onSave:async e=>{let t=await r.save({mode:`workspace`,...e});return r.finish(),t},canSave:r.canSave,saving:r.saving,successMessage:`Note created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`qa-note-title`,value:r.title,onChange:e=>r.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,$.jsx)(Gu,{children:`Body`}),(0,$.jsx)(`div`,{className:`flex-1`,children:(0,$.jsx)(Ho,{kind:`markdown`,value:r.content,onChange:r.setContent,placeholder:`Write your note…`})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:r.tags,onChange:r.setTags})]}),(0,$.jsx)(Go,{...r,onRetry:r.retry}),(0,$.jsx)(xD,{geotag:r.geotag,idPrefix:`qa-note-geotag`})]})})}var TD=`data/schema/tab`,ED=`2.0`;function DD(e){try{return new URL(e),!0}catch{return!1}}function OD(){let[e,t]=(0,Q.useState)(``),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),c=R_(),l=e.trim(),u=DD(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:TD,schemaVersion:ED,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:Yo(i),...t?{geo:t}:{}}};return await ys(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 kD({onClose:e,initialData:t}){let n=OD();return(0,Q.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,$.jsx)(CD,{title:`New Link`,icon:_n,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-link-url`,children:`URL`}),(0,$.jsx)(Y,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-link-title`,children:`Title`}),(0,$.jsx)(Y,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsx)(xD,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function AD({onClose:e,initialData:t}){let n=J_();return(0,Q.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,$.jsx)(CD,{title:`New Todo`,icon:Vt,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsx)(Gv,{...n,idPrefix:`qa-todo`}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`qa-todo-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,$.jsx)(xD,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function jD({onClose:e,initialData:t}){let n=ey();return(0,Q.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,$.jsx)(CD,{title:`New Identity`,icon:We,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsx)(ay,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`qa-identity-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]})]})})}var MD=3;function ND(e){return`${e.name}:${e.size}:${e.lastModified}`}function PD(e=[]){let[t,n]=(0,Q.useState)(()=>e.map(e=>({id:ND(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(t),o=(0,Q.useRef)(null),s=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,Q.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,Q.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,Q.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(ND(e))).map(e=>({id:ND(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,Q.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,Q.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,Q.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,Q.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await Ms(e),d=r===`backends`?await ks(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(MD,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 Ur(n,{...d,key:hs(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 Ns(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 Kr(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(MD,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 Hr(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 ys(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`)&&_s(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 FD(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ID(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 FD(e.file.size)}}function LD({item:e}){switch(e.status){case`done`:return(0,$.jsx)(oe,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,$.jsx)(z,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,$.jsx)(Rn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,$.jsx)(Yn,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function RD({item:e}){if(e.status===`queued`)return null;let t=e.status===`done`||e.status===`error`||e.status===`linking`?1:e.status===`checking`?0:e.progress;return(0,$.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:J(`h-full rounded-full transition-[width] duration-normal`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function zD({items:e,running:t,onRemove:n}){let r=e.filter(e=>e.status===`done`).length,i=e.filter(e=>e.status===`error`).length;return(0,$.jsx)($.Fragment,{children:e.length>0&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(Gu,{children:[e.length,` file(s)`,r>0&&(0,$.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,$.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,$.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(LD,{item:e}),(0,$.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,$.jsx)(`span`,{className:J(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:ID(e)}),!t&&e.status!==`done`&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(RD,{item:e})]},e.id))})]})})}function BD({items:e,running:t,onCancel:n}){return(0,$.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,$.jsx)(zD,{items:e,running:!0,onRemove:()=>{}}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function VD(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return Xr(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var HD=`data/schema/file`,UD=`3.0`;function WD(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:VD(e),geotag:R_()}}function GD(e,t,n={}){let r=Yo(n.tags??[]),i=n.comment?.trim();return{schema:HD,schemaVersion:UD,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 KD=`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 qD({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${t}-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`${t}-comment`,value:e.comment,onChange:t=>e.setComment(t.target.value),rows:3,placeholder:`Optional; searchable, and the only text a photo has`,className:KD}),n&&e.tags.length+e.comment.trim().length>0&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,$.jsx)(xD,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var JD={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 YD(e){return/^(image|video)\//.test(e.type)}async function XD(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
21
+ `)+(n.length>5?`\n…and ${n.length-5} more paths`:``);return window.confirm(`Permanently delete ${t.length} Trash item(s) from ${e}?\n\n${r}\n\nDeleted folders include all their contents. This cannot be undone. Files currently at the original paths are kept.`)}async function Cb(e,t){let n=pb(`backends`,t);if(!n?.backend)return;let{items:r}=await _b(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Sb(n.backend,i))return;let a=await yb(e,n.backend,i.map(e=>e.id)),o=a.filter(e=>!e.ok);if(o.length)throw Error(`${a.length-o.length} deleted; ${o.length} remain in Trash. ${o[0].message||o[0].reason||`Please retry.`}`)}function wb(){let{showProgress:e}=Vr();return(0,Q.useCallback)(async(t,n,r,i)=>{let a=e({title:t,description:n});try{let e=await i();if(e===!1)throw Error(`The operation could not be completed.`);return a.done({title:r,description:n}),e}catch(e){throw a.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}},[e])}var Tb=new Map;function Eb(e,t,n,r,i){let a=JSON.stringify([t,n,r]),o=Tb.get(a);if(o)return o;let s=(async()=>{let a=e({title:`Resyncing…`,description:r});try{for(await va(t,n,r);;){let e=await Xi(t,n,r);if(i?.(e),!e.resyncing&&e.status!==`syncing`){if(e.lastError)throw Error(e.lastError);a.done({title:e.resyncCancelledAt?`Resync stopped`:`Resync complete`,description:`${r}${e.progress?` · ${e.progress.scanned} files scanned`:``}`}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t,treeName:`backends`}}));return}let o=e.progress;a.update({title:`Resyncing…`,description:`${r}${o?` · ${o.scanned}${o.total==null?``:` / ${o.total}`} files scanned`:``}`}),await new Promise(e=>setTimeout(e,2e3))}}catch(e){throw a.fail({title:`Resync needs attention`,description:`${r}: ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return Tb.set(a,s),s.finally(()=>{Tb.get(a)===s&&Tb.delete(a)}).catch(()=>{}),s}var Db=[`tree.path.inserted`,`tree.path.moved`,`tree.path.removed`,`tree.path.copied`,`tree.path.locked`,`tree.path.unlocked`,`tree.layer.updated`,`tree.layer.converted`,`tree.recalculated`,`tree.created`,`tree.deleted`,`tree.renamed`,`context.path.changed`,`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`],Ob=new Map;function kb(e,t,n){Da(e,t),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t,cacheInvalidated:!0}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}function Ab(e,t){let n=Ob.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=Db.map(n=>{let a=(a={})=>{if(n===`backend.resync.changed`&&a.resyncing!==!1)return;let o=typeof a.workspaceId==`string`?a.workspaceId:null,s=typeof a.workspaceName==`string`?a.workspaceName:null;if(o&&!t.has(o)||!o&&s&&s!==e)return;let c=typeof a.treeName==`string`?a.treeName:void 0;n===`tree.renamed`?c=void 0:n===`context.path.changed`?c??=`context`:[`backend.tree.changed`,`backend.changed`,`backend.resync.changed`,`dataBackends.changed`,`services.changed`,`connect`].includes(n)&&(c??=`backends`),r.add(c),!i&&(i=setTimeout(()=>{i=void 0;let t=r.has(void 0)?[void 0]:[...r];r.clear();for(let n of t)Da(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return hd.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)Da(e,t);a.forEach(([e,t])=>hd.off(e,t))}},Ob.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),Ob.delete(e))}}function jb({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=wb(),{showProgress:a}=Vr(),o=n||`context`,s=o===`directory`,c=(0,Q.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),l=(0,Q.useCallback)(async(n,r=!0)=>{let i;if(e)i=await vs(e,n,r);else if(t)i=await Aa(t,n,r,o);else return!1;let a=Tm(n);if(i&&a)try{e?await ds(e,n,a):t&&await zi(t,n,a,o)}catch{}return c(),i},[e,t,o,c]),u=(0,Q.useCallback)(async(n,r=!1,a=!1,s=!1)=>i(s?`Destroying…`:a?`Purging…`:`Removing…`,n,s?`Destroyed`:a?`Purged`:`Removed`,async()=>{try{return e?await us(e,n,r):t?await na(t,n,r,o,a,s):!1}finally{c()}}),[e,t,o,c,i]),d=(0,Q.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await ms(e,n,t.join(`/`),!1)}else if(t)i=await zi(t,n,{name:r},o);else return!1;return c(),i},[e,t,o,c]),f=(0,Q.useCallback)(async(n,r,a=!1,s=o,l=o,u={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await ms(e,n,r,a,u);else if(t)i=await Ao(t,n,r,a,s,l,u);else return!1;return c(),i}),[e,t,o,c,i]),p=(0,Q.useCallback)(async n=>{let r;if(e)r=await Is(e,n);else if(t)r=await hi(t,n,o);else return null;return c(),r},[e,t,o,c]),m=(0,Q.useCallback)(async n=>{let r;if(e)r=await cs(e,n);else if(t)r=await Va(t,n,o);else return null;return c(),r},[e,t,o,c]),h=(0,Q.useCallback)(async(n,r,a=!1,s=o,l=o)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await bs(e,n,r,a);else if(t)i=await Ta(t,n,r,a,s,l);else return!1;return c(),i}),[e,t,o,c,i]),_=(0,Q.useCallback)(async(n,r)=>e?await ds(e,n,r):t?await zi(t,n,r,o):!1,[e,t,o]),v=(0,Q.useCallback)(async(n,r)=>{let i;if(e)i=await ts(e,n,r);else if(t)i=await Si(t,n,r,o);else return null;return c(),i},[e,t,o,c]),y=(0,Q.useCallback)(async(n,r)=>{let i;if(e)i=await Ts(e,n,r);else if(t)i=await mo(t,n,r,o);else return null;return c(),i},[e,t,o,c]),b=(0,Q.useCallback)(async e=>{if(!t)return!1;let n=await ci(t,e,t,o);return c(300),n},[t,o,c]),x=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;try{await Ea(t,e,n??t,o)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return c(300),!0},[t,o,c]),S=(0,Q.useCallback)(async e=>{if(!t)return!1;let n=await Jr(t,e,o);return c(),n},[t,o,c]),C=(0,Q.useCallback)(async e=>{if(!t)return!1;let n=await pa(t).catch(()=>[]),r=oo(e,n);return r?(await Eb(a,t,r.driver,r.address),c(300),!0):!1},[t,c,a]),w=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;let r=await pa(t).catch(()=>[]),i=ma(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await ca(t,i.driver,i.address,[a]),c(200),!0},[t,c]),T=(0,Q.useCallback)(async(e,n)=>{if(!t)return!1;let r=await pa(t).catch(()=>[]),i=ma(e,r);return!i||!i.key?!1:(await ea(t,i.driver,i.address,i.key,n),c(200),!0)},[t,c]),E=(0,Q.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await pa(t),r=po(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await Qi(t,r.driver,r.address,r.key),!0}finally{c(200)}}):!1,[t,c,i]),D=(0,Q.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await g(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-CSjPDp4d.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([29,3,4,10,11,13,12,14]));r({mode:e,path:n,workspaceId:t,treeName:o,onImported:()=>{kb(t,o),c()}})},[t,o,c]);return{onInsertPath:l,onRemovePath:u,onRenamePath:d,onMovePath:f,onCopyPath:h,onExportSubtree:t?e=>D(`export`,e):void 0,onImportSubtree:t&&o!==`backends`?e=>D(`import`,e):void 0,onUpdateNode:_,onMergeLayer:v,onSubtractLayer:y,onMergeDown:s?void 0:p,onSubtractDown:s?void 0:m,onLockLayer:t?b:void 0,onUnlockLayer:t?x:void 0,onDestroyLayer:t&&!s?S:void 0,onResyncBackend:t?C:void 0,onCreateBackendFolder:t?w:void 0,onRenameBackendFolder:t?T:void 0,onDeleteBackendFolder:t?E:void 0}}function Mb({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let u=gl(),d=jb({workspaceId:n,treeName:r}),f=r===`backends`,p=f?ma(i):null,[m,h]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{if(!f)return;let e=!1;return pa(n).then(t=>{e||h(t)}).catch(()=>{}),()=>{e=!0}},[n,f]);let g=f?po(i,m):null,_=i.split(`/`).filter(Boolean).pop()||i,[v,y]=(0,Q.useState)(void 0);(0,Q.useEffect)(()=>{let e=!1;return Ai(n).then(t=>{e||y(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||y(null)}),()=>{e=!0}},[n,r,i]);let b=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},x=(e,t,n,r=!1)=>(0,$.jsxs)(`button`,{type:`button`,className:J(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>b(n),children:[e,t]}),S=(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),C=e=>{let t=f?(()=>{let t=ep(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:np(i)};u(`/workspaces/${n}/settings/hooks?${tp(t).toString()}`)},w=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},T=pb(r,i);return T?(0,$.jsxs)(em,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[x((0,$.jsx)(nt,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),T.backend&&x((0,$.jsx)(ir,{className:`h-3 w-3`}),`Restore original paths`,()=>xb(n,i)),T.backend&&x((0,$.jsx)(nt,{className:`h-3 w-3`}),`Empty Trash`,()=>Cb(n,i),!0)]}):(0,$.jsxs)(em,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[x((0,$.jsx)(rt,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&x((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),S,f?p&&(0,$.jsxs)($.Fragment,{children:[x((0,$.jsx)(sn,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=w(`New folder name:`);e&&await d.onCreateBackendFolder?.(i,e)}),p.key&&x((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=w(`New folder name:`,_);e&&await d.onRenameBackendFolder?.(i,e)}),x((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create storage rule…`,()=>C(`store`))]}):(0,$.jsxs)($.Fragment,{children:[x((0,$.jsx)(sn,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=w(`New folder name:`);e&&await d.onInsertPath(`${i===`/`?``:i}/${e}`)}),x((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename`,async()=>{let e=w(`New name:`,_);e&&await d.onRenamePath(i,e)}),x((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create rule…`,()=>C(`store`)),x((0,$.jsx)(qt,{className:`w-3 h-3`}),`Create download rule…`,()=>C(`download`))]}),v!==void 0&&x(v?(0,$.jsx)(ee,{className:`w-3 h-3`}):(0,$.jsx)(Oe,{className:`w-3 h-3`}),v?`Unpin`:`Pin`,async()=>{v?await oa(n,v.id):await Yi(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),S,x((0,$.jsx)(A,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!f&&l&&c&&c.length>0&&x((0,$.jsx)(Ce,{className:`w-3 h-3`}),`Paste ${c.length} document(s)`,()=>l(i,c)),f?g&&(0,$.jsxs)($.Fragment,{children:[S,x((0,$.jsx)(nt,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${_}" and its contents from the backend?`)&&await d.onDeleteBackendFolder?.(i)},!0)]}):(0,$.jsxs)($.Fragment,{children:[S,x((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await d.onRemovePath(i,!0)},!0)]})]})}function Nb({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,Q.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,$.jsx)(Lp,{label:`Export Documents`,onClose:o,children:(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,$.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,$.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,$.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,$.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,$.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,$.jsxs)(Z,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,$.jsx)(A,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,$.jsx)(`textarea`,{className:`w-full min-h-24 flex-1 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,$.jsx)(`div`,{className:`mt-8 pt-4 border-t flex justify-end`,children:(0,$.jsx)(Z,{onClick:o,children:`Close`})})]})})}function Pb({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.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,Ip.createPortal)((0,$.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,$.jsx)(`div`,{className:`bg-background border rounded-(--panel-radius) 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,$.jsxs)(`div`,{className:`p-6`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data containing documents to import`})]}),(0,$.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,$.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,$.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,$.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,$.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,$.jsx)(Z,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,$.jsx)(Z,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function Fb({document:e}){let{replicating:t,label:n}=bo(e);return t?(0,$.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,$.jsx)(Yn,{className:`h-3 w-3 animate-spin`}),n]}):null}function Ib(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:lm(e.currentTarget,`inside`)}function Lb({documentId:e,onOpenActions:t,className:n}){return t?(0,$.jsx)(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),t(n.currentTarget,e)},className:`rounded-sm p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground ${n??``}`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,$.jsx)(Qt,{className:`h-4 w-4`})}):null}function Rb(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function zb({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Ep(),[c,l]=(0,Q.useState)(!1),{replicating:u}=bo(e),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=Yr(e),m=Vb(e),h=m||Ub(e),{blobUrl:g}=__(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),_=t=>{o?.(t,e.id)},v=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),y=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),b=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||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},x=e=>{e.shiftKey&&e.preventDefault()},S=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(jg,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>Rb(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring transition-opacity ${u?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:b,onMouseDown:x,...s,onContextMenu:S,draggable:!0,onDragStart:_,children:[(0,$.jsx)(Ng,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,$.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,$.jsx)(Ng,{className:`w-12`,children:g?(0,$.jsx)(`img`,{src:g,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,$.jsx)(Gm,{document:e,chip:!0})}),(0,$.jsx)(Ng,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),p.isExternal&&(0,$.jsx)(Ht,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,$.jsx)(Fb,{document:e})]}),p.subtitle&&(0,$.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,$.jsx)(Ng,{className:`hidden md:table-cell`,children:(0,$.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:p.schemaLabel})}),(0,$.jsx)(Ng,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,$.jsx)(Ng,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:y&&(0,$.jsx)(`span`,{className:`font-mono`,title:`${y.algo} checksum`,children:y.hash})}),(0,$.jsx)(Ng,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,$.jsx)(Ng,{className:`w-12 text-right`,children:(0,$.jsx)(Lb,{documentId:e.id,onOpenActions:a})})]}),(0,$.jsx)(Hy,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function Bb({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Ep(),[c,l]=(0,Q.useState)(!1),u=e.schema===`data/schema/tab`,{replicating:d}=bo(e),f=u?e.data.url:null,p=Yr(e),m=Vb(e),h=m||Ub(e),{blobUrl:g,loading:_}=__(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),v=t=>{o?.(t,e.id)},y=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),b=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),x=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||(u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},S=e=>{e.shiftKey&&e.preventDefault()},C=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>Rb(n,()=>u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${d?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${u&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:x,onMouseDown:S,...s,onContextMenu:C,draggable:!0,onDragStart:v,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[h&&(0,$.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:g?(0,$.jsx)(`img`,{src:g,alt:p.title,loading:`lazy`,className:`h-full w-full object-cover`}):_?(0,$.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,$.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,$.jsx)(Gm,{document:e})})}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,$.jsx)(Gm,{document:e,chip:!0}),(0,$.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:p.title,children:p.title}),p.isExternal&&(0,$.jsx)(Ht,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,$.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:p.schemaLabel}),(0,$.jsx)(Fb,{document:e})]}),p.subtitle&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:p.subtitle,children:p.subtitle}),p.preview&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:p.preview}),(0,$.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,$.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,$.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),b&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,$.jsx)(he,{className:`h-3 w-3`}),(0,$.jsx)(`span`,{className:`font-mono`,title:`${b.algo} checksum`,children:b.hash})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,$.jsx)(et,{className:`h-3 w-3`}),(0,$.jsx)(`span`,{title:`Created: ${y(e.createdAt)}`,children:y(e.createdAt)})]})]})]}),(0,$.jsx)(Lb,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,$.jsx)(Hy,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function Vb(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Hb(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function Ub(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Wb({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Uo(e,t),[a,o]=(0,Q.useState)(!1);return i||a?(0,$.jsx)($.Fragment,{children:n}):r?(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,$.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,$.jsx)(xe,{className:`h-3.5 w-3.5`})})]}):(0,$.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function Gb({document:e,workspaceId:t,markdown:n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(()=>typeof IntersectionObserver>`u`);(0,Q.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}=Fo(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,$.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,$.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,$.jsx)(E_,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,$.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,$.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,$.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,$.jsx)(Gm,{document:e,size:10,chip:!0}),i&&s&&(0,$.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function Kb({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let c=Ep(),[l,u]=(0,Q.useState)(!1),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=Vb(e),m=Hb(e),h=p||Ub(e),g=Yr(e),_=fi(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||wi(e)),v=e.schema===`data/schema/file`&&(_===`markdown`||_===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,y=!h&&e.schema!==`data/schema/file`&&!!(g.preview||g.subtitle),{replicating:b}=bo(e),{blobUrl:x,loading:S}=__(n??``,e.id,768,{enabled:h,blobFallback:p,version:e.checksumArray?.[0]??null}),C=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||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0))},w=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>Rb(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0),()=>r?.(e.id,!t,!0)),className:`group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-(--card-radius) border transition cursor-pointer outline-none hover:shadow-elevation-2 focus-visible:ring-2 focus-visible:ring-ring ${b?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:C,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...c,onContextMenu:w,draggable:!0,onDragStart:t=>s?.(t,e.id),title:g.title,children:[(0,$.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,$.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${h&&x||y||v&&n||m&&n?``:`aspect-square`}`,children:[h&&S&&(0,$.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),h&&x?(0,$.jsx)(`img`,{src:x,alt:g.title,loading:`lazy`,className:`block h-auto w-full`}):m&&n?(0,$.jsx)(Wb,{workspaceId:n,documentId:e.id,fallback:(0,$.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,$.jsx)(Gm,{document:e,size:10,chip:!0})})}):v&&n?(0,$.jsx)(Gb,{document:e,workspaceId:n,markdown:_===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):y?(0,$.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,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(Gm,{document:e}),(0,$.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:g.schemaLabel})]}),(0,$.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:g.title}),g.subtitle&&(0,$.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:g.subtitle}),(0,$.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:g.preview})]}):(0,$.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,$.jsx)(Gm,{document:e,size:10,chip:!0})}),(0,$.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,$.jsx)(`button`,{onClick:t=>{t.stopPropagation(),i(e)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Open to the side`,children:(0,$.jsx)(Ze,{className:`h-3.5 w-3.5`})}),o&&(0,$.jsx)(`button`,{onClick:t=>{t.stopPropagation(),o(t.currentTarget,e.id)},className:`rounded-sm bg-scrim p-1 text-scrim-foreground`,title:`Actions`,"aria-label":`Document actions`,"aria-haspopup":`menu`,children:(0,$.jsx)(Qt,{className:`h-3.5 w-3.5`})})]})]}),!y&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,$.jsx)(`span`,{className:`truncate text-xs font-medium`,title:g.title,children:g.title}),g.isExternal&&(0,$.jsx)(Ht,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,$.jsx)(Hy,{document:e,isOpen:l,onClose:()=>u(!1),workspaceId:n})]})}function qb(e,t,n,r,i){let[a,o]=(0,Q.useState)(!1),s=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:a,onDragOver:e=>{!t||!s(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,a||o(!0))},onDragLeave:()=>o(!1),onDrop:async a=>{if(o(!1),!t||!s(a))return;a.preventDefault(),a.stopPropagation();let c=null;try{c=JSON.parse(a.dataTransfer.getData(`application/json`))}catch{c=null}if(!(c?.type!==`document`||!Array.isArray(c.documentIds)||c.documentIds.length===0)&&!_g(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function Jb(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function Yb({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,$.jsx)(sr,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,$.jsx)($e,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var Xb=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function Zb({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=qb(e,r,i,a,o);return(0,$.jsxs)(`button`,{type:`button`,title:Xb(e),onClick:()=>t?.(e.path),onContextMenu:t=>Jb(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.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 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,$.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,$.jsx)(Yb,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,$.jsx)(sr,{className:`hidden h-4 w-4 group-hover:block`}):(0,$.jsx)(rt,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,$.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,$.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function Qb({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=qb(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,$.jsxs)(`button`,{type:`button`,title:Xb(e),onClick:()=>t?.(e.path),onContextMenu:t=>Jb(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-(--card-radius) border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,$.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,$.jsx)(sr,{className:`h-10 w-10`,strokeWidth:1.5}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)($e,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,$.jsx)(rt,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c})]})}),(0,$.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,$.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function $b({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,$.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,$.jsx)(Qb,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function ex({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,$.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,$.jsx)(Zb,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function tx({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=qb(e,r,i,a,o);return(0,$.jsxs)(jg,{"data-selection-ignore":``,className:`cursor-pointer ${s.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:t=>Jb(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:Xb(e),children:[(0,$.jsx)(Ng,{className:`w-10`}),(0,$.jsx)(Ng,{className:`w-12`,children:(0,$.jsx)(Yb,{folder:e})}),(0,$.jsx)(Ng,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,$.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,$.jsx)(Ng,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,$.jsx)(Ng,{className:`hidden lg:table-cell`}),(0,$.jsx)(Ng,{className:`hidden lg:table-cell`}),(0,$.jsx)(Ng,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,$.jsx)(Ng,{className:`w-12 md:w-auto`})]})}function nx({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,$.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,$.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,$.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,$.jsx)(hr,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,$.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,$.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function rx({externalSearchQuery:e,toolbarActions:t,documents:n,isLoading:r,contextPath:i,treeName:a,workspaceId:o,totalCount:s,onRemoveDocument:c,onDeleteDocument:l,onDestroyDocument:u,onRemoveDocuments:d,onDeleteDocuments:f,onDestroyDocuments:p,onCopyDocuments:m,onCutDocuments:h,onPasteDocuments:g,onImportDocuments:v,onSelectionChange:y,pastedDocumentIds:b,viewMode:x=`card`,allowViewToggle:S=!1,activeContextUrl:C,currentContextUrl:w,currentPage:T=1,pageSize:D=50,onPageChange:O,onPageSizeChange:k,onPurgeDocuments:j,disablePurgeDocuments:M=!1,backendSearchQueries:N=[],onBackendSearch:P,onRemoveBackendQuery:F,serverSort:I,onServerSortChange:L,scope:R=`path`,onScopeChange:z,canSaveChanges:ee=!1,isSavingChanges:te=!1,onSaveChanges:ne,linkTree:ie,folders:ae,onOpenFolder:oe}){let[V,H]=(0,Q.useState)(()=>{if(!S)return x;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return x}),U=S?V:x,se=(0,Q.useCallback)(e=>{H(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[W,ce]=(0,Q.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),le=(0,Q.useCallback)(()=>{ce(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[ue,de]=(0,Q.useState)(new Set),fe=(0,Q.useCallback)(e=>{de(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[pe,me]=(0,Q.useState)(new Set),[he,ve]=(0,Q.useState)(null),[K,q]=(0,Q.useState)(null),ye=es(),be=!!(ye&&o),xe=(0,Q.useCallback)((e,t=!1)=>{if(!ye||!o)return;let r=e.map(e=>n.find(t=>t.id===e)).filter(e=>!!e);r.length!==0&&ye.openAddRelated({workspaceName:o,documents:r},t)},[ye,o,n]),[Se,we]=(0,Q.useState)(!1),[Te,Ee]=(0,Q.useState)(null),[De,Oe]=(0,Q.useState)(!1),[ke,Ae]=(0,Q.useState)(null),[je,Me]=(0,Q.useState)(!1),Ne=(0,Q.useRef)(!1),Ie=(0,Q.useRef)(!1),Le=a===`backends`&&R===`path`?ep(i):null;(0,Q.useEffect)(()=>()=>{Ne.current=!0},[]);let[Re,ze]=(0,Q.useState)(!1),[Ve,He]=(0,Q.useState)(null),[Ue,We]=(0,Q.useState)(!1),[Ge,Ke]=(0,Q.useState)(null),qe=jo()==null&&!!o,[Je,Xe]=(0,Q.useState)(null),[$e,et]=(0,Q.useState)(null),tt=!!(ie&&g),rt=!!o,{showSuccessToast:it,showErrorToast:at}=Wr(),{showProgress:ot}=Vr(),st=Eg(),ct=o?e=>st.open(e,o):void 0,lt=R===`workspace`,ut=lt?void 0:c,dt=lt?void 0:d,[ft,pt]=(0,Q.useState)(!1),[mt,ht]=(0,Q.useState)(!1),[gt,_t]=(0,Q.useState)(``),vt=e??gt,yt=e!==void 0,[bt,xt]=(0,Q.useState)(!1),Ct=N.length>0,wt=(0,Q.useRef)(null),Tt=(0,Q.useCallback)(()=>{_t(``),wt.current&&(wt.current.value=``)},[]);(0,Q.useEffect)(()=>{if(!S||window.matchMedia(`(max-width: 767px)`).matches)return;let e=wt.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[S]);let Dt=JSON.stringify([o,a,i]),[Ot,kt]=(0,Q.useState)(Dt);Dt!==Ot&&(kt(Dt),me(new Set),Ee(null),q(null),ve(null)),(0,Q.useEffect)(()=>{y?.(Array.from(pe))},[pe,y]);let At=(0,Q.useCallback)(()=>{if(!P)return;let e=vt.trim();e&&(P(e),Tt())},[P,vt,Tt]),jt=(0,Q.useCallback)(()=>{Tt(),F&&N.length>0&&F(-1)},[F,N.length,Tt]),Mt=(0,Q.useCallback)((e,t)=>{let n;pe.has(t)&&pe.size>1?n=Array.from(pe):(n=[t],me(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:R===`path`?i:void 0,sourceTreeName:a,sourceWorkspaceId:o};e.dataTransfer.setData(`application/json`,JSON.stringify(r)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[pe,i,a,o,R]),Nt=(0,Q.useCallback)(async e=>{if(!g)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let n=null;try{n=JSON.parse(t)}catch{return}n?.type!==`document`||!Array.isArray(n.documentIds)||n.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),xt(!1),!_g(n,o,a,i)&&(await g(i,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),me(new Set)))},[i,a,o,g]),Pt=(0,Q.useCallback)(e=>{g&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,xt(!0))},[g]),Ft=(0,Q.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||xt(!1)},[]),It=(0,Q.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}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),Lt=(0,Q.useMemo)(()=>n.length===0?null:new Qo(n,It),[n,It]),Rt=(0,Q.useDeferredValue)(vt),zt=(0,Q.useMemo)(()=>{if(!Rt.trim())return n;let{text:e,ids:t,invalid:r}=Cp(Rt);if(r)return[];let i=e&&Lt?Lt.search(e).map(e=>e.item):n;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[n,Rt,Lt]),Bt=(0,Q.useMemo)(()=>{if(!ae||ae.length===0||Rt.trim())return[];let e=I?.order===`desc`?-1:1;return[...ae].sort((t,n)=>Number(!!n.isParent)-Number(!!t.isParent)||(t.label||t.name).localeCompare(n.label||n.name,void 0,{numeric:!0,sensitivity:`base`})*e)},[ae,Rt,I?.order]),Vt=Bt.length>0,[Ut,Wt]=(0,Q.useState)(null),Gt=(0,Q.useMemo)(()=>o&&a&&oe?(e,t)=>Wt({x:t.clientX,y:t.clientY,path:e}):void 0,[o,a,oe]),Jt={folders:Bt,onOpen:oe,onMenu:Gt,onPasteDocuments:g,contextPath:i,treeName:a,workspaceId:o},{sorted:Yt,sort:Xt,toggleSort:Qt}=Ig(zt,(0,Q.useMemo)(()=>({title:e=>Yr(e).title?.toLowerCase()??``,schema:e=>Yr(e).schemaLabel??``,type:Hi,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),$t=(0,Q.useCallback)(e=>rb(e,I?.sortBy),[I?.sortBy]),en=(0,Q.useMemo)(()=>fb(zt,$t,I?.order===`asc`?`asc`:`desc`),[zt,$t,I?.order]),tn=W&&!ri(I?.sortBy)&&en.length>1,nn=(0,Q.useCallback)((e,t)=>{me(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),rn=(0,Q.useMemo)(()=>(U===`table`?Yt:tn?en.filter(e=>!ue.has(e.key)).flatMap(e=>e.items):zt).map(e=>e.id),[U,Yt,tn,en,ue,zt]),an=(0,Q.useRef)(null),on=JSON.stringify([o,i,a,T]),cn=(0,Q.useCallback)(e=>{an.current=null,me(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),ln=(0,Q.useCallback)((e,t,n,r=!1)=>{let i=an.current,a=i?.scope===on&&rn.includes(i.id)?i.id:null;(!r||a===null)&&(an.current={scope:on,id:e}),me(i=>{if(r)return Dp(rn,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[on,rn]),un=(0,Q.useCallback)((e,t)=>{let n;pe.has(e)?n=Array.from(pe):(n=[e],me(new Set([e]))),ve({anchor:t,ids:n})},[pe]),fn=(0,Q.useCallback)((e,t)=>{un(t,lm(e))},[un]),pn=(0,Q.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),un(t,Ib(e)))},[un]),mn=(0,Q.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){we(!0);try{for(let n of t)await go(o,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;it(`Created ${n} relation${n===1?``:`s`}`),Rg(),q(null)}catch(e){at(e instanceof Error?e.message:`Failed to create relations`)}finally{we(!1)}}},[o,it,at]),hn=(0,Q.useCallback)(async(e,t,n)=>{if(g){for(let r of e)await g(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});me(new Set)}},[g]),gn=(0,Q.useCallback)(async(e,t,r)=>{if(!o||!Te||Ie.current)return;Ie.current=!0,Ne.current=!1,Me(!1),Oe(!0);let i=ot({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${Te.ids.length} document(s) · ${e.join(`, `)}`});try{let a=n=>Wa(o,n,{to:e,mode:t,keepDocument:r.keepDocument,...t===`delete`&&Le?{deleteFrom:{backend:Le.backend,folder:Le.rel}}:{},folder:r.folder,filename:r.filename,onConflict:r.onConflict}),s=t===`delete`?await Rf(Te.ids,a,{shouldStop:()=>Ne.current,onProgress:(t,n)=>{Ae({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(Te.ids),pending:[]},c=s.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,l=s.successful.filter(e=>e.transfers?.some(e=>e.state===`pending`)).length,u=s.successful.length-c-l,d=s.failed.length,f=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,p=e.join(`, `),m=[c?`${c} already there`:null,l?`${l} queued for backend sync`:null,d?`${d} skipped`:null,s.pending.length?`${s.pending.length} not processed`:null].filter(Boolean).join(` · `),h=`${f} ${p}: ${u} document${u===1?``:`s`}${m?` · ${m}`:``}`;d>0?(i.fail({title:`Operation incomplete`,description:`${h}. ${wp(s.failed,new Map(n.map(e=>[e.id,Yr(e).title])))}`,variant:`destructive`}),console.warn(`Backend transfer skipped documents:`,s.failed)):i.done({title:s.pending.length?`Operation stopped`:l?`Transfer queued`:`Operation complete`,description:h}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`));let g=[...s.failed.map(e=>e.id),...s.pending];Ee(g.length?{ids:g,mode:t}:null),me(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{Ie.current=!1,Oe(!1),Ae(null)}},[o,Te,Le,n,ot]),yn=(0,Q.useCallback)(()=>{pe.size===zt.length?me(new Set):me(new Set(zt.map(e=>e.id)))},[pe.size,zt]),bn=(0,Q.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{let t=window.document.createElement(`textarea`);t.value=e,window.document.body.appendChild(t),t.select(),window.document.execCommand(`copy`),window.document.body.removeChild(t)}},[]),xn=e=>{if(e.length===0)return[];let t=e.length,r=t>1?` (${t})`:``,i=t===1?n.find(t=>t.id===e[0]):void 0,o=()=>me(new Set),s=e.some(e=>(n.find(t=>t.id===e)?.locations?.length??0)>0),c=[],d=e=>{e&&c.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;d({id:`view`,group:`open`,label:`View details`,icon:Xn,run:()=>et({document:i})}),d(sy(i)&&qe&&{id:`edit`,group:`open`,label:`Edit`,icon:_e,run:()=>et({document:i,edit:!0})}),d(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:Ht,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),d(ct&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:Ze,run:()=>ct(i)})}return d(m&&{id:`copy`,group:`clipboard`,label:`Copy${r}`,icon:A,shortcut:`Mod+C`,run:()=>m(e)}),d(h&&{id:`cut`,group:`clipboard`,label:`Cut${r}`,icon:Et,shortcut:`Mod+X`,run:()=>h(e)}),d(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:_n,run:()=>bn(String(i.id))}),d(i&&qe&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:Dn,run:()=>Xe(i)}),d(tt&&{id:`link-to`,group:`organize`,label:`Link to…${r}`,icon:Zt,run:()=>q(e)}),d(be&&{id:`add-related`,group:`organize`,label:`Add related document…${r}`,icon:sn,run:t=>xe(e,t?.shiftKey)}),d(qe&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${r}`,icon:_e,run:()=>Ke(e)}),d(qe&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:A,run:t=>{We(!!t?.shiftKey),He(e)}}),d({id:`export`,group:`organize`,label:`Export…${r}`,icon:qt,run:()=>pt(!0)}),d(a!==`backends`&&(ut||dt)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${r}`,icon:re,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&ut?ut(e[0]):dt?.(e),o()}}),d(a!==`backends`&&(l||f)&&{id:`delete`,group:`remove`,label:`Delete from index${r}`,icon:nt,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&l?l(e[0]):f?.(e),o()}}),s&&rt?(d({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${r}`,icon:Pe,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Ee({ids:e,mode:`copy`})}),d({id:`backend-move`,group:`backends`,label:`Move to backend…${r}`,icon:dn,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Ee({ids:e,mode:`move`})}),d({id:`backend-delete`,group:`backends`,label:`Delete from backend…${r}`,icon:nt,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Ee({ids:e,mode:`delete`})})):s&&(u||p)&&d({id:`destroy`,group:`backends`,label:`Delete from backend(s)${r}`,icon:nt,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&u?u(e[0]):p?.(e),o()}}),c},Sn=()=>{let e=[],t=t=>{t&&e.push(t)},r=b??[];return t(g&&r.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${r.length})`,icon:Ce,shortcut:`Mod+V`,run:async()=>{try{await g(i,r)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(zt.length>0&&{id:`select-all`,group:`select`,label:vt?`Select all matches (${zt.length})`:`Select all on this page`,icon:St,shortcut:`Mod+A`,run:()=>me(new Set(zt.map(e=>e.id)))}),t(pe.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:zn,run:()=>me(new Set)}),t(g&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:En,hint:`Browse and add existing documents to this folder`,run:()=>ze(!0)}),t(v&&{id:`import`,group:`add`,label:`Import…`,icon:Qe,run:()=>ht(!0)}),t(n.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:qt,run:()=>{me(new Set),pt(!0)}}),t(j&&s>0&&{id:`purge`,group:`purge`,label:`Purge all (${s})`,icon:nt,destructive:!0,disabled:M||!!vt,hint:vt?`Purge is disabled while local search is active`:M?`Purge requires loaded server results with no browser-only or live selection`:`Delete all documents matching the current server-side filters across all pages`,run:j}),e},Cn=!!(L&&I&&o),wn=he?he.ids?xn(he.ids):Sn():[],Tn=he?.ids?.length===1?n.find(e=>e.id===he.ids[0]):void 0,On=Tn?(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,$.jsx)(Gm,{document:Tn,chip:!0}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Yr(Tn).title}),(0,$.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Tn.id,` · `,Tn.schema]})]})]}):(0,$.jsx)(`div`,{className:`truncate text-base font-semibold`,children:he?.ids?`${he.ids.length} documents`:`This folder`}),kn=e=>{ve({anchor:lm(e.currentTarget),ids:pe.size>0?Array.from(pe):null})},An=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),me(new Set),ve({anchor:Ib(e),ids:null}))},jn=e=>{if(e.defaultPrevented||am(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(sm(e)){e.preventDefault(),t?un(Number(t.dataset.documentId),lm(t,`inside`)):ve({anchor:lm(e.target,`inside`),ids:pe.size>0?Array.from(pe):null});return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=Array.from(e.currentTarget.querySelectorAll(`[data-document-id]`));if(n.length===0)return;let r=t?n.indexOf(t):-1,i=n[e.key===`ArrowDown`?Math.min(r+1,n.length-1):Math.max(r-1,0)];e.preventDefault(),i.focus({preventScroll:!0}),i.scrollIntoView({block:`nearest`}),e.shiftKey&&ln(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&pe.size>0){e.preventDefault(),me(new Set);return}om(e,[...xn(Array.from(pe)),...Sn()])},Mn=(0,Q.useCallback)(async e=>{if(!v)return!1;try{return await v(e,i)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[v,i]),Nn=e=>tn?en.map(t=>{let n=ue.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!pe.has(t),0);return(0,$.jsxs)(`section`,{className:`group mb-4`,children:[(0,$.jsx)(nx,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>fe(t.key),onSelectAll:e=>nn(r,e)}),!n&&e(t.items)]},t.key)}):e(zt);return r?(0,$.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})}):(0,$.jsxs)(`div`,{tabIndex:-1,onKeyDown:jn,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${bt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:Pt,onDragLeave:Ft,onDrop:Nt,children:[(0,$.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,$.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,$.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:vt?`${zt.length} of ${n.length}`:`${s.toLocaleString()} document${s===1?``:`s`}`})]}),(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,$.jsxs)(`p`,{hidden:yt,className:`min-w-0 truncate`,children:[`Context: `,(0,$.jsx)(`span`,{className:`font-mono`,children:i}),C&&w&&C!==w&&(0,$.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,$.jsxs)(`p`,{className:`shrink-0`,children:[pe.size>0&&(0,$.jsxs)(`span`,{className:`text-info`,children:[pe.size,` selected`]}),pe.size>0&&(vt||s>D)&&(0,$.jsx)(`span`,{className:`mx-1`,children:`·`}),vt?`on this page`:s>D?`Showing ${Math.min((T-1)*D+1,s)}–${Math.min(T*D,s)}`:null]})]})]}),!yt&&(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[!yt&&z&&(0,$.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>z(`path`),className:`px-2.5 py-2 transition-colors ${R===`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,$.jsxs)(`button`,{type:`button`,onClick:()=>z(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${R===`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,$.jsx)(Ye,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!yt&&(0,$.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,$.jsx)(tr,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,$.jsx)(`input`,{ref:wt,type:`text`,placeholder:P?Ct?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,title:`Search text or an exact document ID, e.g. @id:101140. Press Enter to search the server.`,defaultValue:``,onChange:e=>_t(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`&&P&&(e.preventDefault(),At())},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`}),(vt||Ct)&&(0,$.jsx)(`button`,{onClick:jt,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,$.jsx)(G,{className:`h-4 w-4`})})]}),!yt&&P&&vt.trim()&&!N.includes(vt.trim())&&(0,$.jsxs)(Z,{size:`sm`,variant:`default`,onClick:At,className:`shrink-0`,title:Ct?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,$.jsx)(tr,{className:`h-3.5 w-3.5 mr-1`}),Ct?`Refine`:`Search server`]})]}),!yt&&Ct&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),N.map((e,t)=>(0,$.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,$.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,$.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,$.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),F&&(0,$.jsx)(`button`,{onClick:()=>F(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),F&&N.length>1&&(0,$.jsx)(`button`,{onClick:()=>F(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,$.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,$.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,$.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[S&&(0,$.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,_,`Table view`],[`tile`,$n,`Tile view`],[`card`,Kt,`Card view`]].map(([e,t,n])=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>se(e),title:n,"aria-pressed":U===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${U===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,$.jsx)(t,{className:`h-4 w-4`})},e))}),S&&U!==`table`&&!ri(I?.sortBy)&&(0,$.jsx)(`button`,{type:`button`,onClick:le,title:W?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":W,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${W?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,$.jsx)(B,{className:`h-4 w-4`})})]}),O&&s>0&&(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,$.jsxs)(`select`,{value:D,onChange:e=>k?.(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`,"aria-label":`Documents per page`,children:[(0,$.jsx)(`option`,{value:25,children:`25`}),(0,$.jsx)(`option`,{value:50,children:`50`}),(0,$.jsx)(`option`,{value:100,children:`100`}),(0,$.jsx)(`option`,{value:200,children:`200`})]}),(0,$.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,$.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[Cn&&(0,$.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,$.jsx)(nb,{workspaceId:o,value:I,onChange:L})]}),(0,$.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(n.length>0||v||g)&&(0,$.jsxs)(`div`,{className:`contents`,children:[(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:kn,"aria-haspopup":`menu`,"aria-label":pe.size>0?`Actions (${pe.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${rm(`Shift+F10`)} or right-click)`,children:[(0,$.jsx)(vn,{className:`h-4 w-4`}),(0,$.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,pe.size>0?` (${pe.size} selected)`:``]})]}),pe.size>0&&(0,$.jsxs)(Z,{variant:`ghost`,size:`sm`,onClick:()=>me(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,$.jsx)(G,{className:`h-3.5 w-3.5`}),(0,$.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),b&&b.length>0&&g&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>g(i,b),className:`flex items-center gap-1.5`,title:`Paste into this folder (${rm(`Mod+V`)})`,children:[(0,$.jsx)(Ce,{className:`h-4 w-4`}),`Paste (`,b.length,`)`]})]}),ee&&ne&&(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:ne,disabled:te,className:`w-control-sm shrink-0 px-0 touch-target`,"aria-label":te?`Saving filters`:`Save current query and filters`,title:`Save current query and filters`,children:(0,$.jsx)(Be,{className:`h-3.5 w-3.5`})}),t]})]})]})}),O&&s>D&&(0,$.jsxs)(`div`,{className:`document-pagination mt-3 flex min-w-0 flex-wrap items-center justify-end gap-2 border-t pt-3 max-sm:gap-0.5`,children:[(0,$.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((T-1)*D+1,s),` - `,Math.min(T*D,s),` of `,s]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>O(1),disabled:T===1,className:`p-1 touch-target`,children:(0,$.jsx)(Fe,{className:`h-4 w-4`})}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>O(T-1),disabled:T===1,className:`p-1 touch-target`,children:(0,$.jsx)(E,{className:`h-4 w-4`})}),(0,$.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,$.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),T,(0,$.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,$.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(s/D)]}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>O(T+1),disabled:T>=Math.ceil(s/D),className:`p-1 touch-target`,children:(0,$.jsx)(hr,{className:`h-4 w-4`})}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>O(Math.ceil(s/D)),disabled:T>=Math.ceil(s/D),className:`p-1 touch-target`,children:(0,$.jsx)(ge,{className:`h-4 w-4`})})]})]})]}),(0,$.jsx)($h,{scope:JSON.stringify([on,U,rn]),selected:pe,onSelectionChange:cn,onContextMenu:An,children:zt.length===0&&!Vt?(0,$.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(Rn,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:vt?`No documents match your search`:`No documents found in this context`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:vt?(0,$.jsxs)($.Fragment,{children:[`Search: `,(0,$.jsxs)(`span`,{className:`font-mono`,children:[`"`,vt,`"`]})]}):(0,$.jsxs)($.Fragment,{children:[`Path: `,(0,$.jsx)(`span`,{className:`font-mono`,children:i})]})}),!yt&&vt&&(0,$.jsx)(`button`,{onClick:Tt,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!vt&&b&&b.length>0&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,rm(`Mod+V`),` to paste `,b.length,` document(s)`]})]})}):U===`tile`?(0,$.jsxs)(`div`,{children:[(0,$.jsx)($b,{...Jt}),zt.length===0&&(0,$.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Nn(e=>(0,$.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,$.jsx)(Kb,{document:e,isSelected:pe.has(e.id),workspaceId:o,onSelect:ln,onOpenToSide:ct,onRightClick:pn,onOpenActions:fn,onDragStart:Mt},e.id))}))]}):U===`table`?(0,$.jsx)(`div`,{children:(0,$.jsxs)(Dg,{children:[(0,$.jsx)(Og,{children:(0,$.jsxs)(jg,{children:[(0,$.jsx)(Mg,{className:`w-10`,children:(0,$.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:zt.length>0&&pe.size===zt.length,ref:e=>{e&&(e.indeterminate=pe.size>0&&pe.size<zt.length)},onChange:yn,title:`Select all on this page`})}),(0,$.jsx)(Fg,{label:(0,$.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:Xt,onSort:Qt,className:`w-12`}),(0,$.jsx)(Fg,{label:`Title`,sortKey:`title`,sort:Xt,onSort:Qt,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,$.jsx)(Fg,{label:`Schema`,sortKey:`schema`,sort:Xt,onSort:Qt,className:`hidden md:table-cell`}),(0,$.jsx)(Fg,{label:`ID`,sortKey:`id`,sort:Xt,onSort:Qt,className:`hidden lg:table-cell`}),(0,$.jsx)(Mg,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,$.jsx)(Fg,{label:`Created`,sortKey:`created`,sort:Xt,onSort:Qt,className:`hidden sm:table-cell`}),(0,$.jsx)(Mg,{className:`w-12 md:w-auto`,children:(0,$.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,$.jsxs)(kg,{children:[Bt.map(e=>(0,$.jsx)(tx,{folder:e,onOpen:oe,onMenu:Gt,onPasteDocuments:g,contextPath:i,treeName:a,workspaceId:o},e.path)),Yt.map(e=>(0,$.jsx)(zb,{document:e,isSelected:pe.has(e.id),workspaceId:o,onSelect:ln,onOpenToSide:ct,onRightClick:pn,onOpenActions:fn,onDragStart:Mt},e.id))]})]})}):(0,$.jsxs)(`div`,{children:[(0,$.jsx)(ex,{...Jt}),zt.length===0&&(0,$.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Nn(e=>(0,$.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,$.jsx)(`div`,{children:(0,$.jsx)(Bb,{document:e,isSelected:pe.has(e.id),workspaceId:o,onSelect:ln,onOpenToSide:ct,onRightClick:pn,onOpenActions:fn,onDragStart:Mt})},e.id))}))]})}),he&&(0,$.jsx)(mm,{anchor:he.anchor,items:wn,onClose:()=>ve(null),label:he.ids?`Document actions`:`Folder actions`,header:On}),(0,$.jsx)(Nb,{isOpen:ft,onClose:()=>pt(!1),documents:n,selectedDocuments:pe}),(0,$.jsx)(Pb,{isOpen:mt,onClose:()=>ht(!1),onImport:Mn}),Ve&&o&&(0,$.jsx)(tg,{modal:Ue,workspaceId:o,ids:Ve,onClose:()=>He(null)}),K&&ie&&(0,$.jsx)(Lp,{label:`Link to`,onClose:()=>q(null),children:(0,$.jsx)(ih,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:K.length,fixedWorkspaceName:o,tabs:[`context`,`directory`,`relations`],saving:Se,relationExcludeIds:new Set(K),onConfirm:(e,t)=>hn(e,K,t),onConfirmRelation:e=>mn(e,K),onClose:()=>q(null)})}),Te&&o&&(0,Ip.createPortal)((0,$.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,$.jsx)(Sg,{workspaceId:o,documentCount:Te.ids.length,initialMode:Te.mode,defaultFilename:Te.ids.length===1?wi(n.find(e=>e.id===Te.ids[0])??{}):``,saving:De,progress:ke,stopping:je,onStop:()=>{Ne.current=!0,Me(!0)},deleteFrom:Le?{backend:Le.backend,folder:Le.rel}:void 0,onConfirm:gn,onClose:()=>{De||Ee(null)}})}),window.document.body),Re&&g&&(0,Ip.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>ze(!1),"aria-hidden":!0}),(0,$.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,$.jsx)(Cg,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:o,onConfirm:async e=>{await g(i,e),ze(!1)},onClose:()=>ze(!1)})})]}),window.document.body),Je&&o&&(0,$.jsx)(qh,{workspaceId:o,document:Je,onClose:()=>Xe(null)},`${o}:${Je.id}`),Ge&&o&&(0,$.jsx)(hg,{workspaceId:o,documentIds:Ge,onClose:()=>Ke(null)}),(0,$.jsx)(Hy,{document:$e?.document??null,isOpen:!!$e,onClose:()=>et(null),workspaceId:o,initialEdit:$e?.edit}),Ut&&o&&a&&oe&&(0,$.jsx)(Mb,{x:Ut.x,y:Ut.y,workspaceName:o,treeName:a,path:Ut.path,onClose:()=>Wt(null),onOpen:oe,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:a,path:e}})),pastedDocumentIds:b,onPasteDocuments:g?(e,t)=>g(e,t):void 0})]})}function ix(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,Q.useState)(e.canvasQueries??[]),a=(0,Q.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,Q.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,Q.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,Q.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,Q.useCallback)(()=>o([]),[o])}}function ax({config:e,canvas:t}){let n=typeof e.pageSize==`number`?e.pageSize:50,r=e.viewMode===`card`||e.viewMode===`tile`||e.viewMode===`table`?e.viewMode:`table`,[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(1),[u,d]=(0,Q.useState)(!0),f=t.canvasSort??Qy,{queries:p,runSearch:m,removeQuery:h}=ix(t,()=>l(1));(0,Q.useEffect)(()=>{let e=!1;return(async()=>{d(!0);try{let r=await t.fetchDocuments({limit:n,page:c,sortBy:f.sortBy,order:f.order,queries:p.length?p:void 0});if(e)return;a(r.payload||[]),s(r.totalCount||r.count||0)}catch{e||(a([]),s(0))}finally{e||d(!1)}})(),()=>{e=!0}},[t,n,c,f.sortBy,f.order,p]);let g=(0,Q.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,$.jsx)(nb,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,$.jsx)(rx,{documents:i,isLoading:u,contextPath:t.path,treeName:t.treeName,workspaceId:t.workspaceId,totalCount:o,serverSort:f,viewMode:r,allowViewToggle:!0,currentPage:c,pageSize:n,onPageChange:l,backendSearchQueries:p,onBackendSearch:_?void 0:m,onRemoveBackendQuery:_?void 0:h})})]})}Ff({type:`documents-table`,name:`Documents`,icon:_,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:ax});function ox({config:e,setConfig:t,canvas:n}){let[r,i]=(0,Q.useState)(()=>new Date),a=e.format!==`24`;return(0,Q.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,$.jsx)(`div`,{className:`text-3xl font-semibold tabular-nums`,children:r.toLocaleTimeString(void 0,{hour12:a,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>t({...e,format:a?`24`:`12`}),className:`mt-1 px-2 py-0.5 text-[10px] border rounded-md text-muted-foreground hover:bg-accent`,children:a?`12h`:`24h`})]})}Ff({type:`clock`,name:`Clock`,icon:N,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:ox});var sx=450,cx=10;function lx(e,t){let{open:n}=py(),r=(0,Q.useRef)(null),i=(0,Q.useRef)(null),a=(0,Q.useRef)(!1),o=()=>{e&&n(e,t)},s=()=>{r.current&&=(clearTimeout(r.current),null)};return{activationProps:{role:`button`,tabIndex:0,onClick:()=>{if(a.current){a.current=!1;return}o()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},onContextMenu:e=>{e.preventDefault(),o()},onPointerDown:e=>{e.pointerType===`touch`&&(i.current={x:e.clientX,y:e.clientY},a.current=!1,s(),r.current=setTimeout(()=>{a.current=!0,o()},sx))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>cx&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function ux({doc:e,workspaceId:t}){let n=Yr(e),{activationProps:r}=lx(e,t);return(0,$.jsxs)(`li`,{...r,title:`Open details`,className:`canvas-no-drag cursor-pointer py-1.5 min-w-0 rounded px-1 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,$.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,$.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function dx({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=!1;return(async()=>{o(!0);try{let r=await t.fetchDocuments({limit:n});if(e)return;i(r.payload||[]),c(null)}catch(t){if(e)return;c(t instanceof Error?t.message:`Failed to load documents`),i([])}finally{e||o(!1)}})(),()=>{e=!0}},[t,n]),a?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,$.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,$.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,$.jsx)(ux,{doc:e,workspaceId:t.workspaceId},e.id))})}Ff({type:`recent-documents`,name:`Recent documents`,icon:xt,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:dx});function fx({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,$.jsx)(`textarea`,{value:r,readOnly:n.readOnly,onChange:n=>t({...e,text:n.target.value}),placeholder:n.readOnly?``:`Jot something down…`,className:`canvas-no-drag w-full h-full resize-none bg-transparent text-sm leading-6 outline-none`})}Ff({type:`note`,name:`Note`,icon:Kn,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:fx});var px=`data/schema/file`,mx=`data/schema/drawing`;function hx(e){return(e.schema===px||e.schema===mx)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function gx(e){return e.schema===px&&String(e.metadata?.contentType||``).startsWith(`video/`)}var _x=`data/mime/image`;function vx(e,t,n=!1){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(0),[s,c]=(0,Q.useState)(1),[l,u]=(0,Q.useState)(!0),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=ix(e,()=>c(1)),y=e.canvasSort??Qy;(0,Q.useEffect)(()=>{let r=!1,a=async()=>{u(!0),f(null);try{let a=await e.fetchDocuments({limit:t,page:s,queries:h.length?h:void 0,sortBy:y.sortBy,order:y.order,...n?{anyOf:[_x,`data/mime/video`]}:{allOf:[_x]}});if(r)return;i((a.payload||[]).filter(e=>hx(e)||n&&gx(e))),o(a.totalCount||a.count||0)}catch(e){if(r)return;i([]),o(0),f(e instanceof Error?e.message:`Failed to load images`)}finally{r||u(!1)}};return a(),window.addEventListener(`workspace:documents:refresh`,a),()=>{r=!0,window.removeEventListener(`workspace:documents:refresh`,a)}},[e,t,s,h,y.sortBy,y.order,n]);let b=(0,Q.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,Q.useCallback)(()=>{m(``),v()},[v]),S=(0,Q.useCallback)(e=>{_(e)},[_]),C=(0,Q.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,Q.useMemo)(()=>Math.max(1,Math.ceil(a/t)),[a,t]),input:p,setInput:m,submit:b,clearSearch:x,removeQuery:S,activeQueries:h,sort:y,setSort:C}}function yx({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=__(e,t.id,512,{blobFallback:!gx(t),version:t.checksumArray?.[0]??null}),c=wi(t)||`image-${t.id}`,l=Ra(t),u=l!==``&&i!==`off`;return(0,$.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-(--card-radius) border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,$.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!gx(t)&&(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,$.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-normal group-hover:scale-105`}),gx(t)&&(0,$.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,$.jsx)(xe,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,$.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,$.jsx)(`span`,{className:`pointer-events-none absolute inset-x-0 bottom-0 px-1.5 pb-1 pt-4 text-left text-[11px] leading-snug text-white bg-gradient-to-t from-black/75 via-black/45 to-transparent ${i===`reveal`?`caption-reveal`:``}`,children:(0,$.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,$.jsx)(`span`,{className:`pointer-events-none absolute right-1 top-1 rounded-full bg-black/55 p-1 text-white transition-opacity ${i===`reveal`?`hidden [@media(hover:hover)]:block [@media(hover:hover)]:group-hover:opacity-0`:``}`,title:`Has a comment`,children:(0,$.jsx)(Me,{className:`h-3 w-3`})})]})}function bx({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Fo(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!gx(a)}),l=wi(a)||`image-${a.id}`,u=Ra(a),[d,f]=(0,Q.useState)(!1);return Fp(r),(0,Q.useEffect)(()=>{let e=e=>{e.target?.closest(`video`)||(e.key===`ArrowLeft`&&n>0&&i(n-1),e.key===`ArrowRight`&&n<t.length-1&&i(n+1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,t.length,i]),(0,Ip.createPortal)((0,$.jsxs)(`div`,{"data-scheme":`dark`,className:`fixed inset-0 z-fullscreen flex flex-col bg-scrim p-0 sm:p-4`,onClick:r,children:[(0,$.jsx)(`button`,{type:`button`,onClick:r,className:`canvas-no-drag absolute right-2 top-2 z-10 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20 touch-target sm:right-4 sm:top-4`,title:`Close`,children:(0,$.jsx)(G,{className:`h-5 w-5`})}),n>0&&!d&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n-1)},className:`canvas-no-drag absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Previous`,children:(0,$.jsx)(E,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n+1)},className:`canvas-no-drag absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Next`,children:(0,$.jsx)(hr,{className:`h-6 w-6 touch-target`})}),(0,$.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,$.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,$.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),gx(a)&&(0,$.jsx)(Sx,{workspaceId:e,doc:a},a.id),o&&(0,$.jsx)(a_,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,$.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,$.jsx)(`span`,{className:`mx-auto mb-1 block max-w-2xl whitespace-pre-wrap text-sm text-foreground`,children:u}),l,` · `,n+1,`/`,t.length,!d&&!gx(a)&&(0,$.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function xx({workspaceId:e,state:t,comments:n,onToggleComments:r}){let{input:i,setInput:a,submit:o,clearSearch:s,removeQuery:c,activeQueries:l,sort:u,setSort:d,page:f,setPage:p,totalPages:m,totalCount:h,isLoading:g}=t,_=l.length>0;return(0,$.jsxs)(`div`,{className:`canvas-no-drag flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b px-1 pb-1.5`,children:[(0,$.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()},placeholder:_?`Refine: add another query (Enter)…`:`Search media (Enter)…`,className:`h-7 w-full rounded-md border bg-background pl-7 pr-7 text-xs`}),_&&(0,$.jsx)(`button`,{type:`button`,onClick:s,title:`Clear search`,className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),_&&(0,$.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,$.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,$.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(t),title:`Remove "${e}"`,className:`rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,$.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-pressed":n!==`off`,title:n===`off`?`Show comments on tiles`:`Hide comments on tiles`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border touch-target ${n===`off`?`text-muted-foreground hover:bg-accent`:`border-primary/30 bg-primary/15 text-primary hover:bg-primary/25`}`,children:(0,$.jsx)(Me,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(nb,{workspaceId:e,value:u,onChange:d}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,$.jsx)(Md,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,$.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(Math.max(1,f-1)),disabled:f<=1,title:`Previous page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,$.jsx)(E,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(Math.min(m,f+1)),disabled:f>=m,title:`Next page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,$.jsx)(hr,{className:`h-3.5 w-3.5`})})]})]})]})}function Sx({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=Uo(e,t.id);return(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`span`,{children:`Loading video…`}),i&&(0,$.jsx)(`span`,{role:`alert`,children:i}),n&&(0,$.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function Cx({config:e,setConfig:t,canvas:n}){let r=vx(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=jo()==null&&(n.interactive??!n.readOnly),[a,o]=(0,Q.useState)(new Set),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),p=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[m,h]=(0,Q.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,$.jsx)(xx,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,$.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,$.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:_?`Loading media…`:y.length?`No images or videos match your search.`:`No images or videos in this canvas' context.`}):(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(min(120px,100%),1fr))] gap-2 sm:grid-cols-[repeat(auto-fill,minmax(min(200px,100%),1fr))] sm:gap-3`,children:g.map((e,t)=>(0,$.jsxs)(`div`,{className:`relative`,onContextMenu:t=>{i&&(t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,ids:a.has(e.id)?[...a]:[e.id]}))},children:[(0,$.jsx)(yx,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select document ${e.id}`,checked:a.has(e.id),onChange:()=>p(e.id),className:`canvas-no-drag absolute left-2 top-2 h-4 w-4 accent-primary`})]},e.id))})}),d&&(0,$.jsx)(mm,{anchor:d,onClose:()=>f(null),label:`${d.ids.length} image${d.ids.length===1?``:`s`}`,items:[{id:`bulk-edit`,label:`Bulk edit… (${d.ids.length})`,icon:_e,run:()=>u(d.ids)}]}),l&&(0,$.jsx)(hg,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,$.jsx)(bx,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}Ff({type:`gallery`,name:`Gallery`,icon:Se,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Cx});var wx=150;function Tx(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function Ex(e){let t=e.metadata??{},n=e.data??{};return{w:Tx(t.width)||Tx(t.imageWidth)||Tx(n.width)||Tx(n.imageWidth),h:Tx(t.height)||Tx(t.imageHeight)||Tx(n.height)||Tx(n.imageHeight)}}function Dx(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=Ex(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 Ox({config:e,setConfig:t,canvas:n}){let r=vx(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,Q.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,$.jsx)(xx,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,$.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,$.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:s?`Loading images…`:l.length?`No images match your search.`:`No images in this canvas' context.`}):(0,$.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${wx}px, 1fr))`,gridAutoRows:`${wx}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=Dx(e,t);return(0,$.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,$.jsx)(yx,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,$.jsx)(bx,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}Ff({type:`mosaic`,name:`Mosaic`,icon:gt,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Ox});var kx=`data/schema/task`;function Ax({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=Y_(e),[a,o]=(0,Q.useState)(!1),{replicating:s,label:c}=bo(e),l=i.status===`completed`,u=i.status??`pending`,d=Z_(i),{activationProps:f,stopRowActivation:p}=lx(e,t),m=async()=>{if(!(n||a)){o(!0);try{await $_(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,$.jsxs)(`div`,{...f,title:`Open details`,className:`canvas-no-drag flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-2.5 py-2 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${s?`opacity-60`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{p(e),m()},disabled:n||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`canvas-no-drag mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${n?`cursor-default opacity-70`:``}`,children:a?(0,$.jsx)(Yn,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,$.jsx)(oe,{className:`h-3 w-3`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,$.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,$.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${X_[u]}`,children:V_[u]}),i.dueDate&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,$.jsx)(pe,{className:`h-3 w-3`}),Q_(i.dueDate)]}),typeof i.priority==`number`&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,$.jsx)(Lt,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,$.jsx)(Yn,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function jx({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!0),[c,l]=(0,Q.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,Q.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,Q.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[kx],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===Ji))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,Q.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,Q.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>Y_(e).status!==`completed`):i,v=i.filter(e=>{let t=Y_(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,$.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,$.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,$.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,$.jsx)(Ax,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}Ff({type:`todos`,name:`Todos`,icon:Vt,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:jx});function Mx(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var Nx=`context`;function Px(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:Nx,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:Nx,path:e?`/${e}`:`/`}}return{treeName:Nx,path:`/`}}function Fx(e,t,n){let r=n&&n!==Nx?`/trees/${encodeURIComponent(n)}`:``,i=Mx(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function Ix({canvas:e}){return jo()!=null||!Sd()?(0,$.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,$.jsx)(Lx,{workspaceId:e.workspaceId},e.workspaceId)}function Lx({workspaceId:e}){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(`Workspace`),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([qr(e),Ai(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),c(null)}catch{if(t||a!==r)return;n([]),c(`Workspace pins are unavailable. Check your workspace access or try again.`)}finally{!t&&a===r&&o(!1)}},s=()=>{document.visibilityState===`visible`&&a()};a(),window.addEventListener(`focus`,s),document.addEventListener(`visibilitychange`,s);let l=hd.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),l?.(),window.clearInterval(u)}},[e,l]),(0,$.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,$.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>u(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,$.jsx)(P,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,$.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,$.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=Nm(t.color),i=(0,$.jsxs)($.Fragment,{children:[n?(0,$.jsx)(W,{className:`h-5 w-5 shrink-0 text-warning`}):(0,$.jsx)(f,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,$.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,$.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,$.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-(--card-radius) border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,$.jsx)(`li`,{children:n?(0,$.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,$.jsx)(Nu,{to:Fx(e,t.path,t.tree),title:`Open ${t.tree}:${t.path}`,className:`${a} transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,style:o,children:i})},t.id)})}):(0,$.jsx)(`p`,{className:`p-2 text-sm text-muted-foreground`,children:a?`Loading pins…`:`No workspace pins yet. Pin a folder from the workspace tree menu.`})})]})}Ff({type:`workspace-pins`,name:`Workspace pins`,icon:Oe,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:Ix});function Rx({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,Q.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,$.jsxs)(`div`,{className:c?u?`absolute inset-0 z-40 flex flex-col bg-background`:`fixed inset-0 z-50 flex flex-col bg-background`:`flex flex-col h-full rounded-(--card-radius) border bg-background overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`canvas-drag-handle flex items-center gap-2 px-2 py-1 border-b bg-muted/30 select-none ${o?``:`cursor-move`}`,children:[t&&(0,$.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,$.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(zx,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:Mn}),(0,$.jsx)(zx,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:de})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-accent touch-target`,title:c?`Restore`:`Full screen`,children:c?(0,$.jsx)(lt,{className:`w-3.5 h-3.5`}):(0,$.jsx)(xn,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 touch-target`,title:`Remove widget`,children:(0,$.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,Ip.createPortal)(d,u??document.body):d}function zx({on:e,onClick:t,label:n,icon:r}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-pressed":e,title:e?`${n} (on)`:n,className:`canvas-no-drag shrink-0 p-0.5 rounded touch-target ${e?`bg-primary/15 text-primary hover:bg-primary/25`:`text-muted-foreground hover:text-foreground hover:bg-accent`}`,children:(0,$.jsx)(r,{className:`w-3.5 h-3.5`})})}var Bx=(0,Nf.WidthProvider)(Nf.default),Vx=12,Hx=80,Ux=40,Wx=[12,12],Gx=[8,8],Kx={w:!1,h:!1};function qx(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function Jx(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function Yx(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 Xx(e,t,n=0){let r=n>0?n:qx(e);return e.map(e=>{let n=t[e.i]??Kx;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?Vx:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var Zx=4;function Qx(e,t,n=Wx[1]){return Math.max(1,Math.ceil((e-n-Zx)/(t+n)))}var $x=45,eS=640;function tS(e,t,n=0,r){let i=[...Xx(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:Vx,y:a,h:n};return a+=n,i})}var nS=e=>e&&e.trim()?[e]:[];function rS(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(Yx):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=Vx,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function iS({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,metadata:a,isLocked:o=!1,readOnly:s=!1,interactive:c=!0,fetchDocuments:l,onSaved:u}){let d=!s,f=(0,Q.useMemo)(()=>rS(a),[a]),[p,m]=(0,Q.useState)(f.layout),[h,g]=(0,Q.useState)(f.widgets),[_,v]=(0,Q.useState)(f.fills),y=(0,Q.useRef)(f.fills),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(0),M=(0,Q.useRef)(0),N=(0,Q.useCallback)(e=>{y.current=e,v(e)},[]),[P,F]=(0,Q.useState)(()=>Gy(i?.sort)),I=(0,Q.useRef)(!1),[L,R]=(0,Q.useState)(()=>nS(i?.query)),z=(0,Q.useRef)(!1),ee=(0,Q.useRef)(null),te=(0,Q.useRef)(f),ne=(0,Q.useCallback)(e=>{let t=If(h[e]?.type??``)?.mobileHeight;if(!(!t||A<=0))return Math.max(1,Math.round(A*t))},[h,A]),B=(0,Q.useMemo)(()=>O?tS(p,_,A,ne):Xx(p,_,A),[p,_,O,A,ne]),re=O?Ux:Hx,ie=(0,Q.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,Q.useEffect)(()=>{let e=rS(a);m(e.layout),g(e.widgets),N(e.fills),te.current=e,F(Gy(i?.sort)),I.current=!1,R(nS(i?.query)),z.current=!1,C(!1)},[n,r]),(0,Q.useEffect)(()=>{if(!s)return;let e=rS(a);m(e.layout),g(e.widgets),N(e.fills),te.current=e},[s,ie,a,N]),(0,Q.useEffect)(()=>{let e=ee.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<eS;k(n),M.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?Gx:Wx;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&j(Qx(t,n?Ux:Hx,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let ae=(0,Q.useCallback)(e=>{F(e),I.current=!0,C(!0)},[]),oe=(0,Q.useCallback)(e=>{R(e),z.current=!0,C(!0)},[]),V=(0,Q.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:P,setCanvasSort:d?ae:void 0,canvasQueries:L,setCanvasQueries:d?oe:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await to(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 to(e,n,t,{...r,anyOf:void 0,ids:i});return{payload:a.payload||[],count:a.count??void 0,totalCount:a.totalCount??void 0}})}),[e,t,n,r,i,d,c,l,P,ae,L,oe]),H=(0,Q.useCallback)((e,t,n)=>{te.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),U=(0,Q.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:te.current.widgets,layout:te.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};te.current={...r,fills:y.current};let o=I.current||z.current?{...i||{},...I.current?{sort:P.sortBy?P:null}:{},...z.current?{query:L.join(` `).trim()||null}:{}}:void 0;await io(e,n,t,{...a||{},ui:r},o),I.current=!1,z.current=!1,C(!1),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t}})),u?.()}catch(e){let t=e instanceof Error?e.message:`Save failed`;D(t),console.error(`Failed to save canvas layout:`,e)}finally{T(!1)}}},[d,w,e,n,t,a,u,i,P,L]),se=(0,Q.useCallback)(e=>{!d||O||m(t=>{let n=e.map(e=>{let n=t.find(t=>t.i===e.i),r=y.current[e.i];return n?{...e,x:r?.w?n.x:e.x,w:r?.w?n.w:e.w,y:r?.h?n.y:e.y,h:r?.h?n.h:e.h}:e});return H(n,h),n})},[d,O,H,h]),W=(0,Q.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??Kx,i=Wx[1]+(n.y+n.h)*(Hx+Wx[1]),a={w:n.x+n.w>=Vx,h:M.current>0&&i>=M.current-$x};if(a.w||=r.w&&n.w===t.w,a.h||=r.h&&n.h===t.h,a.w===r.w&&a.h===r.h)return;let o={...y.current,[n.i]:a};N(o),H(te.current.layout,h,o)},[d,N,H,h]),ce=(0,Q.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??Kx,r={...y.current,[e]:{...n,[t]:!n[t]}};N(r),H(p,h,r)},[d,N,H,p,h]),le=(0,Q.useCallback)(e=>{let t=If(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:Jx(B),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>=Vx,h:!1}};m(l),g(u),N(d),x(!1),H(l,u,d)},[p,B,h,N,H]),ue=(0,Q.useCallback)(e=>{let t=p.filter(t=>t.i!==e),n={...h};delete n[e];let r={...y.current};delete r[e],m(t),g(n),N(r),H(t,n,r)},[p,h,N,H]),de=(0,Q.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return H(p,r),r})},[p,H]),fe=Object.keys(h);return(0,$.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,$.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>x(e=>!e),className:`flex items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:[(0,$.jsx)(sn,{className:`w-3.5 h-3.5`}),`Add`,(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,$.jsx)(`div`,{className:`absolute left-0 top-full mt-1 z-20 w-48 rounded-md border bg-popover shadow-elevation-2 py-1`,children:Lf().map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>le(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,$.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:U,disabled:!S||w,className:J(`flex shrink-0 items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs rounded-md transition-colors disabled:opacity-50`,S?`bg-primary text-primary-foreground hover:bg-primary`:`border hover:bg-accent`),children:[(0,$.jsx)(Be,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,$.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[fe.length,` widget`,fe.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,$.jsx)(`div`,{ref:ee,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:fe.length===0?(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,$.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,$.jsx)(Bx,{className:`layout`,layout:B,cols:Vx,rowHeight:re,margin:O?Gx:Wx,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:se,onResizeStop:W,compactType:`vertical`,children:fe.map(e=>{let t=h[e],n=If(t.type),r=_[e]??Kx,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,$.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,$.jsx)(Rx,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>ue(e),fill:_[e]??Kx,onToggleFill:d?t=>ce(e,t):void 0,children:(0,$.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>de(e,t),canvas:V})}):(0,$.jsx)(Rx,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>ue(e),children:(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var aS=`data/schema/file`;function oS(e){return String(e.locations?.[0]?.url||``).trim()}function sS(e){let t=oS(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function cS(e){return e.schema===aS&&String(e.metadata?.contentType||``).startsWith(`image/`)}function lS(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 uS(e){if(e.schema!==aS)return Yr(e);let t=sS(e),n=String(e.metadata?.contentType||``).trim(),r=lS(e.metadata?.size);return{...Yr(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:oS(e),schemaLabel:`file`}}function dS(e){return/^https?:\/\/[^\s]+$/i.test(e)}function fS(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return dS(t)?t:null}return t.isExternal&&dS(t.subtitle)?t.subtitle:dS(t.title)?t.title:null}function pS(e,t,n=!1){return Lo(e,t,{download:n})}function mS(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>dS(e)?(0,$.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`underline decoration-muted-foreground underline-offset-2 hover:text-primary`,children:e},`${e}-${t}`):e)}function hS(e){return e?new Date(e).toLocaleString():``}function gS(){let{code:e=``}=bl(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=(0,Q.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,Q.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=uS(t);return[t.schema,n.title,n.preview,n.subtitle,sS(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,Q.useCallback)(async()=>{if(e){i(!0);try{let t=await X.get(`${Lr}/pub/c/${encodeURIComponent(e)}`,{skipAuth:!0});n(t),o(null)}catch(e){n(null),o(e instanceof Error?e.message:`Failed to load public canvas`)}finally{i(!1)}}},[e]);(0,Q.useEffect)(()=>{p()},[p]),(0,Q.useEffect)(()=>{if(!e)return;let t=zr(`${Rr}/pub`,{transports:[`websocket`],auth:{code:e},reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1500});return t.on(`connect`,()=>c(!0)),t.on(`disconnect`,()=>c(!1)),t.on(`connect_error`,()=>c(!1)),t.on(`canvas:changed`,()=>p()),()=>{t?.disconnect(),t=null}},[e,p]);let m=(0,Q.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,Q.useCallback)(()=>{u(``)},[]),g=(0,Q.useCallback)(async e=>({payload:ri(e?.sortBy)?ki(d,e.sortBy,e?.order):d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,$.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,$.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,$.jsxs)(Ku,{className:`max-w-md bg-card`,children:[(0,$.jsx)(qu,{children:(0,$.jsx)(Ju,{children:`Canvas unavailable`})}),(0,$.jsx)(Xu,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,$.jsx)(fd,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,$.jsx)(Bo.Provider,{value:e,children:(0,$.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,$.jsxs)(Ku,{className:`bg-card shadow-elevation-3`,children:[(0,$.jsx)(qu,{className:`border-b p-3 sm:p-6`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,$.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-accent text-primary sm:mt-1 sm:h-12 sm:w-12 sm:rounded-2xl`,style:t.canvas.color?{borderLeft:`4px solid ${t.canvas.color}`}:void 0,children:(0,$.jsx)(gt,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground md:hidden`,children:[s?(0,$.jsx)(pr,{className:`h-3 w-3 text-success`}):(0,$.jsx)(w,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,$.jsx)(Ju,{className:`mt-0.5 truncate text-2xl sm:mt-1 sm:text-3xl md:text-5xl`,children:t.canvas.label||t.canvas.name||`Canvas`}),t.canvas.description&&(0,$.jsx)(`p`,{className:`mt-1.5 max-w-3xl text-sm text-muted-foreground sm:mt-3 sm:text-base`,children:t.canvas.description})]})]}),(0,$.jsxs)(`div`,{className:`hidden shrink-0 items-center gap-2 rounded-full border px-3 py-1 text-xs text-muted-foreground md:flex`,children:[s?(0,$.jsx)(pr,{className:`h-3.5 w-3.5 text-success`}):(0,$.jsx)(w,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,$.jsxs)(Xu,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,$.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,$.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,$.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,$.jsxs)(`span`,{className:`truncate`,children:[`· `,hS(t.stats.refreshedAt)]})]}),(0,$.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,$.jsx)(_S,{label:`Path`,value:t.share.path,mono:!0}),(0,$.jsx)(_S,{label:`Documents`,value:String(t.stats.documentCount)}),(0,$.jsx)(_S,{label:`Shown`,value:String(f.length)}),(0,$.jsx)(_S,{label:`Refreshed`,value:hS(t.stats.refreshedAt)})]}),v&&(0,$.jsx)(`section`,{id:`content-area`,className:`flex w-full flex-col overflow-hidden rounded-2xl border h-viewport-card min-h-[420px] md:h-viewport-pane`,children:(0,$.jsx)(iS,{workspaceId:t.workspace.name,treeName:t.share.treeName,path:t.share.path,layerId:t.canvas.id,querySpec:t.canvas.querySpec,metadata:t.canvas.metadata,readOnly:!0,interactive:!1,fetchDocuments:g},JSON.stringify(_))}),!v&&(0,$.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 border-b px-4 py-3 md:flex-row md:items-center md:justify-between`,children:[(0,$.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,$.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{type:`search`,value:l,onChange:e=>u(e.target.value),placeholder:`Search loaded documents...`,className:`w-full rounded-md border py-1.5 pl-9 pr-8 text-sm md:w-72`}),l&&(0,$.jsx)(`button`,{type:`button`,onClick:h,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:p,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,$.jsx)(P,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,$.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,$.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,$.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,$.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:l.trim()?`No loaded documents match your search.`:`No documents yet.`}):f.map(t=>{let n=uS(t),r=fS(t,n),i=t.schema===aS,a=i?pS(e,t.id):null,o=a||r;return(0,$.jsxs)(`article`,{className:`p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,$.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,$.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,$.jsxs)(`a`,{href:pS(e,t.id,!0),download:n.title,className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(qt,{className:`h-3.5 w-3.5`}),`Download`]}),(0,$.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:hS(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,$.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:mS(n.preview)}),cS(t)&&(0,$.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,$.jsx)(`img`,{src:a||void 0,alt:n.title,loading:`lazy`,className:`max-h-64 max-w-full rounded border bg-muted object-contain transition-opacity hover:opacity-90`})})]},t.id)})})]})]})]}),(0,$.jsx)(fd,{className:`mt-6 text-center`})]})})})}function _S({label:e,value:t,mono:n=!1}){return(0,$.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,$.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,$.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var vS={title:``,content:``,comment:``,tags:[]};function yS(e,t,n=`add`){let r=R_(),i=qo(`new:${n}:${e?.mode===`workspace`?`${e.workspaceName}:${e.treeName}:${e.path}`:e?.contextId??`home`}`),a=e=>async(n,i,a)=>{let o=typeof i.workspace==`string`?i.workspace:(await Ms(e)).workspaceName,s=await r.capture(),c={schema:`data/schema/note`,schemaVersion:`2.0`,comment:n.comment,data:{title:n.title.trim(),content:n.content},metadata:{features:Yo(n.tags),...s?{geo:s}:{}}},l=typeof i.id==`number`?i.id:void 0;if(l==null){let t=await ys(e,[c],{refresh:!1});if(!t.length)throw Error(`The server did not return the saved note`);l=t[0],a({id:l,workspace:o})}else await fa(o,{...c,id:l});await t?.([l]),_s(e)},o=zo(i,vS,{retainAfterSave:!0,valid:e=>!!e.content.trim(),save:e?a(e):void 0});async function s(e){await o.saveWith(a(e));let t=o.getSnapshot().meta.id;if(typeof t!=`number`)throw Error(`Write a note before saving`);return[t]}return{...o.value,status:o.status,error:o.error,storageError:o.storageError,setTitle:e=>o.update({title:e}),setContent:e=>o.update({content:e}),setComment:e=>o.update({comment:e}),setTags:e=>o.update({tags:e}),saving:o.status===`saving`,canSave:!!o.value.content.trim()&&o.status!==`saving`,save:s,finish:o.clear,retry:o.flush,geotag:r}}var bS=(0,Q.createContext)(void 0);function xS(){let e=(0,Q.useContext)(bS),t=es()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,Q.useMemo)(()=>e===void 0?n?r===`context`&&i?{mode:`context`,contextId:i}:a&&o?{mode:`workspace`,workspaceName:a,path:o,treeName:s||`context`,treeType:s===`directory`||s===`backends`?`directory`:`context`}:null:null:e,[e,n,r,i,a,o,s])}function SS({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,Q.useRef)(null),o=(0,Q.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,Q.useEffect)(()=>{o()},[e,o]),(0,$.jsx)(`textarea`,{ref:e=>{a.current=e,i?.(e)},value:e,onChange:e=>t(e.target.value),onBlur:n,placeholder:r,rows:1,spellCheck:!1,className:`w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-sm leading-relaxed text-foreground outline-none placeholder:text-muted-foreground/60`})}function CS({onLinkTo:e,onDelete:t}){return(0,$.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:e,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Link to…`,title:`Link to…`,children:(0,$.jsx)(Zt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-destructive`,"aria-label":`Delete`,title:`Delete (moves to trash)`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})}function wS({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,Q.useState)(!1);return(0,$.jsx)($p,{onClose:n,children:(0,$.jsx)(ih,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await Qr(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:Qp,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 go(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Rg(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var TS=1200;function ES(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 DS(e,t){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([Ss(n,[t]),Cs(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 Na(n,i,[t],{treeName:o,treeType:c,limit:50}).then(e=>{r(e.payload||[]),l({workspaceName:n,path:i,treeName:o,treeType:c})}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))},[e,t]),d=(0,Q.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,Q.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,Q.useEffect)(()=>{u()},[u]),(0,Q.useEffect)(()=>{let e=()=>d();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[d]),{docs:n,setDocs:r,loading:i,error:o,scope:c,reload:d,removeDoc:(0,Q.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await ai(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}function OS({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let s=No(e,t||``,!!t),{title:c,content:l,setTitle:u,setContent:d}=s,f=()=>{s.save().catch(()=>{})};return(0,$.jsxs)(`div`,{ref:t=>n(e.id,t),className:J(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[ES(e.createdAt),` · #`,e.id]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[(0,$.jsx)(Go,{...s,onRetry:s.save}),(0,$.jsx)(CS,{onLinkTo:a,onDelete:o})]})]}),(0,$.jsx)(`input`,{value:c,onChange:e=>u(e.target.value),onBlur:f,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(SS,{value:l,onChange:d,onBlur:f,innerRef:t=>r(e.id,t)})]})}function kS({target:e,onCreated:t,onCancel:n}){let r=yS(e,void 0,`applet`),{title:i,content:a,setTitle:o,setContent:s,saving:c}=r,[l,u]=(0,Q.useState)(null),d=async()=>{try{await r.save(e),r.finish(),t()}catch(e){u(e instanceof Error?e.message:`Failed to save note`)}};return(0,$.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Close note`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]}),(0,$.jsx)(`input`,{value:i,onChange:e=>o(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(SS,{value:a,onChange:s,placeholder:`Write your note…`}),(0,$.jsx)(Go,{...r,onRetry:r.retry}),l&&(0,$.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,$.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,$.jsx)(`button`,{type:`button`,onClick:d,disabled:!a.trim()||c,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:c?`Saving…`:`Done`})})]})}function AS({autoAdd:e=!1}){let t=xS(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=DS(t,ko),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(0),[f,p]=(0,Q.useState)(`desc`),[m,h]=(0,Q.useState)(e),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(new Map),y=(0,Q.useRef)(new Map),b=(0,Q.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,Q.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,Q.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await s(e.id)}catch{}},[s]),C=(0,Q.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return f===`asc`?n:-n}),e},[n,f]),w=(0,Q.useMemo)(()=>{let e=c.trim().toLowerCase();if(!e)return[];let t=[];for(let n of C){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[c,C]),T=w.length?w[Math.min(u,w.length-1)]:null;(0,Q.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,Q.useCallback)(e=>{if(!w.length)return;let t=e?(u+1)%w.length:u;e&&d(t);let n=w[t],r=y.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+c.trim().length)),v.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[w,u,c]);return t?(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),d(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),E(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),c.trim()&&(0,$.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:w.length?`${Math.min(u+1,w.length)}/${w.length}`:`0/0`})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:f===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:f===`desc`?(0,$.jsx)(Bt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(wn,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>h(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,$.jsx)(sn,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,$.jsx)(kS,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)},JSON.stringify(t)),r&&!n.length&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Yn,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,$.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,$.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),C.map(e=>(0,$.jsx)(OS,{doc:e,updateWorkspace:a?.workspaceName??null,registerEl:b,registerBody:x,highlighted:T?.docId===e.id,onLinkTo:()=>_(e.id),onDelete:()=>S(e)},e.id))]}),g!==null&&(0,$.jsx)(wS,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:js(t)})}var jS=`2.1`,MS=new Set([`completed`,`cancelled`]);function NS({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,Q.useState)(String(e.data?.title??``)),[u,d]=(0,Q.useState)(String(e.data?.description??``)),[f,p]=(0,Q.useState)(e.data?.status||`pending`),[m,h]=(0,Q.useState)(W_(e.data?.dueDate)),[g,_]=(0,Q.useState)(`idle`),{replicating:v,label:y}=bo(e),b=(0,Q.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),x=(0,Q.useRef)(null),S=(0,Q.useRef)(0),C=(0,Q.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++S.current;_(`saving`);try{let i=G_(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 fa(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,Q.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}),TS))},[C,f,m]),T=(0,Q.useCallback)(()=>{x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:m})},[C,c,u,f,m]);(0,Q.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]);let E=(0,Q.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,Q.useCallback)(e=>{h(e),x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:e})},[C,c,u,f]),O=MS.has(f);return(0,$.jsxs)(`div`,{ref:t=>n(e.id,t),className:J(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,$.jsxs)(`span`,{className:`shrink-0`,children:[ES(e.createdAt),` · #`,e.id,f!==`pending`&&(0,$.jsxs)(`span`,{children:[` · `,V_[f]??f]})]}),(0,$.jsx)(Bv,{value:m,onChange:D,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,$.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,$.jsx)(Yn,{className:`inline h-3 w-3 animate-spin`}),v&&(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,$.jsx)(oe,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,$.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,$.jsx)(CS,{onLinkTo:a,onDelete:o})]})]}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.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,$.jsx)(be,{className:`h-4 w-4 text-success`}):(0,$.jsx)(ln,{className:`h-4 w-4`})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),w(e.target.value,u)},onBlur:T,placeholder:`Untitled`,spellCheck:!1,className:J(`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,$.jsx)(SS,{value:u,onChange:e=>{d(e),w(c,e)},onBlur:T,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function PS({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(K_()),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null);return(0,$.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,$.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]}),(0,$.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`What needs doing?`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,$.jsx)(SS,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,$.jsx)(`div`,{className:`mt-2`,children:(0,$.jsx)(Bv,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,$.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,$.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await ys(e,[{schema:Ji,schemaVersion:jS,data:q_({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 FS({autoAdd:e=!1}){let t=xS(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=DS(t,Ji),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(0),[p,m]=(0,Q.useState)(`desc`),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(e),[y,b]=(0,Q.useState)(null),x=(0,Q.useRef)(new Map),S=(0,Q.useRef)(new Map),C=(0,Q.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,Q.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,Q.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete todo ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await c(e.id)}catch{}},[c]),E=(0,Q.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,Q.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!MS.has(String(e.data?.status??`pending`)));return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return p===`asc`?n:-n}),e},[n,p,h]),O=(0,Q.useMemo)(()=>n.filter(e=>MS.has(String(e.data?.status??`pending`))).length,[n]),k=(0,Q.useMemo)(()=>{let e=l.trim().toLowerCase();if(!e)return[];let t=[];for(let n of D){let r=String(n.data?.description??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[l,D]),A=k.length?k[Math.min(d,k.length-1)]:null;(0,Q.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,Q.useCallback)(e=>{if(!k.length)return;let t=e?(d+1)%k.length:d;e&&f(t);let n=k[t],r=S.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+l.trim().length)),x.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[k,d,l]);return t?(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(tr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,$.jsx)(`input`,{value:l,onChange:e=>{u(e.target.value),f(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),j(!0))},placeholder:`Search todos…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),l.trim()&&(0,$.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:k.length?`${Math.min(d+1,k.length)}/${k.length}`:`0/0`})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:J(`rounded-md border p-1.5 transition-colors`,h?`border-foreground text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:h?`Hide done items`:`Show done items${O?` (${O})`:``}`,"aria-label":h?`Hide done items`:`Show done items`,children:h?(0,$.jsx)(Xn,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Nt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:p===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:p===`desc`?(0,$.jsx)(Bt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(wn,{className:`h-3.5 w-3.5`})}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a todo`,children:[(0,$.jsx)(sn,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,$.jsx)(PS,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Yn,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,$.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,$.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:O?`Nothing pending - ${O} done item${O>1?`s`:``} hidden.`:`No todos here yet - add the first one.`}),D.map(e=>(0,$.jsx)(NS,{doc:e,updateWorkspace:o?.workspaceName??null,registerEl:C,registerBody:w,highlighted:A?.docId===e.id,onLinkTo:()=>b(e.id),onDelete:()=>T(e),onStatusSaved:E},e.id))]}),y!==null&&(0,$.jsx)(wS,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:js(t)})}var IS=(0,Q.createContext)(null);function LS(){let e=(0,Q.useContext)(IS);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function RS(e=!0){let{registerViewer:t}=LS();(0,Q.useEffect)(()=>{if(e)return t()},[e,t])}var zS=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],BS=`canvas.lens.camera`,VS={min:1,max:4,step:.1,hardware:!1};function HS(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(BS)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:zS.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function US(e,t){let n=zS.find(t=>t.id===e.resolution)??zS[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function WS(e={}){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(e.onEnded);(0,Q.useEffect)(()=>{n.current=e.onEnded});let r=(0,Q.useRef)(null),i=(0,Q.useRef)(null),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(HS),p=(0,Q.useRef)(d),[m,h]=(0,Q.useState)([]),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(1),w=(0,Q.useRef)(1),[T,E]=(0,Q.useState)(!1),D=(0,Q.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,Q.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,Q.useCallback)(async()=>{try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`&&e.deviceId);h(e.map((e,t)=>({deviceId:e.deviceId,label:e.label||`Camera ${t+1}`})))}catch{}},[]),j=(0,Q.useCallback)(()=>{D.current&&window.clearTimeout(D.current),r.current?.getTracks().forEach(e=>e.stop()),r.current=null,t.current&&(t.current.srcObject=null),c(null),o(!1),_(!1),y(null),x(null),C(1),w.current=1,E(!1)},[]),M=(0,Q.useCallback)(async(e,i)=>{r.current=e,e.getVideoTracks().forEach(e=>{e.onended=()=>{j(),n.current?.()}}),t.current&&(t.current.srcObject=e,await t.current.play().catch(()=>{}));let a=e.getVideoTracks()[0],s=a?.getSettings();if(x(s?.width&&s?.height?{width:s.width,height:s.height}:null),_(i),E(!1),i&&a){let e=a.getCapabilities?.()??{};y(e),e.focusMode?.includes(`continuous`)&&await k({focusMode:`continuous`});let t=a.getSettings().zoom;C(e.zoom?t??e.zoom.min:1),w.current=1,A()}c(e),o(!0)},[j,k,A]),N=(0,Q.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:US(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:US(e,!1),audio:!1});throw t}},[]),P=(0,Q.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Camera needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getUserMedia)return u(`Camera API not available in this browser.`),!1;try{let e=await N(p.current);return await M(e,!0),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Camera permission denied.`:t===`NotFoundError`?`No camera found.`:`Camera failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M,N]),F=(0,Q.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Screen capture needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getDisplayMedia)return u(`Screen capture API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1280},height:{ideal:720}},audio:!1});return await M(e,!1),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Screen capture cancelled.`:`Screen capture failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M]),I=(0,Q.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(BS,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]),L=(0,Q.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),R=(0,Q.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),z=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),ee=(0,Q.useCallback)(e=>{let t=v?.focusMode??[];if(!t.length)return;D.current&&window.clearTimeout(D.current);let n=navigator.mediaDevices.getSupportedConstraints(),r=e&&n.pointsOfInterest?{pointsOfInterest:[e]}:{};t.includes(`single-shot`)?(k({...r,focusMode:`single-shot`}),t.includes(`continuous`)&&(D.current=window.setTimeout(()=>void k({...r,focusMode:`continuous`}),1500))):k({...r,focusMode:`continuous`})},[v,k]),te=(0,Q.useCallback)((e=640,n=.72)=>{let r=t.current;if(!r||r.readyState<2||!r.videoWidth)return null;let a=Math.max(1,w.current),o=r.videoWidth/a,s=r.videoHeight/a,c=(r.videoWidth-o)/2,l=(r.videoHeight-s)/2,u=Math.min(1,e/Math.max(o,s)),d=Math.round(o*u),f=Math.round(s*u);i.current||=document.createElement(`canvas`);let p=i.current;p.width=d,p.height=f;let m=p.getContext(`2d`);return m?(m.drawImage(r,c,l,o,s,0,0,d,f),p.toDataURL(`image/jpeg`,n)):null},[]);return(0,Q.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:P,startScreen:F,stop:j,captureFrame:te,camera:(0,Q.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}:VS,zoom:S,setZoom:L,torchSupported:!!v?.torch,torch:T,setTorch:R,focusSupported:z,focusAt:ee}:null,[g,m,d,I,b,v,S,L,T,R,z,ee])}}async function GS(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 X.postEnvelope(`${xr.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 KS=[{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}],qS=1e3,JS=32,YS=12,XS=`canvas.lens.fit`;function ZS({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=LS(),a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,Q.useEffect)(()=>{if(!o)return;let e=window.setTimeout(()=>s(null),900);return()=>window.clearTimeout(e)},[o]);let c=r&&!r.zoomRange.hardware?r.zoom:1;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`video`,{ref:a,muted:!0,playsInline:!0,onClick:t?e=>{let t=a.current;if(!t||!r?.focusSupported||!t.videoWidth)return;let n=t.getBoundingClientRect(),o=(e.clientX-n.left)/n.width,l=(e.clientY-n.top)/n.height,u=.5+(o-.5)/c,d=.5+(l-.5)/c,f=i===`contain`?Math.min(n.width/t.videoWidth,n.height/t.videoHeight):Math.max(n.width/t.videoWidth,n.height/t.videoHeight),p=t.videoWidth*f/n.width,m=t.videoHeight*f/n.height,h=.5+(u-.5)/p,g=.5+(d-.5)/m;h<0||h>1||g<0||g>1||(r.focusAt({x:h,y:g}),s({x:o,y:l,key:Date.now()}))}:void 0,style:c===1?void 0:{transform:`scale(${c})`},className:J(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,$.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute h-10 w-10 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white/90 animate-fade-in`,style:{left:`${o.x*100}%`,top:`${o.y*100}%`}},o.key)]})}function QS({children:e}){let t=es(),n=(0,Q.useRef)(t);(0,Q.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,Q.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=WS({onEnded:()=>a.current()}),[m,h]=(0,Q.useState)(null),g=(0,Q.useRef)(m);(0,Q.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(qS),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(null),[N,P]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(null),[L,R]=(0,Q.useState)(null),z=L&&L.frame===F?L:null,ee=(0,Q.useRef)(null),[te,ne]=(0,Q.useState)(0),[B,re]=(0,Q.useState)(``),[ie,ae]=(0,Q.useState)(()=>{try{return localStorage.getItem(XS)===`cover`?`cover`:`contain`}catch{return`contain`}}),oe=(0,Q.useCallback)(e=>{ae(e);try{localStorage.setItem(XS,e)}catch{}},[]),V=(0,Q.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:qS,snapshot:!1}),H=(0,Q.useRef)([]),U=(0,Q.useRef)(new Map),se=(0,Q.useRef)(null),W=(0,Q.useRef)(null),ce=(0,Q.useRef)(null),le=(0,Q.useRef)(0),ue=(0,Q.useRef)(``),de=(0,Q.useRef)(!1),fe=(0,Q.useRef)(async()=>{}),pe=(0,Q.useRef)(()=>{});(0,Q.useEffect)(()=>{V.current.text=T,V.current.maxDistance=C===``?NaN:Number(C),V.current.rateMs=x,V.current.paused=y},[T,C,x,y]);let me=(0,Q.useCallback)(()=>(ne(e=>e+1),()=>ne(e=>Math.max(0,e-1))),[]),G=(0,Q.useCallback)(e=>{H.current=[...H.current.slice(-2),e];let t=H.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=se.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(se.current=i,n.current?.setLensIds(i))},[]),he=(0,Q.useCallback)((e,t)=>{for(let n of e)U.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);H.current=[...H.current.slice(-2),n];let r=H.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...U.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>U.current.get(e)).filter(e=>!!e);M(s.length),P(s)},[]),ge=(0,Q.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;ce.current?.abort();let a=new AbortController;ce.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await GS(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?[...Xy(o.filters.timeline),...qy(o.filters.geo),...Jy(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?YS:JS,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||V.current!==t||!t.running?!1:(le.current=0,A(Math.round(performance.now()-r)),O(null),i?he(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):G(c.ids),!0)}catch(e){return a.signal.aborted||V.current!==t||!t.running?!1:(le.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[he,G]),_e=(0,Q.useCallback)(async()=>{let e=V.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await ge(t,e)}if(V.current.running){let e=Math.max(le.current?Math.min(3e4,1e3*2**Math.min(le.current-1,5)):0,V.current.rateMs-(performance.now()-t));W.current=window.setTimeout(()=>void fe.current(),e)}},[p,ge]);(0,Q.useEffect)(()=>{fe.current=_e},[_e]);let ve=(0,Q.useCallback)(()=>{let e=V.current.consumer===`filter`;V.current.running=!1,le.current=0,V.current.consumer=null,W.current&&window.clearTimeout(W.current),ce.current?.abort(),f(),H.current=[],U.current.clear(),se.current=null,h(null),v(null),b(!1),re(``),P([]),I(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,Q.useEffect)(()=>{a.current=ve},[ve]);let K=(0,Q.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||de.current||(V.current.running&&ve(),e===`photo`&&!r.image))return!1;de.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return de.current=!1,i?(H.current=[],U.current.clear(),se.current=null,P([]),M(null),O(null),re(r.workspaceRef),V.current={...V.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`?pe.current(r.image):_e(),!0):!1},[u,d,ve,_e]),q=JSON.stringify(t?{contextId:t.state.activeContextId,path:t.state.activeContextPath,tree:t.state.activeTreeName,features:t.state.filters.features,timeline:t.state.filters.timeline,geo:t.state.filters.geo,gps:t.state.filters.lens.gps}:null);(0,Q.useEffect)(()=>{ue.current!==q&&(ue.current=q,V.current.consumer===`filter`&&(ce.current?.abort(),H.current=[],se.current=null,n.current?.setLensIds([])))},[q]);let ye=(0,Q.useCallback)(e=>{V.current.contextPath=e},[]),be=(0,Q.useCallback)(e=>{V.current.paused=e,b(e)},[]),xe=JSON.stringify([T,C,q]),Se=(0,Q.useRef)(xe);(0,Q.useEffect)(()=>{Se.current=xe});let Ce=(0,Q.useCallback)(e=>{let t=V.current;!t.running||!t.workspaceRef||(ee.current={frame:e,key:Se.current},H.current=[],U.current.clear(),se.current=null,M(null),ge(e,t))},[ge]);(0,Q.useEffect)(()=>{pe.current=Ce},[Ce]);let we=(0,Q.useCallback)(()=>{let e=V.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,I(t),Ce(t))},[p,Ce]),Te=(0,Q.useCallback)(()=>{if(V.current.running&&g.current===`photo`){ve();return}V.current.snapshot=!1,ce.current?.abort(),H.current=[],U.current.clear(),I(null)},[ve]),Ee=(0,Q.useCallback)(async(e,t,n)=>{let r=V.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,I(e),Ce(e),!0):K(`photo`,t,{...n,image:e})},[K,Ce]);(0,Q.useEffect)(()=>{if(!F)return;let e=!0,t=new Image;return t.onload=()=>{e&&R({frame:F,width:t.naturalWidth,height:t.naturalHeight})},t.src=F,()=>{e=!1}},[F]),(0,Q.useEffect)(()=>{if(!F)return;let e=ee.current;if(e&&e.frame===F&&e.key===xe)return;let t=window.setTimeout(()=>Ce(F),350);return()=>window.clearTimeout(t)},[F,xe,Ce]),(0,Q.useEffect)(()=>{!i||!V.current.running||r&&r===V.current.workspaceRef||ve()},[i,r,ve]);let De=(0,Q.useCallback)(()=>{let e=n.current;if(e){if(V.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,Q.useEffect)(()=>ve,[ve]);let Oe=(0,Q.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:ie,setFit:oe,workspaceRef:B,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:K,setContextPath:ye,stop:ve,setPaused:be,snapshot:F,takeSnapshot:we,clearSnapshot:Te,snapshotSize:z,searchPhoto:Ee,reopen:De,hasViewer:te>0,registerViewer:me}),[m,y,_,s,c,ie,oe,B,x,C,T,l,D,k,j,N,K,ye,ve,be,F,we,Te,z,Ee,De,te,me]);return(0,$.jsxs)(IS.Provider,{value:Oe,children:[e,(0,$.jsx)(`video`,{ref:o,muted:!0,playsInline:!0,"aria-hidden":!0,className:`pointer-events-none fixed bottom-0 left-0 h-px w-px opacity-0`})]})}var $S=`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`,eC=`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`,tC=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function nC({className:e}){let{camera:t,fit:n,setFit:r}=LS();if(!t)return null;let{devices:i,prefs:a,setPrefs:o,size:s,zoomRange:c,zoom:l,setZoom:u}=t,d=c.max>c.min;return(0,$.jsxs)(`div`,{className:J(`flex flex-col gap-2`,e),children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,$.jsxs)(`select`,{className:J($S,`max-w-[12rem] flex-1`),value:a.deviceId??``,onChange:e=>o({deviceId:e.target.value||null}),title:`Camera / lens. On phones with several rear cameras, pick the main or wide one if the picture is too zoomed in.`,"aria-label":`Camera`,children:[(0,$.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,$.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,$.jsx)(`select`,{className:$S,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:zS.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:eC,title:n===`contain`?`Showing the whole frame — switch to fill the preview`:`Filling the preview (edges cropped) — switch to the whole frame`,"aria-label":n===`contain`?`Fill preview`:`Fit whole frame`,children:n===`contain`?(0,$.jsx)(An,{className:`h-3.5 w-3.5`}):(0,$.jsx)(At,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,$.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:eC,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,$.jsx)(dr,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:J(eC,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,$.jsx)(Ae,{className:`h-3.5 w-3.5`}):(0,$.jsx)(v,{className:`h-3.5 w-3.5`})}),s&&(0,$.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,title:c.hardware?`Optical/sensor zoom`:`Digital zoom — crops the searched frame too`,children:[(0,$.jsx)(R,{className:`h-3.5 w-3.5 shrink-0`}),(0,$.jsx)(`input`,{type:`range`,min:c.min,max:c.max,step:c.step,value:l,onChange:e=>u(Number(e.target.value)),onDoubleClick:()=>u(c.min),className:`h-1 min-w-0 flex-1 accent-foreground`,"aria-label":`Zoom`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:tC(l)})]})]})}function rC(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=LS();return e?n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:J(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,$.jsx)(`span`,{className:`pointer-events-none absolute left-2 top-2 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-white`,children:t===`photo`?`Photo`:`Snapshot`}),(0,$.jsx)(`button`,{type:`button`,onClick:i,className:`absolute bottom-2 left-1/2 flex h-9 -translate-x-1/2 items-center gap-1.5 rounded-full bg-black/60 px-3 text-xs font-medium text-white backdrop-blur transition-colors hover:bg-black/75`,title:t===`photo`?`Close the photo and clear its matches`:`Discard the snapshot and go back to the live feed`,children:t===`photo`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(G,{className:`h-3.5 w-3.5`}),` Close`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ir,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Take a snapshot and search it`,title:`Snapshot: freeze this frame and search for similar items`,className:`absolute bottom-2 left-1/2 flex h-12 w-12 -translate-x-1/2 items-center justify-center rounded-full border-4 border-white/90 bg-white/25 text-white shadow-lg backdrop-blur transition-transform hover:bg-white/40 active:scale-90`,children:(0,$.jsx)(Xt,{className:`h-5 w-5`})}):null}async function iC(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 aC({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=LS(),o=(0,Q.useRef)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await iC(r);await a(i,e,{workspaceRef:t,contextPath:n})}catch{u(`Could not read that image.`)}finally{c(!1),o.current&&(o.current.value=``)}}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o.current?.click(),disabled:r||s||!t,className:i,title:l??`Search with a photo from the camera app or gallery`,children:[(0,$.jsx)(x,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,$.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,$.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var oC=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,sC=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function cC({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=Ei(t),{blobUrl:a}=__(e,t.id,256,{enabled:i}),o=Yr(t);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-(--card-radius) border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,$.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,$.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,$.jsx)(Gm,{document:t,size:10})}),(0,$.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,$.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function lC(){let e=xS(),t=py(),n=LS(),{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:[];RS(p);let g=p?n.snapshotSize??n.camera?.size:null,_=!!g&&g.height>g.width,v=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:y}=n;return(0,Q.useEffect)(()=>{p&&y(f)},[p,f,y]),e?.mode===`workspace`?(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,$.jsx)(`select`,{className:oC,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:KS.map(e=>(0,$.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,$.jsx)(`input`,{className:J(sC,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,$.jsx)(`input`,{className:J(sC,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:s,onChange:e=>c(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),p?(0,$.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,$.jsx)(on,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(`camera`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Ke,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(`screen`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Fn,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,$.jsx)(aC,{consumer:`applet`,workspaceRef:d,contextPath:f,disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`})]}),(0,$.jsxs)(`div`,{className:J(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,_?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[p&&(0,$.jsx)(ZS,{className:`h-full w-full`,interactive:!0}),p&&(0,$.jsx)(rC,{}),!p&&(0,$.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,$.jsx)(dt,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),p&&(0,$.jsx)(nC,{className:`shrink-0`}),(0,$.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,$.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,$.jsxs)($.Fragment,{children:[n.snapshot?`snapshot`:`live`,` · `,l==null?`searching…`:`${l} ms/frame`,` · `,h.length,` match`,h.length===1?``:`es`,f?` · scoped to ${f}`:``]}):m?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),h.length===0?(0,$.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:p?n.snapshot?`Nothing similar in the snapshot`:`Nothing matching in view`:`Matches appear here`}):(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,$.jsx)(cC,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}var uC=`data/schema/`,dC={"data/schema/file":{label:`Files`,icon:nn},"data/schema/note":{label:`Notes`,icon:Kn},"data/schema/task":{label:`Todos`,icon:Vt},"data/schema/tab":{label:`Tabs`,icon:Ye},"data/schema/message/email":{label:`Emails`,icon:bt},"data/schema/link":{label:`Links`,icon:_n},"data/schema/identity":{label:`Identities`,icon:We},"data/schema/drawing":{label:`Sketches`,icon:le}};function fC(e){return dC[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:ke}}function pC(e){return dC[e]?.icon??ke}function mC(e){return{...e,lens:Ky.lens}}function hC(e,t,n=!1){let r=n?e=>e:mC;return JSON.stringify(r(e))!==JSON.stringify(r(t??Ky))}var gC={savedGeoSelection:null,liveEnabled:!1,liveError:null,t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,addModal:!1,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null,activeContextPath:null,activeContextType:null,activeWorkspaceName:null,activeTreeName:null,activeCanvasId:null,activeContextId:null,activeAccentColor:null,filters:Ky,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function _C(e,t){switch(t.type){case`SET_VIEW`:return{...e,t1Open:t.view!==null,t1View:t.view};case`TOGGLE_VIEW`:return e.t1View===t.view?{...e,t1Open:!1,t1View:null}:{...e,t1Open:!0,t1View:t.view};case`CLOSE_T1`:return{...e,t1Open:!1,t1View:null,t2Open:!1,t2AgentId:null};case`OPEN_T2_AGENT`:return{...e,t2Open:!0,t2AgentId:t.agentId};case`CLOSE_T2`:return{...e,t2Open:!1,t2AgentId:null};case`OPEN_ADD`:return{...e,addOpen:!0,addModal:t.modal??(e.addOpen&&e.addModal),addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addModal:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,addModal:!1,addKind:null,addRelateTo:null,editDocument:t.document,editWorkspaceId:t.workspaceId};case`SET_TOOLS_TAB`:return{...e,toolsTab:t.tab};case`SET_APPS_APPLET`:return{...e,appsAppletId:t.appletId};case`SET_ACCENT_COLOR`:return e.activeAccentColor===t.color?e:{...e,activeAccentColor:t.color};case`SET_GEO_SELECTION`:return{...e,geoSelection:t.selection,isDirty:e.activeContextType===`context`?hC(e.filters,e.savedFilters,!0)||JSON.stringify(t.selection)!==JSON.stringify(e.savedGeoSelection):e.isDirty};case`SET_SAVED_GEO_SELECTION`:return{...e,savedGeoSelection:t.selection,isDirty:e.activeContextType===`context`?hC(e.filters,e.savedFilters,!0)||JSON.stringify(e.geoSelection)!==JSON.stringify(t.selection):e.isDirty};case`SET_MAP_DOCUMENTS`:return e.mapDocuments===t.documents&&e.mapWorkspaceId===t.workspaceId?e:{...e,mapDocuments:t.documents,mapWorkspaceId:t.workspaceId};case`SET_NAVIGATION`:{let n=e.activeContextType===t.contextType&&e.activeContextId===t.contextId&&e.activeCanvasId===t.canvasId;return{...e,activeWorkspaceName:t.workspaceName,activeTreeName:t.treeName,activeCanvasId:t.canvasId,activeContextId:t.contextId,activeContextType:t.contextType,activeContextPath:t.contextPath,geoSelection:null,...n?{}:{filters:Ky,savedFilters:null,savedSearchQuery:null,isDirty:!1,savedGeoSelection:null,liveEnabled:!1,liveError:null}}}case`SET_CONTEXT_SCOPE`:return e.activeContextType!==`context`||e.activeWorkspaceName===t.workspaceName&&e.activeContextPath===t.contextPath&&e.activeTreeName===t.treeId?e:{...e,activeWorkspaceName:t.workspaceName,activeContextPath:t.contextPath,activeTreeName:t.treeId};case`SET_LIVE`:return{...e,liveEnabled:t.enabled,liveError:null};case`SET_LIVE_ERROR`:return{...e,liveError:t.error};case`SET_FILTERS`:return{...e,filters:t.filters,isDirty:e.activeContextType===null?!1:hC(t.filters,e.savedFilters,e.activeContextType===`context`)||e.activeContextType===`context`&&JSON.stringify(e.geoSelection)!==JSON.stringify(e.savedGeoSelection)};case`SET_SAVED_FILTERS`:{let n=t.hydrating===!0&&e.isDirty,r=n?e.filters:t.savedFilters??Ky;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?hC(r,t.savedFilters,e.activeContextType===`context`):!1}}case`SET_SAVING`:return{...e,isSaving:t.isSaving};case`SET_BITMAPS`:return{...e,availableBitmaps:t.keys,bitmapsLoading:!1};case`SET_BITMAPS_LOADING`:return{...e,bitmapsLoading:t.loading};case`SET_TIMELINES`:return{...e,availableTimelines:t.names,timelineScales:t.scales??e.timelineScales,timelinesLoading:!1};case`SET_TIMELINES_LOADING`:return{...e,timelinesLoading:t.loading};default:return e}}var vC=`toolbox:session:filters`;function yC(){try{let e=localStorage.getItem(vC);if(!e)return null;let t=JSON.parse(e);return{...Ky,...t,features:{...Ky.features,...t.features??{}},timeline:{...Ky.timeline,...t.timeline??{}},geo:{...Ky.geo,...t.geo??{}},lens:Ky.lens,sort:Gy(t.sort)}}catch{return null}}function bC(e){try{localStorage.setItem(vC,JSON.stringify(mC(e)))}catch{}}function xC(e,t=!1){if(!e?.toolbox)return null;try{let n=e.toolbox;return{features:{allOf:n.features?.allOf??[],anyOf:n.features?.anyOf??[],noneOf:n.features?.noneOf??[]},timeline:{quickFilter:n.timeline?.quickFilter??null,customRanges:n.timeline?.customRanges??(n.timeline?.customRange?[n.timeline.customRange]:[]),indexCreated:n.timeline?.indexCreated??!0,indexUpdated:n.timeline?.indexUpdated??!0,indexDeleted:n.timeline?.indexDeleted??!1,contentEvents:n.timeline?.contentEvents??!1,selectedTimelines:n.timeline?.selectedTimelines??[]},geo:{bbox:n.geo?.bbox??null,includeUnlocated:n.geo?.includeUnlocated??!1},lens:t?{...Ky.lens,...n.lens??{}}:Ky.lens,sort:Gy(n.sort)}}catch{return null}}function SC(e,t){let n=e;for(let e of t.split(`/`).filter(Boolean))if(n=n?.children?.find(t=>t.name===e)??null,!n)break;return n}function CC({children:e,target:t}){let[n,r]=(0,Q.useReducer)(_C,gC),i=pl(),a=gl(),o=new URLSearchParams(i.search).get(`ownerId`)||void 0,s=(0,Q.useRef)(null),c=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{c.current=n}),(0,Q.useEffect)(()=>{let e=!1,n=i.pathname.split(`/`).filter(Boolean),a=t===void 0?n[0]===`workspaces`&&decodeURIComponent(n[1]||``)||null:t?.mode===`workspace`?t.workspaceName:null,o=t===void 0?n[0]===`contexts`&&decodeURIComponent(n[1]||``)||null:t?.mode===`context`?t.contextId:null,{path:s,treeName:l}=t?.mode===`workspace`?t:a?Px(i.pathname):{path:`/`,treeName:``},u=t=>{if(e)return;let n=t?`canvas`:o?`context`:null,i=c.current;i.activeContextType!==null&&n===null&&bC(i.filters),r({type:`SET_NAVIGATION`,workspaceName:a,treeName:a?l:null,canvasId:t,contextId:o,contextType:n,contextPath:a?s:null})};return a&&s!==`/`?(vi(a,l).then(t=>{if(e)return;let n=SC(t,s);u(n?.type===`canvas`?n.id:null)}).catch(()=>u(null)),()=>{e=!0}):(u(null),()=>{e=!0})},[i.pathname,t]),(0,Q.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_BITMAPS_LOADING`,loading:!0}),ti(e).then(e=>{r({type:`SET_BITMAPS`,keys:e})}))},[n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let e=n.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),Ti(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let{activeContextType:e,activeCanvasId:t,activeWorkspaceName:i,activeTreeName:a,activeContextPath:o}=n;if(e!==`context`){if(e===`canvas`&&t&&i&&o)vi(i,a||`context`).then(e=>{let t=SC(e,o),n=xC(t?.metadata);r({type:`SET_SAVED_FILTERS`,savedFilters:n,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{r({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=yC();r({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[n.activeCanvasId,n.activeContextPath,n.activeContextType,n.activeTreeName,n.activeWorkspaceName]),(0,Q.useEffect)(()=>{let{activeContextType:e,activeContextId:t}=n;if(e!==`context`||!t)return;let l=!1;s.current=null;let u=0,d=e=>{let t=new URLSearchParams(window.location.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let n=t.toString();a(`${i.pathname}${n?`?${n}`:``}${window.location.hash}`,{replace:!0})},f=(e,t,n,i=null,a=n?[n]:[])=>{let o=e?.filters??t??Ky,c=e?.geoSelection??i;s.current=JSON.stringify({filters:o,geoSelection:c,queries:e?.queries??a}),r({type:`SET_SAVED_FILTERS`,savedFilters:t,savedSearchQuery:n}),r({type:`SET_FILTERS`,filters:o}),r({type:`SET_GEO_SELECTION`,selection:c}),r({type:`SET_SAVED_GEO_SELECTION`,selection:i}),r({type:`SET_LIVE`,enabled:e!==null}),d(e?.queries??a)},p=e=>{let n=++u;return Cs(t,o).then(t=>{if(l||n!==u)return;let i=t.metadata,a=xC(i,!0),o=typeof i?.toolboxSearchQuery==`string`?i.toolboxSearchQuery:null;if(r({type:`SET_CONTEXT_SCOPE`,workspaceName:t.workspaceName||t.workspaceId||null,contextPath:t.path||`/`,treeId:t.treeId||null}),t.liveQuery)f(t.liveQuery,a,o,i?.toolboxGeoSelection??null,t.queryOptions?.queries);else if(e){r({type:`SET_LIVE`,enabled:!1});let e=c.current.isDirty?c.current.filters:a??Ky,n=i?.toolboxGeoSelection??null;s.current=JSON.stringify({filters:e,geoSelection:n,queries:[]}),r({type:`SET_SAVED_FILTERS`,savedFilters:a,savedSearchQuery:o,hydrating:!0}),r({type:`SET_GEO_SELECTION`,selection:n}),r({type:`SET_SAVED_GEO_SELECTION`,selection:n});let l=new URLSearchParams(window.location.search),u=t.queryOptions?.queries?.length?t.queryOptions.queries:o?[o]:[];!l.has(`q`)&&!l.has(`search`)&&u.length&&d(u)}}).catch(e=>{l||n!==u||r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not load context`})})};p(!0);let m=()=>{p(!1)},h=hd.on(`context.url.set`,e=>{e?.id===t&&m()}),g=hd.on(`context.updated`,e=>{let n=e;if((n.contextId||n.id)!==t)return;if(!n.metadata){p(!0);return}++u;let r=xC(n.metadata,!0);f(n.liveQuery??null,r,typeof n.metadata.toolboxSearchQuery==`string`?n.metadata.toolboxSearchQuery:null,n.metadata.toolboxGeoSelection??null,n.queryOptions?.queries)}),_=hd.on(`connect`,()=>{p(!0)}),v=hd.on(`disconnect`,()=>{c.current.liveEnabled&&r({type:`SET_LIVE_ERROR`,error:`Disconnected — Live updates will resume when connected.`})});return window.addEventListener(`contexts:refresh`,m),()=>{l=!0,s.current=null,h(),g(),_(),v(),window.removeEventListener(`contexts:refresh`,m)}},[n.activeContextId,n.activeContextType,o]);let l=(0,Q.useMemo)(()=>{let e=new URLSearchParams(i.search),t=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),n=(e.get(`search`)||``).trim();return t.length?t:n?[n]:[]},[i.search]),u=(0,Q.useRef)(l);(0,Q.useEffect)(()=>{u.current=l},[l]);let d=(0,Q.useRef)(!1),f=(0,Q.useRef)(null),[p,m]=(0,Q.useState)(0);(0,Q.useEffect)(()=>()=>{f.current!==null&&window.clearTimeout(f.current),f.current=null},[n.activeContextType,n.activeContextId,n.liveEnabled,o]),(0,Q.useEffect)(()=>{n.activeContextType!==`context`||!n.activeContextId||o||!n.liveEnabled||s.current===null||d.current||f.current!==null||!hd.isConnected()||JSON.stringify({filters:n.filters,geoSelection:n.geoSelection,queries:l})!==s.current&&(f.current=window.setTimeout(()=>{f.current=null;let e=c.current;if(e.activeContextId!==n.activeContextId||!e.liveEnabled)return;let t=u.current,i=JSON.stringify({filters:e.filters,geoSelection:e.geoSelection,queries:t});if(i===s.current)return;let a=s.current;d.current=!0;let o={filters:e.filters,geoSelection:e.geoSelection,queries:t,binding:Zy(e.filters,e.geoSelection,t)};hd.request(`context.filters.set`,{contextId:e.activeContextId,liveQuery:o}).then(()=>{c.current.activeContextId===e.activeContextId&&s.current===a&&(s.current=i,r({type:`SET_LIVE_ERROR`,error:null}))}).catch(t=>{c.current.activeContextId===e.activeContextId&&r({type:`SET_LIVE_ERROR`,error:t instanceof Error?t.message:`Live update failed`})}).finally(()=>{d.current=!1,m(e=>e+1)})},n.liveError?1500:100))},[n.activeContextType,n.activeContextId,n.liveEnabled,n.filters,n.geoSelection,l,o,p,n.liveError]);let h=(0,Q.useCallback)(async e=>{let t=c.current;if(t.activeContextType!==`context`||!t.activeContextId||o)return;let n=l,i=e?{filters:t.filters,geoSelection:t.geoSelection,queries:n,binding:Zy(t.filters,t.geoSelection,n)}:null;try{await hd.request(`context.filters.set`,{contextId:t.activeContextId,liveQuery:i}),s.current=JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:n}),r({type:`SET_LIVE`,enabled:e})}catch(e){r({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not change Live mode`})}},[o,l]);(0,Q.useEffect)(()=>{n.activeContextType===null&&bC(n.filters)},[n.filters,n.activeContextType]);let g=(0,Q.useCallback)(e=>r({type:`SET_VIEW`,view:e}),[]),_=(0,Q.useCallback)(e=>r({type:`TOGGLE_VIEW`,view:e}),[]),v=(0,Q.useCallback)(()=>r({type:`CLOSE_T1`}),[]),y=(0,Q.useCallback)(e=>r({type:`OPEN_T2_AGENT`,agentId:e}),[]),b=(0,Q.useCallback)(()=>r({type:`CLOSE_T2`}),[]),x=(0,Q.useCallback)(e=>r({type:`OPEN_ADD`,kind:e}),[]),S=(0,Q.useCallback)(e=>r({type:`OPEN_ADD`,kind:null,modal:e?.modal,relateTo:e?.fresh?null:void 0}),[]),C=(0,Q.useCallback)((e,t=!1)=>r({type:`OPEN_ADD`,kind:null,relateTo:e,modal:t}),[]),w=(0,Q.useCallback)(()=>r({type:`CLOSE_ADD`}),[]),T=(0,Q.useCallback)((e,t)=>r({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),E=(0,Q.useCallback)(e=>r({type:`SET_TOOLS_TAB`,tab:e}),[]),D=(0,Q.useCallback)(e=>r({type:`SET_APPS_APPLET`,appletId:e}),[]),O=(0,Q.useCallback)(e=>r({type:`SET_ACCENT_COLOR`,color:e}),[]),k=(0,Q.useCallback)(e=>{r({type:`SET_FILTERS`,filters:e})},[]),A=(0,Q.useCallback)((e,t)=>{let{filters:n}=c.current,i=e.startsWith(uC),a=i?n.features.allOf.filter(t=>t!==e):t?[...new Set([...n.features.allOf,e])]:n.features.allOf.filter(t=>t!==e),o=i&&t?[...new Set([...n.features.anyOf,e])]:n.features.anyOf.filter(t=>t!==e),s=n.features.noneOf.filter(t=>t!==e);r({type:`SET_FILTERS`,filters:{...n,features:{allOf:a,anyOf:o,noneOf:s}}})},[]),j=(0,Q.useCallback)((e,t)=>{let{filters:n}=c.current,i=n.features.allOf.filter(t=>t!==e),a=n.features.anyOf.filter(t=>t!==e),o=n.features.noneOf.filter(t=>t!==e);t===`allOf`?i.push(e):t===`anyOf`?a.push(e):t===`noneOf`&&o.push(e),r({type:`SET_FILTERS`,filters:{...n,features:{allOf:i,anyOf:a,noneOf:o}}})},[]),M=(0,Q.useCallback)(()=>{let{filters:e}=c.current;r({type:`SET_GEO_SELECTION`,selection:null}),r({type:`SET_FILTERS`,filters:{...Ky,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}});let t=new URLSearchParams(i.search);t.delete(`q`),t.delete(`search`),t.set(`q`,``),a({pathname:i.pathname,search:t.toString(),hash:i.hash},{replace:!0})},[i.pathname,i.search,i.hash,a]),N=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),P=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),F=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),I=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),L=(0,Q.useCallback)(e=>{let{filters:t}=c.current;r({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),R=(0,Q.useCallback)(e=>{r({type:`SET_GEO_SELECTION`,selection:e})},[]),z=(0,Q.useCallback)((e,t=null)=>{r({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),ee=(0,Q.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:n,activeTreeName:a,activeContextPath:s,filters:u,geoSelection:d,isSaving:f}=c.current;if(!f){r({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&n&&s){let e=a||`context`,t=SC(await vi(n,e),s),r=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await zi(n,s,{metadata:{...t?.metadata||{},toolbox:mC(u)},querySpec:{features:u.features,filters:[...Xy(u.timeline),...qy(u.geo)],query:r.trim()||void 0,sort:u.sort?.sortBy?u.sort:null}},e),Da(n,e)}else if(e===`context`&&t){let e=(await Cs(t,o)).metadata||{},n=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;await ns(t,{metadata:{...e,toolbox:u,toolboxGeoSelection:d,toolboxSearchQuery:n.trim()||void 0},...Zy(u,d,l)},o)}let c=new URLSearchParams(i.search).get(`q`)||new URLSearchParams(i.search).get(`search`)||``;r({type:`SET_SAVED_FILTERS`,savedFilters:u,savedSearchQuery:c.trim()||null,hydrating:!0}),e===`context`&&r({type:`SET_SAVED_GEO_SELECTION`,selection:d})}finally{r({type:`SET_SAVING`,isSaving:!1})}}},[i.search,o,l]),te=(0,Q.useCallback)(e=>{let t=c.current.availableBitmaps.filter(t=>t!==e);r({type:`SET_BITMAPS`,keys:t});let n=c.current.filters,i={...n,features:{allOf:n.features.allOf.filter(t=>t!==e),anyOf:n.features.anyOf.filter(t=>t!==e),noneOf:n.features.noneOf.filter(t=>t!==e)}};JSON.stringify(i.features)!==JSON.stringify(n.features)&&r({type:`SET_FILTERS`,filters:i})},[]),ne=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await yo(t,e),te(e)},[te]),B=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await Vi(t,e);return te(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[te]),re=(0,Q.useCallback)(()=>{let e=c.current.activeWorkspaceName;e&&(r({type:`SET_TIMELINES_LOADING`,loading:!0}),Ti(e).then(e=>{r({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[]),ie=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Ri(t,e),re()},[re]),ae=(0,Q.useCallback)(async e=>{let t=c.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await Oi(t,e);let n=c.current.availableTimelines.filter(t=>t!==e);r({type:`SET_TIMELINES`,names:n});let i=c.current.filters,a=i.timeline.selectedTimelines.filter(t=>t!==e);a.length!==i.timeline.selectedTimelines.length&&r({type:`SET_FILTERS`,filters:{...i,timeline:{...i.timeline,selectedTimelines:a}}})},[]),{features:oe,timeline:V,geo:H,lens:U}=n.filters,se=oe.allOf.length>0||oe.anyOf.length>0||oe.noneOf.length>0||V.quickFilter!==null||(V.customRanges?.length??0)>0||(V.selectedTimelines?.length??0)>0||H.bbox!==null||U.gps!==null||U.ids!==null||n.geoSelection!==null;return(0,$.jsx)(fs.Provider,{value:{state:n,setView:g,toggleView:_,closeT1:v,openAgentT2:y,closeT2:b,openAdd:x,openAddPicker:S,openAddRelated:C,closeAdd:w,openEdit:T,setToolsTab:E,openApplet:D,setAccentColor:O,setFilters:k,setFeatureToggle:A,setFeatureMode:j,clearFilters:M,hasActiveFilters:se,setTimelineFilter:P,setGeoBBox:F,setLensGps:I,setLensIds:L,setGeoSelection:R,setMapDocuments:z,setSort:N,setLiveEnabled:h,saveFilters:ee,deleteBitmap:ne,deleteDataset:B,createTimeline:ie,deleteTimeline:ae,refreshTimelines:re},children:e})}function wC(e){let t=new URLSearchParams(e),n=t.getAll(`q`).map(e=>e.trim()).filter(Boolean),r=(t.get(`search`)||``).trim();return t.has(`q`)?n:r?[r]:[]}function TC(){let{state:e,setFilters:t}=zs();return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:e.filters.geo.includeUnlocated??!1,onChange:n=>t({...e.filters,geo:{...e.filters.geo,includeUnlocated:n.target.checked}})}),`Include documents without a location`]})}var EC=p();Zo();var DC=`#8b5cf6`,OC=`#94a3b8`,kC={color:DC,weight:2,fillColor:DC,fillOpacity:.12},AC={color:DC,weight:2,dashArray:`5,5`,fillColor:DC,fillOpacity:.06},jC=e=>Math.round(e*1e6)/1e6;function MC(e){let t=e<10?32:e<100?38:44,n=`<div style="display:flex;align-items:center;justify-content:center;width:${t}px;height:${t}px;border-radius:9999px;background:${DC};color:#fff;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.4);font:600 12px system-ui,sans-serif;cursor:pointer">${e}</div>`;return ag.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var NC=e=>e.replace(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e]),PC=new Map;function FC(e){let t=PC.get(e);return t??(t=(0,EC.renderToStaticMarkup)((0,Q.createElement)(pC(e),{width:13,height:13,strokeWidth:2.5})),PC.set(e,t)),t}var IC=new Map;function LC(e,t){let n=`${e}|${+!!t}`,r=IC.get(n);if(!r){let i=`<div style="display:flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:9999px;background:${t?DC:OC};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${FC(e)}</div>`;r=ag.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),IC.set(n,r)}return r}function RC(){let{state:e,setGeoSelection:t,setGeoBBox:n}=zs(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=py(),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(null),p=(0,Q.useRef)([]),m=(0,Q.useRef)(!1),[h,g]=(0,Q.useState)(`idle`),[_,v]=(0,Q.useState)(0),y=(0,Q.useRef)(h),b=(0,Q.useMemo)(()=>r.reduce((e,t)=>e+ +!!Py(t),0),[r]),x=(0,Q.useMemo)(()=>i?r.reduce((e,t)=>{let n=Py(t);return e+(n&&Iy(n.lat,n.lon,i)?1:0)},0):0,[r,i]),S=(0,Q.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&ag.default.polyline(t,AC).addTo(e),t.forEach(t=>ag.default.circleMarker(t,{radius:4,color:DC,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),C=(0,Q.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),w=(0,Q.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:jC(e.lat),lon:jC(e.lng)}))}),C(),g(`idle`)},[t,C]),T=(0,Q.useCallback)(()=>{C(),g(`idle`),t(null),n(null)},[C,t,n]);(0,Q.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=ag.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});ag.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`&copy; OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=ag.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>MC(e.getChildCount())}).addTo(t),f.current=ag.default.layerGroup().addTo(t),l.current=t;let r=t.getContainer(),i=null,a=null,o=()=>{a&&=(a.remove(),null)},s=e=>{if(y.current===`rect`){e.preventDefault(),i=t.mouseEventToLatLng(e),o();try{r.setPointerCapture(e.pointerId)}catch{}}},m=e=>{if(y.current!==`rect`||!i)return;e.preventDefault();let n=ag.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=ag.default.rectangle(n,AC).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=ag.default.latLngBounds(i,t.mouseEventToLatLng(e));i=null,o();try{r.releasePointerCapture(e.pointerId)}catch{}let s=a.getSouthWest(),c=a.getNorthEast();s.lat!==c.lat&&s.lng!==c.lng&&n({minLat:jC(s.lat),minLon:jC(s.lng),maxLat:jC(c.lat),maxLon:jC(c.lng)}),g(`idle`)};r.addEventListener(`pointerdown`,s),r.addEventListener(`pointermove`,m),r.addEventListener(`pointerup`,h),r.addEventListener(`pointercancel`,h);let _=e=>{y.current===`polygon`&&(p.current=[...p.current,e.latlng],v(p.current.length),S())};t.on(`click`,_);let b=new ResizeObserver(()=>t.invalidateSize());b.observe(e);let x=window.setTimeout(()=>t.invalidateSize(),120);return()=>{r.removeEventListener(`pointerdown`,s),r.removeEventListener(`pointermove`,m),r.removeEventListener(`pointerup`,h),r.removeEventListener(`pointercancel`,h),t.off(`click`,_),b.disconnect(),window.clearTimeout(x),t.remove(),l.current=null,u.current=null,f.current=null,d.current=null}},[t,n,S]),(0,Q.useEffect)(()=>{y.current=h;let e=l.current;if(!e)return;let t=e.getContainer();h!==`polygon`&&p.current.length&&C(),h===`rect`?(e.dragging.disable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=`none`):h===`polygon`?(e.dragging.enable(),e.doubleClickZoom.disable(),t.style.cursor=`crosshair`,t.style.touchAction=``):(e.dragging.enable(),e.doubleClickZoom.enable(),t.style.cursor=``,t.style.touchAction=``)},[h,C]),(0,Q.useEffect)(()=>{let e=l.current,t=c.current;if(!e||!t)return;let n=new ResizeObserver(()=>e.invalidateSize());return n.observe(t),()=>n.disconnect()},[]),(0,Q.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=Py(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||Iy(t.lat,t.lon,i),c=ag.default.marker([t.lat,t.lon],{icon:LC(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(NC(Yr(e).title),{direction:`top`,offset:[0,-14]}),c.on(`click`,()=>{y.current===`idle`&&s(e,a??``)}),o.push(c)}t.addLayers(o),!m.current&&n.length&&!i&&(m.current=!0,e.fitBounds(ag.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,Q.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=ag.default.layerGroup();o&&ag.default.rectangle(ag.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),kC).addTo(t),i?.kind===`polygon`&&ag.default.polygon(i.points.map(e=>[e.lat,e.lon]),kC).addTo(t),t.addTo(e),d.current=t},[o,i]);let E=h===`rect`?`Drag a box on the map…`:h===`polygon`?`Tap to add points${_?` · ${_}`:``}`:o||i?`Area selected`:`Pan & pick an area`,D=`flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors`;return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:J(D,h===`rect`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Drag a rectangle to select an area`,children:[(0,$.jsx)(zn,{className:`h-3.5 w-3.5`}),`Box`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:J(D,h===`polygon`?`border-primary bg-primary/10 text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Tap points to enclose an area`,children:[(0,$.jsx)(Ee,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:w,disabled:_<3,className:J(D,`border-primary bg-primary text-primary-foreground hover:bg-primary disabled:opacity-40 disabled:hover:bg-primary`),title:`Close the polygon and filter`,children:[(0,$.jsx)(oe,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,$.jsx)(`button`,{type:`button`,onClick:C,className:J(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:T,disabled:!o&&!i&&h===`idle`,className:J(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent`),title:`Clear the area selection`,children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,$.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:E})]}),(0,$.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,$.jsx)(`div`,{ref:c,className:`absolute inset-0`}),b===0&&(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,$.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border px-3 py-2 shrink-0 text-[11px] text-muted-foreground`,children:[(0,$.jsx)(tn,{className:`h-3 w-3`}),b,` of `,r.length,` located`,i&&(0,$.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,x,` in area`]})]})]})}var zC=[{label:`25 m`,m:25},{label:`100 m`,m:100},{label:`500 m`,m:500},{label:`2 km`,m:2e3},{label:`10 km`,m:1e4}],BC=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,VC=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,HC=e=>Math.round(e*1e4)/1e4;function UC(){let{state:e,setLensGps:t,setLensIds:n}=zs(),r=e.filters.lens,i=e.activeWorkspaceName,a=r.gps?.radiusM??100,[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(r.gps?.radiusM??100),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(0),[m,h]=(0,Q.useState)(`prompt`),g=(0,Q.useRef)(null),_=(0,Q.useRef)(c);(0,Q.useEffect)(()=>{_.current=c},[c]);let v=`geolocation`in navigator&&window.isSecureContext;(0,Q.useEffect)(()=>{if(!navigator.permissions?.query)return;let e=null;return navigator.permissions.query({name:`geolocation`}).then(t=>{e=t,h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`),t.onchange=()=>h(t.state===`granted`?`granted`:t.state===`denied`?`denied`:`prompt`)}).catch(()=>{}),()=>{e&&(e.onchange=null)}},[]),(0,Q.useEffect)(()=>{if(!o||!v)return;let e=navigator.geolocation.watchPosition(e=>{let n=HC(e.coords.latitude),r=HC(e.coords.longitude);t({lat:n,lon:r,radiusM:_.current})},e=>d(e.code===e.PERMISSION_DENIED?`Location permission denied.`:e.message),{enableHighAccuracy:!0,maximumAge:15e3,timeout:2e4});return g.current=e,()=>{navigator.geolocation.clearWatch(e),g.current=null}},[o,v,f,t]);let y=e=>{s(e),d(null),e||t(null)},b=()=>{d(null),s(!0),p(e=>e+1)},x=e=>{l(e),r.gps&&t({...r.gps,radiusM:e})},S=LS(),{rateMs:C,setRateMs:w,maxDistance:T,setMaxDistance:E,error:D}=S,O=S.running&&S.consumer===`filter`,k=S.running&&S.consumer!==`filter`;RS(O);let A=t=>{i&&S.start(t,`filter`,{workspaceRef:i,contextPath:e.activeContextPath})},j=O,M=S.snapshotSize??S.camera?.size,N=!!M&&M.height>M.width;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[e.activeContextType===`context`&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Point the camera at an object to find visually related content in this context. `,e.liveEnabled?`Bound devices follow your matches as you move.`:`Enable Live to show the matches on your other devices.`]}),(0,$.jsx)(TC,{}),(0,$.jsxs)(`section`,{className:`space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,disabled:!v,onChange:e=>y(e.target.checked)}),(0,$.jsx)(fn,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`span`,{children:`Track this device’s GPS`})]}),(0,$.jsx)(`select`,{className:BC,value:c,onChange:e=>x(Number(e.target.value)),disabled:!o,children:zC.map(e=>(0,$.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?m===`denied`?(0,$.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):u?(0,$.jsxs)(`span`,{className:`text-destructive`,children:[u,` `,(0,$.jsx)(`button`,{type:`button`,onClick:b,className:`underline hover:text-foreground`,children:`Request again`})]}):r.gps?`Showing documents within ${a>=1e3?`${a/1e3} km`:`${a} m`} of ${r.gps.lat}, ${r.gps.lon}.`:o?`Waiting for a position fix…`:`Resurface documents geotagged near your current position.`:`Needs a secure context (https or localhost) with location access.`})]}),(0,$.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,$.jsxs)(`button`,{type:`button`,onClick:S.stop,className:`flex h-7 items-center gap-1 rounded-md bg-destructive px-2.5 text-xs font-medium text-destructive-foreground hover:bg-destructive/90`,children:[(0,$.jsx)(on,{className:`h-3.5 w-3.5`}),` `,S.source===`photo`?`Close photo`:`Stop ${S.source===`camera`?`camera`:`recording`}`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>A(`camera`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Ke,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>A(`screen`),disabled:!i||k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`,children:[(0,$.jsx)(Fn,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,$.jsx)(aC,{consumer:`filter`,workspaceRef:i??``,contextPath:e.activeContextPath,disabled:k,className:`flex h-7 items-center gap-1 rounded-md bg-foreground px-2.5 text-xs font-medium text-background hover:bg-foreground/90 disabled:opacity-50`}),(0,$.jsx)(`select`,{className:BC,value:C,onChange:e=>w(Number(e.target.value)),disabled:!i,title:`Frame rate. High rates (10–30 fps) are experimental; the loop never overlaps requests, so the effective rate is capped by search latency.`,children:KS.map(e=>(0,$.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,$.jsx)(`input`,{className:J(VC,`w-24`),placeholder:`max dist`,inputMode:`decimal`,value:T,onChange:e=>E(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K (loose but tunable).`})]}),(0,$.jsxs)(`div`,{className:J(`relative overflow-hidden rounded-lg border border-border bg-black/80`,j?N?`aspect-[3/4] max-h-[60vh]`:`aspect-video`:`hidden`),children:[(0,$.jsx)(ZS,{className:`h-full w-full`,interactive:!0}),(0,$.jsx)(rC,{})]}),j&&(0,$.jsx)(nC,{}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?(0,$.jsx)(`span`,{className:`text-destructive`,children:D}):j?S.snapshot?`Snapshot: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. The photo is not stored. Tap Live to resume the feed.`:`Live: view narrowed to ${S.lastCount??`…`} match${S.lastCount===1?``:`es`}. Tap the shutter to search one still frame. Frames are ephemeral, never stored. Closing the toolbox keeps it running.`:k?`The Lens applet is using the camera. Stop it there first.`:r.ids===null?i?`Point a camera (or share a screen). The view narrows to what the feed matches.`:`Open a workspace to refine with a live feed.`:`The current view holds ${r.ids.length} camera match${r.ids.length===1?``:`es`}. Save to keep this view, or clear matches to remove the camera filter.`}),!j&&r.ids!==null&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(null),className:`min-h-10 rounded-md border border-border px-3 text-xs hover:bg-muted`,children:`Clear matches`})]})]})}var WC={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function GC(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return(t%360+360)%360}function KC(e){return WC[e]??`oklch(var(--data-l) var(--data-c) ${GC(e)})`}var qC=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],JC=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],YC=[`Yesterday`,`Today`,`Tomorrow`],XC=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],ZC=10,QC=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function $C(e,t){let n=new Date;switch(e){case`millennium`:{let e=Math.floor(n.getFullYear()/1e3)*1e3;return new Date(e-t*1e3,0,1)}case`century`:{let e=Math.floor(n.getFullYear()/100)*100;return new Date(e-t*100,0,1)}case`decade`:{let e=Math.floor(n.getFullYear()/10)*10;return new Date(e-t*10,0,1)}case`year`:return new Date(n.getFullYear()-t,0,1);case`month`:return new Date(n.getFullYear(),n.getMonth()-t,1);case`week`:{let e=(n.getDay()+6)%7,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()-e);return r.setDate(r.getDate()-t*7),r}}}function ew(e,t){let n=new Date(t);switch(e){case`millennium`:n.setFullYear(n.getFullYear()+1e3);break;case`century`:n.setFullYear(n.getFullYear()+100);break;case`decade`:n.setFullYear(n.getFullYear()+10);break;case`year`:n.setFullYear(n.getFullYear()+1);break;case`month`:n.setMonth(n.getMonth()+1);break;case`week`:n.setDate(n.getDate()+7)}return n}function tw(e,t,n){if(n===0)return`Now`;switch(e){case`millennium`:case`century`:case`decade`:{let e=t.getFullYear();return e<=0?`${1-e} BCE`:`${e}`}case`year`:return`${t.getFullYear()}`;case`month`:return`${QC[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${QC[t.getMonth()]} – ${e.getDate()} ${QC[e.getMonth()]}`}}}function nw(e,t){return Array.from({length:t},(t,n)=>{let r=$C(e,n),i=ew(e,r);return{offset:n,label:tw(e,r,n),start:r,end:i,isNow:n===0}})}var rw={yesterday:5,today:5,tomorrow:5,lastWeek:5,thisWeek:5,nextWeek:5,lastMonth:4,thisMonth:4,nextMonth:4,lastYear:3,thisYear:3,nextYear:3,lastDecade:2,thisDecade:2,nextDecade:2,lastCentury:1,thisCentury:1,nextCentury:1,lastMillennium:0,thisMillennium:0,nextMillennium:0};function iw(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function aw(e,t){let n=uw(e);return n?(n.setDate(n.getDate()+t),iw(n)):e}function ow(e){let t=[...e].sort((e,t)=>e.start.localeCompare(t.start)),n=[];for(let e of t){let t=n[n.length-1];t&&e.start<=aw(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function sw(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return ow([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=aw(t,-1)&&r.push({start:n.start,end:aw(t,-1)}),aw(t,1)<=n.end&&r.push({start:aw(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function cw(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:iw(t.start),end:iw(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function lw({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=zs(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,Q.useState)(3),[d,f]=(0,Q.useState)(ZC),[p,m]=(0,Q.useState)(new Set),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)(e);e!==_&&(v(e),e&&rw[e]!==void 0&&u(rw[e]),m(new Set));let[y,b]=(0,Q.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=XC[l],S=nw(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,Q.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{qi(a,{names:r,buckets:nw(x.unit,d).map(e=>cw(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:qy(c.geo),applyCanvasSpec:!1}).then(t=>{e||g(t)}).catch(()=>{e||g([])})},250);return()=>{e=!0,clearTimeout(t)}},[a,o,s,x.unit,d,w,C]);let T=a&&r.length>0?h:[],E=Math.max(1,...T.map(e=>e.total)),D=e=>{u(t=>Math.max(0,Math.min(5,t+e))),f(ZC),m(new Set)},O=(0,Q.useCallback)((e,t)=>{m(r=>{let i;if(t&&r.size>0){let t=Math.min(e,...r),n=Math.max(e,...r);i=new Set(r);for(let e=t;e<=n;e++)i.add(e)}else i=new Set(r),i.has(e)?i.delete(e):i.add(e);let a=[...i].sort((e,t)=>e-t),o=[];for(let e of a){let t=o[o.length-1];t&&e===t[1]+1?t[1]=e:o.push([e,e])}return n(o.map(([e,t])=>{let n=S.find(e=>e.offset===t).start,r=new Date(S.find(t=>t.offset===e).end);return r.setDate(r.getDate()-1),{start:iw(n),end:iw(r)}})),i})},[S,n]);return(0,$.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,$.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom in (finer periods)`,children:(0,$.jsx)(R,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>D(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Zoom out (coarser periods)`,children:(0,$.jsx)(Te,{className:`w-3.5 h-3.5`})})]})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-1.5 space-y-1 touch-target`,children:[S.map(e=>{let t=p.has(e.offset),n=T[e.offset],r=n?.total??0,i=r>0?Math.log1p(r)/Math.log1p(E):0,a=n&&r>0?`: ${r} doc${r===1?``:`s`} (${Object.entries(n.counts).map(([e,t])=>`${e}: ${t}`).join(`, `)})`:``;return(0,$.jsxs)(`button`,{type:`button`,onClick:t=>O(e.offset,t.shiftKey),title:`${e.isNow?`Now`:e.label}${a}. Click to tag, shift-click to fill range`,className:J(`w-full flex items-center gap-2 rounded-2xl px-3 py-1.5 text-xs font-medium transition-colors select-none text-left`,t?`bg-primary text-primary-foreground`:e.isNow?`bg-primary/10 text-primary hover:bg-primary/20`:`bg-card text-foreground hover:bg-muted shadow-elevation-1`),children:[e.isNow&&(0,$.jsx)(N,{className:`w-3 h-3 shrink-0`}),(0,$.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,$.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,$.jsx)(`span`,{className:J(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,$.jsx)(`span`,{className:`mt-1 flex h-[3px] overflow-hidden rounded-full`,style:{width:`${Math.max(8,i*100)}%`},children:Object.entries(n.counts).map(([e,t])=>(0,$.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:KC(e)}},e))})]})]},e.offset)}),d<200&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+ZC),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function uw(e){let t=/^(-?\d{1,6})-(\d{2})-(\d{2})$/.exec(e);return t?new Date(Number(t[1]),Number(t[2])-1,Number(t[3])):null}function dw({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,Q.useState)(()=>{let t=e[0]?.start&&uw(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=e=>a(t=>{let n=new Date(t.y,t.m+e,1);return{y:n.getFullYear(),m:n.getMonth()}}),d=(e,r)=>{if(r){n(e),s(null),l(null);return}if(!o){s(e);return}let[i,a]=o<=e?[o,e]:[e,o];t(i,a),s(null),l(null)},f=new Date(i.y,i.m,1),p=new Date(f);p.setDate(p.getDate()-(f.getDay()+6)%7);let m=Array.from({length:42},(e,t)=>{let n=new Date(p);return n.setDate(n.getDate()+t),n}),[h,g]=o?c&&c!==o?o<=c?[o,c]:[c,o]:[o,o]:[null,null],_=t=>e.some(e=>t>=e.start&&t<=e.end),v=t=>e.some(e=>t===e.start||t===e.end),y=iw(r);return(0,$.jsxs)(`div`,{className:`select-none`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(-12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous year`,children:(0,$.jsx)(Fe,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(-1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Previous month`,children:(0,$.jsx)(E,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>a({y:r.getFullYear(),m:r.getMonth()}),className:`text-xs font-semibold text-foreground hover:text-primary transition-colors`,title:`Jump to current month`,children:[QC[i.m],` `,i.y]}),(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(1),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next month`,children:(0,$.jsx)(hr,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(12),className:`p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors`,title:`Next year`,children:(0,$.jsx)(ge,{className:`w-3.5 h-3.5`})})]})]}),(0,$.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,$.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,$.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=iw(e),n=e.getMonth()===i.m,r=h!==null&&g!==null&&t>=h&&t<=g,a=t===h||t===g,s=!o&&_(t),c=a||s&&v(t);return(0,$.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:J(`h-6 text-[11px] tabular-nums transition-colors`,c?`bg-primary text-primary-foreground rounded-md`:r||s?`bg-primary/15 text-foreground`:n?`text-foreground hover:bg-muted rounded-md`:`text-muted-foreground/40 hover:bg-muted rounded-md`,t===y&&!c&&`font-bold text-primary`),children:e.getDate()},t)})}),(0,$.jsx)(`p`,{className:`mt-1.5 text-[10px] text-muted-foreground/70`,children:o?`From ${o}: pick the end date`:`Click start + end. Ctrl+click adds/removes single days.`})]})}function fw({label:e,checked:t,onChange:n,color:r}){return(0,$.jsxs)(`div`,{role:`switch`,"aria-checked":t,tabIndex:0,onClick:()=>n(!t),onKeyDown:e=>(e.key===` `||e.key===`Enter`)&&n(!t),className:`flex items-center justify-between gap-3 cursor-pointer select-none outline-none focus-visible:ring-2 focus-visible:ring-ring rounded`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,$.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,$.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,$.jsx)(`div`,{className:J(`relative w-10 h-5 rounded-full transition-colors shrink-0`,!t&&`bg-accent dark:bg-muted-foreground`),style:t?{backgroundColor:r}:void 0,children:(0,$.jsx)(`div`,{className:J(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function pw(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=zs(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(`quick`),[_,v]=(0,Q.useState)(!1),{showToast:y}=Vr(),b=new Set(a.selectedTimelines??[]),x=(0,Q.useMemo)(()=>{let e=[];return a.indexCreated&&e.push(`crud:created`),a.indexUpdated&&e.push(`crud:updated`),a.indexDeleted&&e.push(`crud:deleted`),a.contentEvents&&e.push(`content`),e.push(...a.selectedTimelines??[]),e.length>0?e:[`crud:created`]},[a.indexCreated,a.indexUpdated,a.indexDeleted,a.contentEvents,a.selectedTimelines]),S=e=>{let n=new Set(b);n.has(e)?n.delete(e):n.add(e),t({selectedTimelines:[...n]})},C=async()=>{let e=l.trim();if(e){f(!0);try{await n(e),u(``),y({title:`Timeline created`,description:e})}catch(e){y({title:`Failed to create timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{f(!1)}}},w=async e=>{if(window.confirm(`Delete timeline "${e}"?\n\nThis removes all interval data for this timeline.`)){m(e);try{await r(e),y({title:`Timeline deleted`,description:e})}catch(e){y({title:`Failed to delete timeline`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{m(null)}}},T=o.filter(e=>!e.startsWith(`crud:`)&&e!==`content`),E=Yy(a),D=E.length>0,O=(0,Q.useCallback)(e=>{t({customRanges:e,customRange:null,...e.length>0?{quickFilter:null}:{}})},[t]),k=e=>{t({quickFilter:a.quickFilter===e?null:e,customRanges:[],customRange:null})},A=e=>{t({customRanges:E.filter((t,n)=>n!==e),customRange:null})},j=(e,t)=>(0,$.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,$.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!D;return(0,$.jsx)(`button`,{type:`button`,onClick:()=>k(e),className:J(`text-xs px-1.5 py-1 rounded-md transition-colors truncate`,r?`bg-primary text-primary-foreground font-medium`:`bg-muted/50 text-foreground hover:bg-muted`),title:e,children:t?YC[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,$.jsx)(lw,{quickFilterKey:a.quickFilter,activeRangeCount:E.length,onSelectRanges:O,histogramNames:x}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,$.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:J(`px-2 py-0.5 transition-colors`,h===`quick`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Quick filters`,children:(0,$.jsx)(H,{className:`w-3 h-3`})}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:J(`px-2 py-0.5 transition-colors`,h===`calendar`?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Calendar range picker`,children:(0,$.jsx)(B,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,$.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,$.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),qC.map((e,t)=>j(e,t===0)),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>v(e=>!e),className:`flex items-center gap-1 text-[11px] text-muted-foreground/70 hover:text-muted-foreground pt-1 transition-colors`,children:[(0,$.jsx)(Xe,{className:J(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&JC.map(e=>j(e,!1))]}):(0,$.jsx)(dw,{ranges:E,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:sw(E,e),customRange:null,quickFilter:null})}),D&&(0,$.jsx)(`div`,{className:`mt-2 space-y-1`,children:E.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded-md bg-primary/10 border border-primary/30 px-2.5 py-1.5`,children:[(0,$.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>A(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,$.jsx)(G,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(fw,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:KC(`crud:created`)}),(0,$.jsx)(fw,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:KC(`crud:updated`)}),(0,$.jsx)(fw,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:KC(`crud:deleted`)}),(0,$.jsx)(fw,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:KC(`content`)})]}),(0,$.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,$.jsx)(P,{className:`w-3 h-3`})})]}),c?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):T.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,$.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:T.map(e=>{let t=b.has(e),n=KC(e);return(0,$.jsxs)(`div`,{className:J(`flex items-center gap-2.5 group rounded-md px-2 py-1.5 cursor-pointer transition-colors`,t?`bg-muted/60`:`hover:bg-muted/30`),onClick:()=>S(e),children:[(0,$.jsx)(`div`,{className:J(`shrink-0 w-4 h-4 rounded border-2 flex items-center justify-center transition-colors`,!t&&`border-muted-foreground/40 bg-transparent group-hover:border-muted-foreground/70`),style:t?{backgroundColor:n,borderColor:n}:void 0,children:t&&(0,$.jsx)(`svg`,{className:J(`w-2.5 h-2.5`,Pm(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,$.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,$.jsx)(`span`,{className:`shrink-0 text-[10px] px-1 py-0.5 rounded bg-muted text-muted-foreground select-none`,title:`Observed granularity for "${e}" — each entry is indexed at its own precision (a bare year at year cells, a full date at day cells)`,children:(s[e]??[]).join(`·`)}),(0,$.jsx)(`button`,{type:`button`,disabled:p===e,onClick:t=>{t.stopPropagation(),w(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:`Delete timeline "${e}"`,children:p===e?(0,$.jsx)(Yn,{className:`w-3 h-3 animate-spin`}):(0,$.jsx)(nt,{className:`w-3 h-3`})})]},e)})}),(0,$.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,$.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),onKeyDown:e=>e.key===`Enter`&&C(),placeholder:`New timeline (e.g. wikipedia, trips)…`,title:`A timeline is a named time axis. Entries index at their own precision — a bare year at year granularity, a full date at day granularity — nothing to configure.`,className:`flex-1 px-2 py-1 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`}),(0,$.jsx)(`button`,{type:`button`,onClick:C,disabled:d||!l.trim(),className:`shrink-0 p-1.5 rounded-md bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 touch-target`,title:`Create timeline`,children:d?(0,$.jsx)(Yn,{className:`w-3.5 h-3.5 animate-spin`}):(0,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]})]})]})]})}var mw={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},hw=`data/dataset/default`;function gw(e){let t=new Map;for(let n of e){let e=n.startsWith(`data/backend/`)?`data/backend`:n.startsWith(`data/mime/`)?`data/mime`:n.startsWith(`data/dataset/`)?`data/dataset`:n.split(`/`)[0];t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}var _w=[`off`,`anyOf`,`allOf`,`noneOf`];function vw(e){return _w[(_w.indexOf(e)+1)%_w.length]}var yw=[{m:`anyOf`,label:`any`,on:`bg-info text-info-foreground`},{m:`allOf`,label:`all`,on:`bg-success text-success-foreground`},{m:`noneOf`,label:`not`,on:`bg-destructive text-destructive-foreground`}];function bw({mode:e,onSet:t}){return(0,$.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:yw.map(n=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:J(`px-2 py-0.5 text-[11px] font-medium transition-colors`,e===n.m?n.on:`bg-transparent text-muted-foreground hover:bg-muted hover:text-foreground`),title:`${n.label}: ${n.m}`,children:n.label},n.m))})}function xw({keys:e,modeOf:t,onCycle:n}){return e.length?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=fC(e),a=t(e),o=yw.find(e=>e.m===a);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:J(`relative flex flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border p-3 min-h-[4.5rem] transition-colors select-none`,a===`off`?`border-border bg-muted/40 text-foreground hover:bg-muted`:a===`anyOf`?`border-info bg-info/10 text-foreground`:a===`allOf`?`border-success bg-success/10 text-foreground`:`border-destructive bg-destructive/10 text-foreground`),children:[o&&(0,$.jsx)(`span`,{className:J(`absolute right-1.5 top-1.5 rounded px-1 py-0.5 text-[9px] font-semibold leading-none`,o.on),children:o.label}),(0,$.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function Sw(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=zs(),{availableBitmaps:o,bitmapsLoading:s,filters:c}=e,l=new Set(c.features.allOf),u=new Set(c.features.anyOf),d=new Set(c.features.noneOf),f=e=>l.has(e)?`allOf`:u.has(e)?`anyOf`:d.has(e)?`noneOf`:`off`,[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(null),{showToast:_}=Vr(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==hw){let t=e.slice(13);if(!window.confirm(`Drop dataset "${t}"?\n\nALL documents stamped with this dataset will be PERMANENTLY DELETED. Documents in other datasets (or the default dataset) are unaffected. Re-ingesting recreates the dataset from scratch.`))return;g(e);try{let n=await a(e);_({title:`Dataset dropped`,description:`"${t}": ${n} document(s) deleted`})}catch(e){_({title:`Dataset drop failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}return}if(!e.startsWith(`data/`)&&window.confirm(`Delete bitmap "${e}"?\n\nThis removes the bitmap from the database. Documents are unaffected, but any features/filters relying on this bitmap will lose their grouping.`)){g(e);try{await i(e),_({title:`Bitmap deleted`,description:e})}catch(e){_({title:`Delete failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{g(null)}}};if(s)return(0,$.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,$.jsx)(Yn,{className:`w-4 h-4 animate-spin text-muted-foreground`})});let y=[...c.features.allOf,...c.features.anyOf,...c.features.noneOf],b=[...new Set([...o,...y])];if(!b.length)return(0,$.jsx)(`div`,{className:`p-4 text-xs text-muted-foreground text-center py-10`,children:`No feature bitmaps found`});let x=p.trim().toLowerCase(),S=x?b.filter(e=>e.toLowerCase().includes(x)):b,C=S.filter(e=>e.startsWith(uC)).sort((e,t)=>{let n=Object.keys(dC),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=gw(S.filter(e=>!e.startsWith(uC))),T=w.get(`data/dataset`);return T&&!T.includes(hw)&&(!x||hw.includes(x))&&T.unshift(hw),(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(tr,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,$.jsx)(`input`,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:`Search features…`,className:`w-full pl-7 pr-3 py-1.5 text-xs rounded-md bg-muted border border-transparent focus:border-ring focus:outline-none`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:n,disabled:!r,className:`flex items-center gap-1.5 w-full justify-center px-2.5 py-1.5 text-xs rounded-md border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-40 disabled:hover:bg-transparent`,children:[(0,$.jsx)(G,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,$.jsx)(xw,{keys:C,modeOf:f,onCycle:e=>t(e,vw(f(e)))}),w.size===0&&C.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:mw[e]??e}),(0,$.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===hw,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,$.jsxs)(`div`,{onClick:()=>t(e,vw(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,vw(o)))},className:J(`flex items-center gap-2 group rounded-md pl-2 pr-1.5 py-1 border-l-2 transition-colors cursor-pointer select-none`,n%2==0?`bg-muted/50`:`bg-transparent`,`hover:bg-muted`,o===`off`?`border-l-transparent`:o===`anyOf`?`border-l-blue-500 !bg-info/10`:o===`allOf`?`border-l-emerald-500 !bg-success/10`:`border-l-rose-500 !bg-destructive/10`),children:[(0,$.jsxs)(`span`,{className:`flex-1 min-w-0 text-xs font-mono text-foreground truncate`,title:i?`Virtual dataset: documents not stamped with any dataset. Included by default; "not" hides them, "all" shows only them.`:e,children:[e,i&&(0,$.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,$.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,$.jsx)(bw,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,$.jsx)(`button`,{type:`button`,disabled:h===e,onClick:t=>{t.stopPropagation(),v(e)},className:`shrink-0 p-1 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50 reveal-on-hover`,title:a?`Drop dataset "${e.slice(13)}" (DELETES its documents)`:`Delete bitmap "${e}" from database`,"aria-label":a?`Drop dataset ${e}`:`Delete bitmap ${e}`,children:h===e?(0,$.jsx)(Yn,{className:`w-3.5 h-3.5 animate-spin`}):(0,$.jsx)(nt,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function Cw(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i,setLiveEnabled:a}=zs(),{toolsTab:o,isDirty:s,isSaving:c,activeContextType:l,savedSearchQuery:u}=e,d=pl(),f=(new URLSearchParams(d.search).has(`q`)||new URLSearchParams(d.search).has(`search`)?wC(d.search):u?[u]:[])[0]||``,p=l!==null&&f.trim()!==(u||``),m=e.filters.sort??Ky.sort,h=m.sortBy!==Ky.sort.sortBy||m.order!==Ky.sort.order,g=i||!!f.trim()||h,_=(0,$.jsxs)($.Fragment,{children:[g&&(0,$.jsxs)(`button`,{type:`button`,onClick:r,title:`Clear all active filters`,className:`flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(G,{className:`h-3 w-3`}),`Clear`]}),l!==null&&g&&(s||p)&&(0,$.jsxs)(`button`,{type:`button`,onClick:n,disabled:c,className:`flex items-center gap-1.5 rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary disabled:opacity-60`,children:[c?(0,$.jsx)(Yn,{className:`h-3 w-3 animate-spin`}):(0,$.jsx)(Be,{className:`h-3 w-3`}),`Save filters`]})]});return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex border-b border-border shrink-0`,children:[{id:`features`,label:`Features`},{id:`timeline`,label:`Timeline`},{id:`map`,label:`Map`},{id:`lens`,label:`Lens`}].map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:J(`flex-1 py-2.5 text-xs transition-colors`,o===e.id?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e.label},e.id))}),l===`context`&&(0,$.jsxs)(`div`,{className:`shrink-0 space-y-1 border-b border-border px-3 py-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex min-h-8 flex-wrap items-center justify-between gap-x-3 gap-y-1`,children:[(0,$.jsxs)(`label`,{className:`flex min-h-8 cursor-pointer items-center gap-2 text-sm font-medium`,title:`Live view updates every device bound to this context. Save filters to keep the current view.`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 accent-current`,checked:e.liveEnabled,disabled:new URLSearchParams(d.search).has(`ownerId`),onChange:e=>{a(e.target.checked)}}),`Live view`]}),(0,$.jsx)(`div`,{className:`ml-auto flex items-center gap-2`,children:_})]}),e.liveError&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-destructive`,children:e.liveError})]}),l!==`context`&&g&&(0,$.jsx)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:_}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[o===`features`&&(0,$.jsx)(Sw,{}),o===`timeline`&&(0,$.jsx)(pw,{}),o===`map`&&(0,$.jsx)(RC,{}),o===`lens`&&(0,$.jsx)(UC,{})]})]})}function ww(){let e=xS(),t=es()?.state,n=!!t&&(e?.mode===`context`?t.activeContextType===`context`&&t.activeContextId===e.contextId:e?.mode===`workspace`?t.activeContextType!==`context`&&t.activeWorkspaceName===e.workspaceName&&t.activeTreeName===e.treeName&&t.activeContextPath===e.path:!t.activeWorkspaceName&&!t.activeContextId),r=!n&&e?.mode===`context`?e.contextId:null;return(0,Q.useEffect)(()=>{if(!r)return;let e=`context:${r}`,t=()=>hd.emit(`subscribe`,{channel:e}),n=hd.on(`connect`,t);return t(),()=>{n(),hd.emit(`unsubscribe`,{channel:e})}},[r]),n?(0,$.jsx)(Cw,{}):(0,$.jsx)(CC,{target:e,children:(0,$.jsx)(QS,{children:(0,$.jsx)(Cw,{})})})}function Tw({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=__(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,$.jsxs)(`div`,{className:`group relative overflow-hidden rounded-(--card-radius) border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,$.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,$.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,$.jsx)(le,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,$.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:ES(e.updatedAt||e.createdAt)})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Delete ${o}`,className:`absolute right-1.5 top-1.5 rounded-md bg-background/80 p-1 opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})}function Ew({autoAdd:e}){let t=xS(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=DS(t,Mi),[c,l]=(0,Q.useState)(e?`new`:null),{showErrorToast:u}=Wr();return t?(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,$.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,$.jsx)(Tw,{doc:e,scope:a,onOpen:()=>l(e),onRemove:()=>{confirm(`Delete "${String(e.data?.title??`Sketch`)}"?`)&&s(e.id).catch(e=>u(e instanceof Error?e.message:`Failed to delete sketch`))}},`${e.id}:${e.checksumArray?.[0]??``}`))}),c&&a&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,$.jsx)(by,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var Dw=[{id:`filters`,label:`Filters`,icon:Un,modes:[`context`,`global`],description:`Search and filter a workspace or a live context`,Component:ww},{id:`notes`,label:`Notes`,icon:Kn,modes:[`context`],description:`All notes in the current context, editable in place`,Component:AS},{id:`todo`,label:`Todos`,icon:Vt,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:FS},{id:`sketch`,label:`Sketch`,icon:le,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:Ew},{id:`lens`,label:`Lens`,icon:cr,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:lC}];function Ow(e){return Dw.filter(t=>t.modes.includes(e))}function kw({target:e,children:t}){return(0,$.jsx)(bS.Provider,{value:e,children:t})}function Aw({children:e}){let[t,n]=(0,Q.useState)(null),r=(0,Q.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,Q.useCallback)(()=>n(null),[]),a=(0,Q.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,$.jsxs)(dy.Provider,{value:a,children:[e,(0,$.jsx)(Hy,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var jw=`universe`;function Mw(){let{appletId:e}=bl(),[t,n]=zu(),r=Dw.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||jw,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,Q.useMemo)(()=>i?{mode:`context`,contextId:i}:{mode:`workspace`,workspaceName:a,path:o,treeName:s,treeType:s===`directory`?`directory`:`context`},[i,a,o,s]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{Ni().then(d).catch(()=>d([])),ps().then(p).catch(()=>p([]))},[]);let[m,h]=(0,Q.useState)(o),[g,_]=(0,Q.useState)(o);g!==o&&(_(o),h(o));let v=e=>{let r=new URLSearchParams(t);r.delete(`add`);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r,{replace:!0})};if(!r)return(0,$.jsxs)(`div`,{className:`flex h-viewport flex-col items-center justify-center gap-3 surface-desk`,children:[(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,$.jsx)(`div`,{className:`flex gap-2`,children:Dw.map(e=>(0,$.jsx)(Nu,{to:`/apps/${e.id}`,className:`rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted`,children:e.label},e.id))})]});let y=i?`context`:`path`;return(0,$.jsx)(Aw,{children:(0,$.jsx)(QS,{children:(0,$.jsxs)(`div`,{className:`flex h-viewport flex-col surface-desk p-shell gap-shell`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 rounded-xl border bg-card px-3 py-2 shadow-elevation-2`,children:[(0,$.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,$.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:J(`px-2.5 py-1 text-xs capitalize transition-colors`,y===e?`bg-foreground text-background`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:e},e))}),y===`path`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`select`,{value:a,onChange:e=>v({workspace:e.target.value,path:`/`}),className:`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Workspace`,children:[!u.some(e=>e.name===a)&&(0,$.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,$.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,$.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),onBlur:()=>{let e=m.trim()||`/`;e!==o&&v({path:e})},onKeyDown:e=>{e.key===`Enter`&&e.target.blur()},spellCheck:!1,placeholder:`/`,className:`h-7 w-40 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,"aria-label":`Path`})]}):(0,$.jsxs)(`select`,{value:i??``,onChange:e=>v({context:e.target.value}),className:`h-7 max-w-56 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Context`,children:[!i&&(0,$.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,$.jsx)(`div`,{className:`grow`}),(0,$.jsx)(Nu,{to:`/home`,className:`flex items-center gap-1 rounded-md p-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Open the full Canvas app`,children:(0,$.jsx)(ve,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-elevation-2`,children:y===`context`&&!i?(0,$.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:[`Pick a context above to bind `,r.label,` to it.`]}):(0,$.jsx)(kw,{target:l,children:(0,$.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})})})}var Nw=`false`,Pw=`false`,Fw=Nw===`true`,Iw=Pw===`true`;function Lw(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,Fw||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await g(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!Iw){if(Fw)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 Rw=new Set,zw=!1,Bw=Lw({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){zw=!0,Rw.forEach(e=>e())}});function Vw(e){return Rw.add(e),zw&&e(),()=>{Rw.delete(e)}}function Hw(){Bw(!0)}function Uw(){let[e,t]=(0,Q.useState)(!1),[n,r]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>Vw(()=>t(!0)),[]),!e||n?null:(0,$.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,$.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>Hw(),className:`flex items-center gap-1 rounded-full bg-foreground px-3 py-1 text-xs font-medium text-background hover:bg-foreground/90`,children:[(0,$.jsx)(P,{className:`h-3 w-3`}),` Reload`]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(!0),"aria-label":`Not now`,className:`rounded-full p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})})}var Ww;function Gw(){let[e,t]=(0,Q.useState)({local:!1});return(0,Q.useEffect)(()=>{Ww??=fetch(`${Lr}/runtime/capabilities`).then(async e=>e.ok?(await e.json()).payload:{local:!1}).catch(()=>({local:!1}));let e=!0;return Ww.then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Kw(e){return e.isShared||e.type===`shared`?e.id:e.name}function qw({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=gl();return(0,$.jsxs)(`div`,{className:J(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,$.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>i?i():s(r),"aria-label":`Back`,title:`Back`,className:`mt-1 shrink-0 text-muted-foreground transition-colors hover:text-foreground touch-target`,children:(0,$.jsx)(Jn,{className:`h-5 w-5`})}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`h1`,{className:J(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,$.jsx)(`p`,{className:J(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(`/`),"aria-label":`Close`,title:`Close`,className:`order-2 flex h-9 w-9 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-4 w-4`})}),n&&(0,$.jsx)(`div`,{className:`order-3 flex w-full items-center gap-2 max-sm:flex-wrap sm:order-1 sm:w-auto`,children:n})]})}function Jw({className:e}){let t=gl();return(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:J(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,e),children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})}function Yw({onBack:e,title:t=`Back`,className:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:J(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,n),children:(0,$.jsx)(Jn,{className:`h-4 w-4`})})}var Xw=180;function Zw({x:e,y:t,current:n,onChange:r,onClose:i}){Fp(i);let[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)({q:``,list:[]}),[d,p]=(0,Q.useState)(!0),m=(0,Q.useRef)(null),h=(0,Q.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&i(),h.current={name:e,t}};(0,Q.useEffect)(()=>{m.current?.focus()},[]),(0,Q.useEffect)(()=>{let e=!0;return gm().then(t=>{e&&(c(t),p(!1))}),()=>{e=!1}},[]),(0,Q.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{_m(e).then(t=>{u({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=l.q===_,y=_!==``&&!v,b=(0,Q.useMemo)(()=>(_?v?l.list:[]:s).slice(0,Xw),[_,v,l.list,s]),x=(0,Q.useRef)(null),[S,C]=(0,Q.useState)({x:e,y:t});return(0,Q.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,Ip.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,$.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,$.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,$.jsx)(G,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[vm.map(e=>(0,$.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:J(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,$.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:J(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,$.jsx)(G,{className:`w-3 h-3`})}),(0,$.jsx)(`label`,{title:`Custom color`,className:J(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!vm.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!vm.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,$.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,$.jsx)(`input`,{ref:m,value:a,onChange:e=>o(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),d||y?(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,$.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,$.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:J(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,$.jsx)(G,{className:`w-4 h-4`})}),b.map(e=>(0,$.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:J(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,$.jsx)(f,{icon:e,width:18,height:18,color:n.color})},e))]}),!d&&!y&&b.length===0&&(0,$.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function Qw(e,t,n){let r=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{r.current=n}),(0,Q.useEffect)(()=>{if(!e)return;e.emit(`subscribe`,{channel:t});let n=Object.keys(r.current).map(t=>{let n=(...e)=>{r.current[t]?.(...e)};return e.on(t,n),[t,n]});return()=>{e.emit(`unsubscribe`,{channel:t});for(let[t,r]of n)e.off(t,r)}},[e,t])}function $w({title:e,onClose:t,children:n}){return(0,$.jsxs)(`div`,{className:`space-y-4 rounded-(--card-radius) border bg-card p-4 shadow-elevation-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),n]})}function eT({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,Q.useState)(!1),l=e.status===`active`,u=e.type===`universe`||e.name===`universe`,d=e.status===`error`,f=e.status===`not_found`,p=e.isShared===!0||e.type===`shared`,m=e.ownerEmail||e.owner,h=typeof e.sharedVia==`object`&&e.sharedVia?e.sharedVia:null,g=h?.permissions||[],_=g.includes(`admin`)?`admin`:g.includes(`write`)?`read/write`:`read-only`,v=h?.type===`group`?`via group ${h.principal}`:h?.type===`user`?`shared with you`:``,y=e.origin===`remote`,b=e.status===`offline`,x=Nm(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(Ku,{className:`relative ${S}`,style:C,children:[(0,$.jsx)(qu,{children:(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,$.jsx)(Ju,{className:`truncate`,children:e.label||e.name}),(0,$.jsx)(Yu,{children:p?`Shared from ${m}`:e.description||``})]}),(0,$.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>n(Kw(e)),title:`Stop Workspace`,disabled:d||f,children:(0,$.jsx)(zn,{className:`h-4 w-4`})}):(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>t(Kw(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,$.jsx)(xe,{className:`h-4 w-4`})}),l&&(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>r(Kw(e)),title:`Enter Workspace`,disabled:d||f,children:(0,$.jsx)(_t,{className:`h-4 w-4`})}),a&&(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:Op(e)?`Workspace settings`:`Workspace settings require admin access`,"aria-label":`Workspace settings`,disabled:f||!Op(e),children:(0,$.jsx)(yn,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,$.jsx)(Z,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,$.jsx)(rn,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,$.jsxs)(Ir,{open:s,onOpenChange:c,children:[(0,$.jsx)(kr,{asChild:!0,children:(0,$.jsx)(Z,{variant:`outline`,size:`icon`,title:y?`Remove remote workspace reference`:`Delete Workspace`,disabled:l&&!y,className:`text-destructive hover:text-destructive hover:bg-destructive/10`,children:(0,$.jsx)(nt,{className:`h-4 w-4`})})}),(0,$.jsxs)(Or,{children:[(0,$.jsxs)(Fr,{children:[(0,$.jsx)(Cr,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,$.jsx)(Sr,{children:y?(0,$.jsxs)($.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,$.jsx)(`br`,{}),(0,$.jsx)(`br`,{}),`The workspace itself stays untouched on `,e.remote?.url||e.host,`; only the stored share token and the local cache entry are dropped.`]}):(0,$.jsxs)($.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,$.jsx)(`br`,{}),(0,$.jsx)(`br`,{}),(0,$.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,$.jsxs)(Mr,{children:[(0,$.jsx)(Pr,{children:`Cancel`}),(0,$.jsx)(jr,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,$.jsx)(Xu,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`div`,{className:`h-3 w-3 rounded-full ${(()=>{switch(e.status){case`active`:return`bg-success`;case`inactive`:case`available`:return`bg-muted-foreground`;case`error`:case`offline`:return`bg-destructive`;case`not_found`:return`bg-muted-foreground`;default:return`bg-accent`}})()}`}),(0,$.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:(()=>{switch(e.status){case`active`:return`Active`;case`inactive`:return`Inactive`;case`error`:return`Error`;case`not_found`:return`Not Found`;case`available`:return`Available`;case`removed`:return`Removed`;case`destroyed`:return`Destroyed`;case`offline`:return`Offline`;default:return e.status}})()}),u&&(0,$.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,$.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:e.remote?.url?`${e.remote.url} (${(e.remote.permissions||[]).join(`, `)||`no permissions`})`:void 0,children:[`Remote · `,e.host]}),p&&(0,$.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:[v,`${_} access`].filter(Boolean).join(` · `),children:[`Shared · `,_]})]})})]})})}function tT(){let[e,t]=zu(),n=e.get(`create`)===`1`,[r,i]=(0,Q.useState)(n),[a,o]=(0,Q.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,Q.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var nT=`canvas:lastPath`,rT=200;function iT(){try{let e=localStorage.getItem(nT);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function aT(e){try{localStorage.setItem(nT,JSON.stringify(e))}catch{}}function oT(e,t,n){if(!e)return;let r=iT(),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>rT)for(let e of a.slice(0,a.length-rT))delete r[e];aT(r)}function sT(e){let t=iT()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function cT(e){let t=sT(e);return t?Fx(e,t.path,t.tree):`/workspaces/${e}`}var lT=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:V,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:or,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:mr,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:Re,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:Fn,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:Dn,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:jn,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:ie,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:mn,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/auth`,icon:k,label:`Authentication`,description:`Configure sign-in backends: local passwords, LDAP and IMAP.`},{path:`/admin/embedding`,icon:Dn,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:fr,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:ur,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:rt,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:ct,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:F,label:`About Canvas`,description:`View versions and information about this installation.`}]}],uT=[`/settings`,...lT.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function dT(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var fT=[{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.`}],pT=`canvas:layout`;function mT(){try{return localStorage.getItem(pT)===`strip`?`strip`:`classic`}catch{return`classic`}}var hT=mT(),gT=new Set;function _T(){for(let e of gT)e()}function vT(){return hT}function yT(e){try{e===`strip`?localStorage.setItem(pT,e):localStorage.removeItem(pT)}catch{}hT=e,_T()}function bT(e){gT.add(e);let t=t=>{(t.key===pT||t.key===null)&&(hT=mT(),e())};return window.addEventListener(`storage`,t),()=>{gT.delete(e),window.removeEventListener(`storage`,t)}}function xT(){return(0,Q.useSyncExternalStore)(bT,vT,()=>`classic`)}var ST=[{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.`}],CT=`canvas:layout-nav`;function wT(){try{let e=localStorage.getItem(CT);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var TT=wT(),ET=new Set;function DT(){return TT}function OT(e){try{e===`shift`?localStorage.removeItem(CT):localStorage.setItem(CT,e)}catch{}TT=e;for(let e of ET)e()}function kT(e){ET.add(e);let t=t=>{(t.key===CT||t.key===null)&&(TT=wT(),e())};return window.addEventListener(`storage`,t),()=>{ET.delete(e),window.removeEventListener(`storage`,t)}}function AT(){return(0,Q.useSyncExternalStore)(kT,DT,()=>`shift`)}function jT(e,t){let n=e.ctrlKey||e.metaKey;switch(t){case`shift`:return e.shiftKey&&!e.altKey&&!n;case`alt`:return e.altKey&&!e.shiftKey&&!n;case`ctrl`:return n&&!e.shiftKey&&!e.altKey;case`none`:return!e.shiftKey&&!e.altKey&&!n}}function MT(){return window.matchMedia(`(max-width: 767px)`).matches&&vT()!==`strip`}var NT=(0,Q.createContext)(null);function PT(){let e=(0,Q.useContext)(NT);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function FT(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`||uT.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function IT(e,t){let n=pl(),r=gl(),i=(0,Q.useRef)(!1),a=(0,Q.useRef)(e);return(0,Q.useEffect)(()=>{a.current=e},[e]),(0,Q.useLayoutEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=FT(n.pathname);if(e===null&&n.pathname!==`/`&&vT()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=MT(),c=s?n.state?.canvasMenu:void 0;t(c?{type:`RESTORE_MENU`,menu:c}:{type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,n.state,t]),{navigateToEntity:(0,Q.useCallback)(e=>{i.current=!0,r(e)},[r])}}function LT(){let[e,t]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=zr(xr.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 RT=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function zT(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await Aa(e,`/${n}`,!0,a);let t=Tm(`/${n}`);t&&await zi(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return Da(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function BT(){let[e,t]=(0,Q.useState)(new Set),[n,r]=(0,Q.useState)(`context`);return{selected:e,setSelected:t,tree:n,setTree:r,toggle:e=>{t(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}}}function VT({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,$.jsx)(`div`,{className:`mt-3 grid gap-1.5 ${o?`grid-cols-1`:`grid-cols-2 sm:grid-cols-3 md:grid-cols-4`}`,children:RT.map(n=>{let r=ym[n.toLowerCase()];return(0,$.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded border px-2 py-1.5 text-sm hover:bg-accent/50`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,$.jsx)(f,{icon:r.icon,width:16,height:16,color:r.color}),(0,$.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var HT=[{value:`full`,icon:ne,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:Pe,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 UT({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,$.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:HT.map(i=>{let a=e===i.value,o=i.icon;return(0,$.jsxs)(`button`,{id:`${r}-${i.value}`,type:`button`,role:`radio`,"aria-checked":a,disabled:n,onClick:()=>t(i.value),className:`flex w-full gap-2 rounded-md border p-2.5 text-left transition-colors disabled:opacity-50 ${a?`border-primary bg-accent/40`:`hover:bg-accent/20`}`,children:[(0,$.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,$.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,$.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,$.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function WT(){let[e,t]=(0,Q.useState)(`full`),[n,r]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{let e=!0;return X.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 GT({disabled:e}){let[t,n]=(0,Q.useState)(0),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),d=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=!0;return d.current?.id!==t&&(d.current={id:t,promise:Ma()}),d.current.promise.then(t=>{if(!e)return;let n=[...t.discovered,...t.adopted];o(e=>[...new Map([...e,...n].map(e=>[e.id,e])).values()]),c(t)}).catch(t=>{e&&u(t instanceof Error?t.message:`Workspace scan failed`)}).finally(()=>{e&&i(!1)}),()=>{e=!1}},[t]),(0,$.jsxs)(`section`,{className:`space-y-2 rounded-md border p-3`,"aria-label":`Find workspace folders`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`text-sm font-medium`,children:`Workspaces folder`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copied a workspace folder here? Scan to add it to your workspaces.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:e||r,onClick:()=>{i(!0),u(``),n(e=>e+1)},children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${r?`animate-spin`:``}`}),r?`Scanning…`:`Rescan`]})]}),r&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Looking for workspace folders…`}),!r&&!l&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:a.length?`Found ${a.length} ${a.length===1?`workspace`:`workspaces`}. Added to your workspace list.`:`No new workspace folders found.`}),a.length>0&&(0,$.jsx)(`ul`,{className:`space-y-2`,children:a.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(Nu,{className:`text-sm font-medium underline underline-offset-2`,to:`/workspaces/${encodeURIComponent(e.name)}`,children:e.label||e.name}),(0,$.jsx)(`p`,{className:`break-all text-xs text-muted-foreground`,children:e.dir})]},e.id))}),l&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:l}),!!s?.skipped.length&&(0,$.jsxs)(`details`,{className:`text-sm text-muted-foreground`,children:[(0,$.jsxs)(`summary`,{children:[s.skipped.length,` `,s.skipped.length===1?`folder could`:`folders could`,` not be added`]}),(0,$.jsx)(`ul`,{className:`mt-1 space-y-1`,children:s.skipped.map(e=>(0,$.jsxs)(`li`,{className:`break-all`,children:[e.dir,`: `,e.reason]},e.dir))})]})]})}function KT({name:e,label:t,setName:n,setLabel:r,disabled:i=!1}){return(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace name`,(0,$.jsx)(Y,{required:!0,pattern:`[a-zA-Z0-9]([a-zA-Z0-9_]|-)*`,placeholder:`my-workspace`,value:e,onChange:e=>n(e.target.value),disabled:i}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Used in addresses. Archive imports also use it as the folder name.`})]}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Display label`,(0,$.jsx)(Y,{required:!0,placeholder:`My Workspace`,value:t,onChange:e=>r(e.target.value),disabled:i})]})]})}function qT({onImported:e,disabled:t=!1}){let[n,r]=(0,Q.useState)(`upload`),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(null),b=t||f,x=async t=>{t.preventDefault(),p(!0),_(``),y(null),h(`Starting…`);let r={name:c.trim(),label:u.trim()},a=e=>h(Ka[e.phase]||e.phase);try{let t=n===`upload`?await wa(i,e=>h(e<1?`Uploading… ${Math.round(e*100)}%`:`Extracting…`),a,r):await eo(o.trim(),r,a);y(t),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e?.(t)}catch(e){_(e instanceof Error?e.message:`Workspace import failed`)}finally{p(!1)}};return(0,$.jsxs)(`form`,{className:`space-y-3`,onSubmit:e=>void x(e),children:[(0,$.jsx)(GT,{disabled:b}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Import from`,(0,$.jsxs)(`select`,{value:n,disabled:b,onChange:e=>r(e.target.value),className:`rounded-md border bg-background p-2`,children:[(0,$.jsx)(`option`,{value:`upload`,children:`Upload an archive`}),(0,$.jsx)(`option`,{value:`path`,children:`Path on this server`})]})]}),n===`upload`?(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace archive`,(0,$.jsx)(Y,{required:!0,type:`file`,accept:`.tar.gz,.tgz,.tar.bz2,.tbz2,.tbz`,disabled:b,onChange:e=>a(e.target.files?.[0]||null)})]}):(0,$.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Server path`,(0,$.jsx)(Y,{required:!0,placeholder:`/tmp/workspace.tar.gz`,value:o,disabled:b,onChange:e=>s(e.target.value)}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`An archive or workspace folder on the server. Archives are extracted into your Workspaces directory.`})]}),(0,$.jsx)(KT,{name:c,label:u,setName:l,setLabel:d,disabled:b}),(0,$.jsxs)(Z,{type:`submit`,disabled:b||!c.trim()||!u.trim()||(n===`upload`?!i:!o.trim()),children:[f?(0,$.jsx)(P,{className:`mr-2 h-4 w-4 animate-spin`}):(0,$.jsx)(Qe,{className:`mr-2 h-4 w-4`}),f?`Importing…`:`Import workspace`]}),f&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:m}),g&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),v&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Imported `,v.label||v.name,`.`]})]})}function JT(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 YT(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function XT(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 ZT(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function QT(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(Am()),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(``),[_,v]=WT(),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),E=Gw(),[D,O]=tT(),k=BT(),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(!1),[R,z]=(0,Q.useState)(null),{showToast:ee}=Vr(),te=gl(),ne=l_(),{openM2Drawer:B}=PT(),re=LT();Qw(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)),"workspaces.scanned":({report:e})=>{!e.discovered.length&&!e.adopted.length&&!e.updated.length&&!e.missing.length||Ni().then(e=>t(JT(e))).catch(()=>{})}}),(0,Q.useEffect)(()=>{let e=async()=>{try{r(!0);let e=await Ni();t(JT(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),ee({title:`Error`,description:t,variant:`destructive`})}finally{r(!1)}};e();let n=()=>{e()};return window.addEventListener(`workspaces:refresh`,n),()=>{window.removeEventListener(`workspaces:refresh`,n)}},[re,ee]);let ie=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await da({name:o,description:c||void 0,color:u,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),k.selected.size>0){try{await so(e.name);let{ok:t,failed:n}=await zT(e.name,Array.from(k.selected),k.tree);n&&ee({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),ee({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}k.setSelected(new Set)}s(``),l(``),d(Am()),m(null),g(``),ee({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),O(!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`}ee({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},ae=async e=>{if(e.preventDefault(),R)try{let e={label:R.label,description:R.description,color:R.color,icon:R.icon??null};await Eo(R.name,e),t(t=>t.map(t=>t.id===R.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),ee({title:`Success`,description:`Workspace '${R.label}' details updated.`}),z(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;ee({title:`Error`,description:t,variant:`destructive`})}},oe=e=>{z(e)},V=async e=>{try{await no(e.name),t(t=>t.filter(t=>t.id!==e.id)),ee({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;ee({title:`Error`,description:t,variant:`destructive`})}},H=async e=>{try{let n=await so(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),ee({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`}ee({title:`Error`,description:t,variant:`destructive`})}},U=async e=>{try{let n=await ha(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),ee({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`}ee({title:`Error`,description:t,variant:`destructive`})}},se=e=>{te(cT(e))},{rowProps:W,handleProps:ce,draggingIndex:le,insertLineClass:ue}=ZT((n,r)=>{let i=YT(e,n,r);t(i),XT(i,(e,t)=>Eo(Kw(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&ee({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{variant:`outline`,onClick:()=>j(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>F(e=>!e),children:`Import workspace`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>N(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>L(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!E.local&&!D&&(0,$.jsxs)(Z,{onClick:()=>O(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,$.jsx)(sn,{className:`h-4 w-4 sm:mr-2`}),(0,$.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),!E.local&&D&&(0,$.jsx)($w,{title:`Create New Workspace`,onClose:()=>O(!1),children:(0,$.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,$.jsx)(Y,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,disabled:C,onClick:e=>b({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:p||`ph:stack-fill`,width:22,height:22,color:Nm(u)})}),(0,$.jsx)(Y,{id:`workspace-color`,type:`color`,value:u,onChange:e=>d(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>d(Am()),disabled:C,children:`Randomize`})]}),y&&(0,$.jsx)(Zw,{x:y.x,y:y.y,current:{icon:p??void 0,color:u},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&d(e.color)},onClose:()=>b(null)}),(0,$.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,$.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`How the workspace directory is laid out on disk. Fixed once created.`}),(0,$.jsx)(UT,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,$.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,$.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,$.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`Ticked folders are created right after the workspace, with matching icons and colors.`}),(0,$.jsx)(VT,{selected:k.selected,onToggle:k.toggle,tree:k.tree,onTreeChange:k.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,$.jsxs)(Z,{type:`submit`,disabled:C||!o.trim(),children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),A&&(0,$.jsx)(eE,{}),I&&(0,$.jsx)(tE,{onClose:()=>L(!1),onChanged:async()=>{try{t(JT(await Ni()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),P&&(0,$.jsx)($w,{title:`Import workspace`,onClose:()=>F(!1),children:(0,$.jsx)(qT,{onImported:()=>F(!1)})}),M&&(0,$.jsx)($T,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),N(!1)},onClose:()=>N(!1)}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,$.jsx)(`div`,{className:`text-center text-destructive`,children:(0,$.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,$.jsx)(`div`,{className:`grid gap-4`,children:e.map((t,n)=>{let r={...t,createdAt:t.createdAt,updatedAt:t.updatedAt,color:t.color===null?void 0:t.color},i=Nm(t.color);return(0,$.jsxs)(`div`,{...W(n),className:`flex items-stretch rounded-lg ${ue(n,e.length)||``} ${le===n?`opacity-60`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,...ce(n),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:`hidden w-5 shrink-0 cursor-grab items-center justify-center rounded-l-lg active:cursor-grabbing md:flex ${i?``:`bg-muted`}`,style:i?{backgroundColor:i}:void 0,children:(0,$.jsx)(T,{className:`h-4 w-4 ${Pm(i)}`})}),(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,$.jsx)(eT,{workspace:r,onStart:H,onStop:U,onEnter:se,onEdit:oe,onSettings:e=>{ne?B(`workspaces`,`settings`,Kw(e)):te(`/workspaces/${Kw(e)}/settings/general`)},onDestroy:V})})]},t.id)})})]}),R&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,R.label]}),(0,$.jsxs)(`form`,{onSubmit:ae,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,$.jsx)(Y,{id:`edit-label`,value:R.label,onChange:e=>z(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`edit-description`,value:R.description||``,onChange:e=>z(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>S({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:R.icon||`ph:stack-fill`,width:22,height:22,color:Nm(R.color)})}),(0,$.jsx)(Y,{id:`edit-workspace-color`,type:`color`,value:R.color||`#FFFFFF`,onChange:e=>z(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>z(e=>e?{...e,color:Am()}:null),children:`Randomize Color`})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:!R.label?.trim(),children:`Save Changes`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>z(null),children:`Cancel`})]})]}),x&&(0,$.jsx)(Zw,{x:x.x,y:x.y,current:{icon:R.icon??void 0,color:R.color??void 0},onChange:e=>{z(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 $T({onImported:e,onClose:t}){let{showToast:n}=Vr(),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(``);return(0,$.jsx)($w,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,$.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault();let i;try{i=new URL(r.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}if(!a.trim().startsWith(`canvas-`)){n({title:`Error`,description:`Invalid access token (expected canvas-...)`,variant:`destructive`});return}f(!0),m(`Starting…`);try{let t=await Ga(i,a.trim(),e=>{m(Ka[e.phase]||e.phase)},{name:s.trim(),label:l.trim()});n({title:`Success`,description:`Workspace '${t.label||t.name}' imported from ${i}.`}),e(t)}catch(e){let t=e,r=t?.message||t?.payload?.message||`Failed to import remote workspace`;n({title:`Error`,description:r,variant:`destructive`})}finally{f(!1),m(``)}},className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:d}),(0,$.jsx)(Y,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:d}),(0,$.jsx)(Z,{type:`submit`,disabled:d||!r.trim()||!a.trim()||!s.trim()||!l.trim(),children:d?`Importing…`:`Import Workspace`})]}),(0,$.jsx)(KT,{name:s,label:l,setName:c,setLabel:u,disabled:d}),d&&p&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,$.jsx)(`strong`,{children:`copy`}),` of the workspace from the remote canvas-server into this one, where it then lives independently. The remote workspace is stopped while it is packed, and large workspaces can take several minutes — progress is shown above.`]})]})})}function eE(){let{showToast:e}=Vr(),[t,n]=(0,Q.useState)(``),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,$.jsx)(Y,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,$.jsx)(Z,{onClick:async()=>{if(!s(t.trim())){e({title:`Error`,description:`Invalid URL`,variant:`destructive`});return}if(!r.trim().startsWith(`canvas-`)){e({title:`Error`,description:`Invalid access token`,variant:`destructive`});return}o(!0);try{sessionStorage.setItem(`sharedToken:last`,r.trim());let e=new URLSearchParams({url:t.trim()}).toString();window.location.href=`/shared?${e}`}catch(t){e({title:`Error`,description:t instanceof Error?t.message:`Failed to open shared resource`,variant:`destructive`})}finally{o(!1)}},disabled:a||!t.trim()||!r.trim(),children:`Open`})]}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`We use your provided URL and token to fetch via the remote's public API.`})]})}function tE({onClose:e,onChanged:t}){let{showToast:n}=Vr(),r=gl(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)([]),f=(0,Q.useCallback)(async()=>{try{d(await wo())}catch{d([])}},[]);(0,Q.useEffect)(()=>{f()},[f]);let p=async e=>{e.preventDefault();let r;try{r=new URL(i.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}l(!0);try{let e=await 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 yi(e.id),await f(),t?.()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to remove remote workspace`,variant:`destructive`})}};return(0,$.jsxs)($w,{title:`Open a remote Workspace`,onClose:e,children:[(0,$.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,$.jsx)(Y,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,$.jsx)(Z,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,$.jsx)(`code`,{className:`font-mono text-xs`,children:`name@host`}),` — nothing is copied. Every call you make to it is forwarded to the remote with the share token (its permissions apply); document content and thumbnails are cached locally so they stay readable when the remote is offline. Use “Import remote…” if you want an independent local copy instead.`]})]}),u.length>0&&(0,$.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,$.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,$.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`remote`})]}),(0,$.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}var nE={membership:`keep`,propagation:`never`,targets:[],acceptPropagatedDeletions:!1},rE=e=>`/workspaces/${encodeURIComponent(e)}/trash/operations`,iE=(e,t)=>X.get(`${rE(e)}?${new URLSearchParams(Object.entries(t).map(([e,t])=>[e,String(t)]))}`),aE=(e,t,n,r={})=>X.post(`${rE(e)}/${n}`,{ids:t,...r}),oE=(e,t,n,r)=>X.patch(`/workspaces/${encodeURIComponent(e)}/backends/imap/${encodeURIComponent(t)}/containers/${encodeURIComponent(n)}`,{removalPolicy:r});function sE(e){let t=pb(`backends`,e.path)?.backend;return(0,$.jsx)(cE,{...e},JSON.stringify([e.workspace,t]))}function cE({workspace:e,path:t,onNavigate:n}){let r=pb(`backends`,t),i=r.backend,a=r.prefix,[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)(null),x=(0,Q.useCallback)(()=>g(e=>e+1),[]),[S,C]=(0,Q.useState)(t);S!==t&&(C(t),v(new Set),b(null),m(null),f(null));let w=o?.revision!==h,T=w?[]:o.items,E=w?[]:o.backends,D=o?.days;(0,Q.useEffect)(()=>{let t=!1;return(i?_b(e,i).then(e=>({...e,backends:[]})):pa(e).then(e=>({items:[],days:null,backends:e.filter(e=>e.driver===`file`&&e.enabled!==!1)}))).then(e=>{t||s({...e,revision:h,error:null})}).catch(e=>{t||s({revision:h,items:[],backends:[],days:null,error:e instanceof Error?e.message:String(e)})}),()=>{t=!0}},[e,i,h]),(0,Q.useEffect)(()=>{let t=null,n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==`backends`||(t||=setTimeout(()=>{t=null,x()},500))};return window.addEventListener(`workspace:trash:refresh`,n),window.addEventListener(`workspace:tree:refresh`,n),()=>{window.removeEventListener(`workspace:trash:refresh`,n),window.removeEventListener(`workspace:tree:refresh`,n),t&&clearTimeout(t)}},[e,x]);let O=hb(T,a),k=async(t,n)=>{if(!(!i||u.current||w||!n.length)&&!(t===`discard`&&!Sb(i,n))){u.current=!0,l(t),f(null),m(null),b(null);try{let r=await(t===`restore`?vb:yb)(e,i,[...n].sort((e,t)=>t.deletedAt-e.deletedAt).map(e=>e.id)),a=r.filter(e=>!e.ok);m(`${r.length-a.length} item(s) ${t===`restore`?`restored to their original paths`:`permanently deleted`}.`),a.length&&f(`${a.length} item(s) remain in Trash. ${a.slice(0,3).map(e=>`${e.key||`Item`}: ${e.reason===`precondition-failed`||e.reason===`target-exists`?`original path is occupied`:e.message||e.reason}`).join(`; `)}`),v(new Set)}catch(e){f(e instanceof Error?e.message:String(e))}finally{u.current=!1,l(null),x()}}},A=(e,t,n)=>b({x:e,y:t,row:n});return(0,$.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col bg-background`,"aria-label":`Backend Trash`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 border-b px-4 py-3`,children:[(0,$.jsx)(nt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(Km,{items:qm(t,e).map((e,t)=>t===2&&i?{...e,label:i}:e),onNavigate:n,className:`basis-48`}),(0,$.jsxs)(`div`,{className:`ml-auto flex max-w-full flex-wrap items-center gap-2`,children:[_.size>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`restore`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,$.jsx)(ir,{className:`h-3.5 w-3.5`}),`Restore selected`]}),(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.filter(e=>_.has(e.id)).flatMap(e=>e.items)),children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),`Delete selected`]})]}),i&&O.length>0&&(0,$.jsxs)(`button`,{className:`flex items-center gap-1 rounded border px-2 py-1 text-sm text-destructive disabled:opacity-50`,disabled:!!c||w,onClick:()=>void k(`discard`,O.flatMap(e=>e.items)),children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),a?`Empty this folder`:`Empty Trash`]}),(0,$.jsx)(`button`,{title:`Refresh Trash`,"aria-label":`Refresh Trash`,className:`rounded p-2 hover:bg-accent`,disabled:!!c||w,onClick:x,children:(0,$.jsx)(P,{className:`h-4 w-4 ${w?`animate-spin`:``}`})})]})]}),(0,$.jsxs)(`div`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`Restore files and folders to their original paths. Existing files are kept.`,D?` Deleted items are kept for ${D} days.`:``]}),p&&(0,$.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:p}),(d||o?.error)&&(0,$.jsx)(`p`,{role:`alert`,className:`px-4 py-2 text-sm text-destructive`,children:d||o?.error}),c&&(0,$.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:c===`restore`?`Restoring…`:`Deleting permanently…`}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:w?(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Loading Trash…`}):i?O.length===0?(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`This Trash folder is empty.`}):(0,$.jsxs)(`table`,{className:`w-full text-left text-sm`,children:[(0,$.jsx)(`thead`,{className:`border-b text-xs text-muted-foreground`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`w-8 p-2`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select all visible items`,checked:O.length>0&&O.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(O.map(e=>e.id)):new Set)})}),(0,$.jsx)(`th`,{className:`p-2`,children:`Name`}),(0,$.jsx)(`th`,{className:`p-2 max-sm:hidden`,children:`Original path`}),(0,$.jsx)(`th`,{className:`p-2 max-md:hidden`,children:`Deleted`}),(0,$.jsx)(`th`,{className:`p-2`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsx)(`tbody`,{children:O.map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-border/50 hover:bg-accent/50`,onContextMenu:t=>{t.preventDefault(),A(t.clientX,t.clientY,e)},onDoubleClick:()=>e.navigable&&n(mb(i,e.key)),children:[(0,$.jsx)(`td`,{className:`p-2`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.name}`,checked:_.has(e.id),disabled:!!c,onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,$.jsx)(`td`,{className:`p-2`,children:(0,$.jsxs)(`button`,{className:`flex items-center gap-2 text-left`,onClick:()=>e.navigable&&n(mb(i,e.key)),children:[e.directory?(0,$.jsx)($e,{className:`h-4 w-4 shrink-0`}):(0,$.jsx)(Rn,{className:`h-4 w-4 shrink-0`}),(0,$.jsxs)(`span`,{children:[e.name,e.navigable&&(0,$.jsxs)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.items.length,` items`]})]})]})}),(0,$.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-sm:hidden`,children:e.key}),(0,$.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-md:hidden`,children:new Date(e.items.reduce((e,t)=>Math.max(e,t.deletedAt),0)).toLocaleString()}),(0,$.jsx)(`td`,{className:`p-2 text-right`,children:(0,$.jsx)(`button`,{title:`Actions for ${e.name}`,"aria-label":`Actions for ${e.name}`,disabled:!!c,className:`rounded p-2 hover:bg-accent`,onClick:t=>A(t.clientX,t.clientY,e),children:(0,$.jsx)(vn,{className:`h-4 w-4`})})})]},e.id))})]}):(0,$.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[E.map(e=>(0,$.jsxs)(`button`,{onClick:()=>n(mb(e.address)),className:`flex items-center gap-3 rounded-lg border p-4 text-left hover:bg-accent`,children:[(0,$.jsx)(nt,{className:`h-6 w-6 text-muted-foreground`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:e.label||e.address}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.address})]})]},e.address)),!E.length&&(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`No file backends are available.`})]})}),y&&(0,$.jsxs)(em,{x:y.x,y:y.y,onClose:()=>b(null),className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[y.row.navigable&&(0,$.jsxs)(`button`,{className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent`,onClick:()=>{n(mb(i,y.row.key)),b(null)},children:[(0,$.jsx)($e,{className:`h-4 w-4`}),`Open folder`]}),(0,$.jsxs)(`button`,{disabled:!!c,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent disabled:opacity-50`,onClick:()=>void k(`restore`,y.row.items),children:[(0,$.jsx)(ir,{className:`h-4 w-4`}),`Restore `,y.row.directory?`folder`:`file`]}),(0,$.jsxs)(`button`,{disabled:!!c||w,className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm text-destructive hover:bg-destructive/10 disabled:opacity-50`,onClick:()=>void k(`discard`,y.row.items),children:[(0,$.jsx)(nt,{className:`h-4 w-4`}),`Delete permanently`]})]})]})}function lE({value:e,backends:t,source:n,onSave:r,destination:i=!0}){let[a,o]=(0,Q.useState)({...nE,...e}),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=`rounded border bg-background px-2 py-1.5 text-xs w-full`,f=async()=>{c(!0),u(``);try{await r(a),u(`Removal policy saved.`)}catch(e){u(e instanceof Error?e.message:`Could not save policy`)}finally{c(!1)}};return(0,$.jsxs)(`details`,{className:`border-t pt-3 text-xs`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:`Source removals and Trash`}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`A completed scan removes missing locations from the backend tree. Items with no remaining locations go to Trash until you purge them.`}),(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`space-y-1 block`,children:[`When an item disappears from this source`,(0,$.jsxs)(`select`,{className:d,value:a.membership,disabled:s,onChange:e=>o({...a,membership:e.target.value}),children:[(0,$.jsx)(`option`,{value:`keep`,children:`Keep in managed trees`}),(0,$.jsx)(`option`,{value:`review`,children:`Review removal in Trash`}),(0,$.jsx)(`option`,{value:`trash`,children:`Move to Trash automatically`})]})]}),(0,$.jsxs)(`label`,{className:`space-y-1 block`,children:[`Remove tracked copies from other backends`,(0,$.jsxs)(`select`,{className:d,value:a.propagation,disabled:s,onChange:e=>o({...a,propagation:e.target.value}),children:[(0,$.jsx)(`option`,{value:`never`,children:`Never`}),(0,$.jsx)(`option`,{value:`review`,children:`Review in Trash`}),(0,$.jsx)(`option`,{value:`automatic`,children:`Automatically, retaining recovery copies`})]})]})]}),a.propagation!==`never`&&(0,$.jsxs)(`fieldset`,{className:`space-y-2`,children:[(0,$.jsx)(`legend`,{className:`mb-1 font-medium`,children:`Destinations`}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:a.targets===`all`,disabled:s,onChange:e=>o({...a,targets:e.target.checked?`all`:[]})}),`All eligible backends`]}),a.targets!==`all`&&t.filter(e=>e.address!==n&&e.kind===`storage`).map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:s||e.config?.propagatedRemovalSupported!==!0,checked:a.targets.includes(e.address),onChange:t=>o({...a,targets:t.target.checked?[...a.targets,e.address]:a.targets.filter(t=>t!==e.address)})}),String(e.config?.label||e.address),e.config?.propagatedRemovalSupported===!0?!e.config?.removalPolicy?.acceptPropagatedDeletions&&` · protected`:` · recovery removal unavailable`]},e.address)),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`Only tracked, Canvas-owned copies are eligible. Protected destinations refuse propagated deletion. Recovery removal currently supports filesystem and workspace blob storage; remote destinations remain protected.`})]}),i&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:s,checked:a.acceptPropagatedDeletions,onChange:e=>o({...a,acceptPropagatedDeletions:e.target.checked})}),`Accept propagated deletions on this backend`]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>void f(),children:s?`Saving…`:`Save removal policy`}),(0,$.jsx)(`span`,{role:`status`,children:l})]})]})]})}function uE({workspaceName:e,canWrite:t}){let{showToast:n}=Vr(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(!1),d=(0,Q.useCallback)(async()=>{o(!0);try{i(await Bi(e))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to load the trash`,variant:`destructive`})}finally{o(!1)}},[e]);(0,Q.useEffect)(()=>{d()},[d]);let f=(0,Q.useCallback)(e=>s.includes(e),[s]),p=async(e,t)=>{c(t=>[...t,...e]);try{await t()}finally{c(t=>t.filter(t=>!e.includes(t)))}},m=t=>p([t.id],async()=>{try{let r=await ba(e,[t.id]);r.failed?.length?n({title:`Not restored`,description:r.failed[0]?.error||`No restore target recorded`,variant:`destructive`}):(n({title:`Restored`,description:`Document put back where it was.`}),i(e=>e.filter(e=>e.id!==t.id)))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to restore`,variant:`destructive`})}}),h=t=>p([t.id],async()=>{try{let r=await mi(e,[t.id]);if(r.failed?.length)throw Error(`The item could not be purged. Refresh and retry.`);n({title:`Cleared from Trash`,description:r.preserved?.length?`Existing backend copies remain indexed.`:`Document permanently deleted.`}),i(e=>e.filter(e=>e.id!==t.id))}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to delete`,variant:`destructive`})}}),g=async()=>{if(!l){u(!0);return}u(!1);try{let t=await mi(e);n({title:`Trash emptied`,description:`${t.destroyed?.length??0} document(s) purged. ${t.preserved?.length??0} item(s) cleared with backend copies preserved.`}),await d()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to empty the trash`,variant:`destructive`})}},_=(0,Q.useMemo)(()=>r.map(e=>{let t=Yr(e),n=(e.trashed?.placements??[]).flatMap(e=>e.paths.map(t=>`${e.tree}:${t}`));return{document:e,title:t.title,origin:n,trashedAt:e.trashed?.trashedAt||null}}),[r]);return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-medium`,children:`Managed-tree items`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1 max-w-2xl`,children:`Restore managed-tree placements or permanently purge these items. Pending removals require separate approval. Backend copies are managed below.`})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 max-sm:flex-wrap`,children:[(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>d(),disabled:a,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${a?`animate-spin`:``}`}),`Refresh`]}),(0,$.jsxs)(Z,{variant:l?`destructive`:`outline`,size:`sm`,onClick:g,onBlur:()=>u(!1),disabled:!t||r.length===0,children:[(0,$.jsx)(nt,{className:`mr-2 h-3.5 w-3.5`}),l?`Click again to delete everything`:`Empty trash`]})]})]}),a&&r.length===0&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading…`}),!a&&r.length===0&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`The trash is empty.`}),_.length>0&&(0,$.jsx)(`div`,{className:`border rounded-md divide-y`,children:_.map(({document:e,title:n,origin:r,trashedAt:i})=>(0,$.jsxs)(`div`,{className:`flex items-center gap-3 px-3 py-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm`,children:n}),(0,$.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[r.length>0?`from ${r.join(`, `)}`:`no recorded origin`,i?` · ${new Date(i).toLocaleString()}`:``]})]}),(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:()=>m(e),disabled:!t||f(e.id)||r.length===0,title:r.length===0?`Nothing recorded to restore to`:`Put it back where it was`,children:[(0,$.jsx)(ir,{className:`mr-2 h-3.5 w-3.5`}),`Restore placements`]}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>h(e),disabled:!t||f(e.id),title:`Delete permanently`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]},e.id))})]})}function dE({workspaceName:e}){return(0,$.jsx)(fE,{workspaceName:e},e)}function fE({workspaceName:e}){let[t,n]=(0,Q.useState)(`pending`),[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(0),[l,u]=(0,Q.useState)(0),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(new Set),[y,b]=(0,Q.useState)({}),[x,S]=(0,Q.useState)(`/Trash`),[C,w]=(0,Q.useState)([]),[T,E]=(0,Q.useState)({write:!1,admin:!1});(0,Q.useEffect)(()=>{let t=!0;return qr(e).then(e=>{let n=e.remote?.permissions||e.access?.permissions||(typeof e.sharedVia==`object`?e.sharedVia?.permissions:[])||[],r=Op(e);t&&E({admin:r,write:r||n.includes(`write`)})}).catch(()=>{}),()=>{t=!1}},[e]);let[D,O]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let t=!0;return pa(e).then(e=>{t&&w(e)}).catch(()=>{}),()=>{t=!1}},[e]),(0,Q.useEffect)(()=>{let n=!1,i=()=>iE(e,{view:t,search:r,...a?{backend:a}:{},offset:s}).then(e=>{n||(f(e),m(``))}).catch(e=>{n||m(e instanceof Error?e.message:`Could not load Trash`)});i();let o=setInterval(()=>{h||i()},5e3);return()=>{n=!0,clearInterval(o)}},[e,t,r,a,s,l,h]);let k=d?.operations||[],A=()=>{v(new Set),u(e=>e+1)},j=()=>{Da(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),window.dispatchEvent(new CustomEvent(`workspace:trash:refresh`,{detail:{workspaceName:e}}))},M=async(t,n=[..._])=>{if(!(!n.length||h)&&!(t===`purge`&&!window.confirm(`Permanently delete retained recovery copies for ${n.length} operation(s)?`))){g(!0),m(``);try{let r=(t===`approve`?(await Promise.all(n.map(n=>aE(e,[n],t,y[n])))).flatMap(e=>e.results):(await aE(e,n,t)).results).filter(e=>!e.ok||e.operation?.state===`failed`);r.length&&m(r.map(e=>e.error||e.operation?.error||`A destination could not be changed. Expand the item for details.`).join(` `)),j(),A()}catch(e){m(e instanceof Error?e.message:`Trash action failed`)}finally{g(!1)}}},N=e=>{n(e),c(0),f(null),v(new Set),b({})};return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:`Workspace Trash`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:`Review source removals, recover items, and see what automatic policies changed.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,role:`tablist`,"aria-label":`Trash views`,children:[[[`pending`,`Pending removal`],[`trashed`,`In Trash`],[`activity`,`Activity`]].map(([e,n])=>(0,$.jsx)(Z,{role:`tab`,"aria-selected":t===e,size:`sm`,variant:t===e?`default`:`outline`,onClick:()=>N(e),children:n},e)),(0,$.jsxs)(Z,{size:`sm`,variant:`ghost`,className:`ml-auto`,onClick:A,disabled:h,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),t===`trashed`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(uE,{workspaceName:e,canWrite:T.write},l),(0,$.jsxs)(`details`,{className:`rounded border p-3`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:`Browse backend recovery copies`}),(0,$.jsx)(`div`,{className:`mt-3 min-h-48`,children:(0,$.jsx)(sE,{workspace:e,path:x,onNavigate:S})})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(Y,{"aria-label":`Filter Trash items`,placeholder:`Filter by item or path…`,className:`max-w-xs`,value:r,onChange:e=>{i(e.target.value),f(null),c(0),v(new Set)}}),(0,$.jsx)(Y,{"aria-label":`Filter by backend`,placeholder:`Backend name…`,className:`max-w-56`,value:a,onChange:e=>{o(e.target.value),f(null),c(0),v(new Set)}}),_.size>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsxs)(`span`,{children:[_.size,` selected`]}),t===`pending`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{size:`sm`,disabled:h,onClick:()=>void M(`approve`),children:`Approve selected`}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`keep`),children:`Keep selected`}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`retry`),children:`Retry`})]}),t===`trashed`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:h,onClick:()=>void M(`restore`),children:`Restore copies`}),(0,$.jsx)(Z,{size:`sm`,variant:`destructive`,disabled:h,onClick:()=>void M(`purge`),children:`Purge copies`})]})]})]}),D&&(0,$.jsxs)(`div`,{className:`rounded border p-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Removal policy · `,D.source.account||D.source.backend,D.source.folder?` / ${D.source.folder}`:``]}),(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,onClick:()=>O(null),children:`Close`})]}),(0,$.jsx)(lE,{source:D.source.backend,backends:C,destination:!1,value:{...nE,...C.find(e=>e.address===D.source.backend)?.config?.removalPolicy,membership:y[D.id]?.membership??D.membership!==`keep`?`review`:`keep`,propagation:D.targets.length?`review`:`never`,targets:[...new Set(D.targets.filter(e=>!y[D.id]||y[D.id].targets.includes(JSON.stringify([e.backend,e.key]))).map(e=>e.backend))]},onSave:async t=>{D.source.driver===`imap`?await oE(e,D.source.account,D.source.folder,t):await _o(e,D.source.driver,D.source.backend,{removalPolicy:t}),w(await pa(e))}},D.id)]}),p&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:p}),(0,$.jsxs)(`div`,{className:`overflow-x-auto rounded border`,children:[(0,$.jsxs)(`table`,{className:`w-full text-left text-xs`,children:[(0,$.jsx)(`thead`,{className:`bg-muted`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`p-3 w-8`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select visible operations`,disabled:!T.write||h||!k.length||t===`activity`,checked:k.length>0&&k.every(e=>_.has(e.id)),onChange:e=>v(e.target.checked?new Set(k.map(e=>e.id)):new Set)})}),(0,$.jsx)(`th`,{className:`p-3`,children:`Item and affected copies`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Source`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Status`}),(0,$.jsx)(`th`,{className:`p-3`,children:`Detected`})]})}),(0,$.jsx)(`tbody`,{children:k.map(e=>{let n=y[e.id]||{targets:e.targets.filter(e=>e.state!==`kept`).map(e=>JSON.stringify([e.backend,e.key])),membership:e.membership!==`keep`};return(0,$.jsxs)(`tr`,{className:`border-t align-top`,children:[(0,$.jsx)(`td`,{className:`p-3`,children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Select ${e.title}`,disabled:!T.write||h||t===`activity`,checked:_.has(e.id),onChange:t=>v(n=>{let r=new Set(n);return t.target.checked?r.add(e.id):r.delete(e.id),r})})}),(0,$.jsx)(`td`,{className:`p-3 min-w-64`,children:(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{className:`cursor-pointer font-medium`,children:e.title}),(0,$.jsxs)(`div`,{className:`mt-2 space-y-2 text-muted-foreground`,children:[(0,$.jsx)(`p`,{children:e.orphan?`No remaining byte locations. Restore placements only unless recovery bytes are available.`:`${e.remainingLocations.length} remaining location(s) when detected.`}),e.placements.map(e=>(0,$.jsxs)(`p`,{children:[e.tree,`: `,e.paths.join(`, `)]},e.tree)),e.membership!==`keep`&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:n.membership,disabled:h||t!==`pending`||e.membershipApplied,onChange:t=>b({...y,[e.id]:{...n,membership:t.target.checked}})}),e.membershipApplied?`Managed placements moved to Trash`:`Move managed placements to Trash`]}),e.targets.map(r=>{let i=JSON.stringify([r.backend,r.key]);return(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:h||t!==`pending`||!!r.trashId,checked:n.targets.includes(i),onChange:t=>b({...y,[e.id]:{...n,targets:t.target.checked?[...n.targets,i]:n.targets.filter(e=>e!==i)}})}),(0,$.jsxs)(`span`,{className:`break-all`,children:[r.backend,`:`,r.key,` · `,r.state,r.error&&(0,$.jsx)(`span`,{className:`block text-destructive`,children:r.error})]})]},i)}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:!T.admin,onClick:()=>O(e),children:`Use these choices as a source policy`}),e.remainingLocations.map(e=>(0,$.jsx)(`p`,{className:`break-all`,children:e.url},e.url))]})]})}),(0,$.jsxs)(`td`,{className:`p-3 break-all`,children:[e.source.account||e.source.backend,e.source.folder&&(0,$.jsx)(`span`,{className:`block text-muted-foreground`,children:e.source.folder})]}),(0,$.jsxs)(`td`,{className:`p-3`,children:[e.state,e.error&&(0,$.jsx)(`p`,{className:`mt-1 max-w-xs text-destructive`,children:e.error})]}),(0,$.jsx)(`td`,{className:`p-3 whitespace-nowrap text-muted-foreground`,children:new Date(e.createdAt).toLocaleString()})]},e.id)})})]}),!k.length&&(0,$.jsx)(`p`,{className:`p-5 text-center text-sm text-muted-foreground`,children:d?`No matching operations.`:`Loading…`})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[d?.total??0,` operation(s)`]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:!s||h,onClick:()=>{c(Math.max(0,s-200)),v(new Set)},children:`Previous`}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,disabled:s+k.length>=(d?.total??0)||h,onClick:()=>{c(s+200),v(new Set)},children:`Next`})]})]})]})}function pE({workspaceName:e,children:t}){let n=e,[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(0),[d,f]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{let t=!1,r=0,a,s=!1,c=async()=>{if(s||t)return;s=!0;let c=++r;try{let s=a?await co(e):await qr(e);!t&&c===r&&(`id`in s&&(a=s.id,f({identity:n,allowed:Op(s)})),i({identity:n,state:Tr()||s.status===`active`?`active`:s.status===`inactive`?`stopped`:`unavailable`}),o(``))}catch(e){if(!t&&c===r){let t=e instanceof Error?e.message:`Unable to check workspace status`,r=wr(t);i(e=>r&&e?.identity===n&&e.state===`active`?e:{identity:n,state:r?`offline`:`unavailable`}),o(t)}}finally{s=!1}},l=t=>{let s=t.detail?.refs;!s?.includes(e)&&!(a&&s?.includes(a))||(r++,i({identity:n,state:`stopped`}),o(``))},u=t=>{let s=t.workspaceId||t.id;!s||s!==e&&s!==a||!t.status||(r++,i({identity:n,state:t.status===`active`?`active`:t.status===`inactive`?`stopped`:`unavailable`}),o(``))};c(),window.addEventListener(`workspaces:refresh`,c),window.addEventListener(`workspace:stopped`,l),window.addEventListener(`focus`,c);let d=hd.on(`connect`,c);hd.on(`workspace:status:changed`,u),hd.on(`workspace.status.changed`,u);let p=Nr(e=>{e||c()});return()=>{t=!0,d?.(),p(),hd.off(`workspace:status:changed`,u),hd.off(`workspace.status.changed`,u),window.removeEventListener(`workspaces:refresh`,c),window.removeEventListener(`workspace:stopped`,l),window.removeEventListener(`focus`,c)}},[e,n,l]),r?.identity!==n)return(0,$.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`});if(r.state===`active`)return t;let p=r.state===`stopped`;return(0,$.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`font-medium`,children:p?`Workspace stopped`:r.state===`offline`?`Server unreachable`:`Workspace unavailable`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p?`Start this workspace to view its content.`:r.state===`offline`?`Reconnect to load this workspace. Previously loaded content stays available offline.`:`Unable to check this workspace. Try again or check its settings.`}),a&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,$.jsx)(Z,{disabled:s,onClick:async()=>{c(!0),o(``);try{p&&await so(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?p?`Starting…`:`Checking…`:p?`Start workspace`:`Retry`}),d?.identity===n&&d.allowed&&(0,$.jsx)(Nu,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]})}function mE({workspaceId:e,workspaceName:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,Q.useEffect)(()=>{let t=!1,n=!1,i=!1,a=0,o=new Map,s=new Map,c=(e,t)=>{let n=e.filter(e=>e.address!==t.backend);if(!t.resyncing)return n;let r=e.find(e=>e.address===t.backend)||s.get(t.backend);return[...n,{address:t.backend,config:r?.config,resyncStartedAt:r?.resyncStartedAt||new Date().toISOString(),progress:t.progress??r?.progress}]},l=async()=>{if(n){i=!0;return}n=!0;let u=a;try{let n=await pa(e);if(!t){s=new Map(n.map(e=>[e.address,e]));let e=n.filter(e=>e.resyncing);for(let t of o.values())t.version>u&&(e=c(e,t.event));r(e)}}catch{}finally{n=!1,i&&!t&&(i=!1,l())}},u=t=>{t.workspaceId!==e||!t.backend||typeof t.resyncing!=`boolean`||(o.set(t.backend,{version:++a,event:t}),r(e=>c(e,t)))},d=t=>{t.workspaceId===e&&l()};l();let f=hd.on(`connect`,l);return hd.on(`backend.resync.changed`,u),hd.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),hd.off(`backend.resync.changed`,u),hd.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,$.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,$.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,$.jsx)(Yn,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,$.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,$.jsx)(G,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,$.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:i}),(0,$.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,$.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}function hE({navigationTabs:e,navigationActions:t,onBack:n,accentColor:r,frameContent:i=!0,urlType:a,urlDisplay:o,contextPath:s,treeName:c,workspaceId:l,workspaceLabel:u,workspaceIcon:d,documentSchema:f,documents:p,isLoading:m,totalCount:h,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:M,disablePurgeDocuments:N,canvasInfo:P,isCanvasPinned:F,onTogglePinCanvas:I,onSaveAsCanvas:L,onShareCanvas:R,onUnshareCanvas:z,onDeleteCanvas:ne,isSharingCanvas:B,isDeletingCanvas:re,isCanvasShared:ie,isCanvasLocked:ae,backendSearchQueries:oe,onBackendSearch:V,onRemoveBackendQuery:H,serverSort:U,onServerSortChange:se,scope:W,onScopeChange:ce,canSaveChanges:le,isSavingChanges:ue,onSaveChanges:de,onBrowseWorkspaces:fe,onBrowseTree:pe,onNavigatePath:me,linkTree:G,children:he,contentBanner:ge,folders:_e,onOpenFolder:ve}){let K=a===`canvas`,{state:q,toggleView:ye,hasActiveFilters:be,openAddPicker:xe}=zs(),Se=Eg(),[Ce,we]=(0,Q.useState)(``),Te=JSON.stringify([l,c,s,f]),[Ee,De]=(0,Q.useState)(Te);Ee!==Te&&(De(Te),we(``));let ke=(0,$.jsxs)($.Fragment,{children:[t,L&&(0,$.jsx)(`button`,{type:`button`,onClick:L,title:`Save as canvas`,"aria-label":`Save as canvas`,className:`flex h-control-sm w-control-sm shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent touch-target`,children:(0,$.jsx)(Ft,{className:`h-4 w-4`})})]});return(0,$.jsxs)(`div`,{className:`flex flex-col h-full min-h-0 bg-background`,children:[e&&(0,$.jsx)(Xg,{accentColor:r,children:e}),(0,$.jsxs)(`div`,{className:`canvas-surface-body${i?` is-framed`:``}`,children:[(0,$.jsx)(Zg,{workspaceIcon:d,workspace:u||l||o.split(`://`)[0]||`Workspace`,tree:c?`${c}${a.endsWith(`-layer`)?`:layer`:``}`:a.replace(`-layer`,``),path:s,accentColor:r,onBack:Se.location?Se.location.section===`view`?Se.close:()=>Se.update?.({section:`view`}):n,section:Se.location?`document/${Se.location.documentId}/${Se.location.section}`:void 0,onSection:Se.location?()=>Se.update?.({section:`view`}):void 0,onBrowseWorkspaces:fe,onBrowseTree:pe,onNavigatePath:me,onFilter:()=>ye(`tools`),filtersActive:be,filtersOpen:q.t1Open&&q.t1View===`tools`,onAdd:e=>xe({modal:e.shiftKey,fresh:!0}),search:V||!he?{queries:oe||[],onSearch:V??we,localOnly:!V,onRemoveQuery:H,scope:W,onScopeChange:ce}:void 0,onDraftChange:he?void 0:we}),K&&P?(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[P.color&&(0,$.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:P.color}}),(0,$.jsx)(gt,{className:`w-4 h-4 shrink-0 text-primary`}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:P.label||o.split(`://`)[1]||`Canvas`}),P.description&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:P.description})]}),le&&de&&(0,$.jsxs)(`button`,{type:`button`,onClick:de,disabled:ue,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:`Save filters`,children:[(0,$.jsx)(Be,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:ue?`Saving...`:`Save filters`})]}),I&&(0,$.jsxs)(`button`,{type:`button`,onClick:I,"aria-pressed":!!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`,title:F?`Unpin from home`:`Pin to home`,children:[F?(0,$.jsx)(ee,{className:`w-3 h-3`}):(0,$.jsx)(Oe,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:F?`Unpin`:`Pin`})]}),R&&(0,$.jsxs)(`button`,{type:`button`,onClick:R,disabled:B||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:ie?`Copy public link`:`Share canvas`,children:[(0,$.jsx)(jn,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:B?`Sharing...`:ie?`Copy link`:`Share`})]}),ie&&z&&(0,$.jsxs)(`button`,{type:`button`,onClick:z,disabled:B||re,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,$.jsx)(te,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),ne&&(0,$.jsxs)(`button`,{type:`button`,onClick:ne,disabled:re||ae&&!ie,title:ae&&!ie?`Unlock this canvas before deleting it`:`Delete canvas`,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,$.jsx)(nt,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`hidden sm:inline`,children:re?`Deleting…`:`Delete`})]})]})}):null,he&&(L||t)&&(0,$.jsx)(`div`,{className:`flex items-center gap-2 border-b px-3 py-1`,children:ke}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[ge,he||(0,$.jsx)(rx,{externalSearchQuery:Ce,toolbarActions:ke,documents:f?p.filter(e=>e.schema===f):p,isLoading:m,folders:f?void 0:_e,onOpenFolder:ve,contextPath:s,treeName:c,workspaceId:l,totalCount:h,viewMode:f?`card`:`table`,allowViewToggle:!0,currentPage:g,pageSize:_,onPageChange:v,onPageSizeChange:y,onRemoveDocument:b,onDeleteDocument:x,onDestroyDocument:S,onRemoveDocuments:C,onDeleteDocuments:w,onDestroyDocuments:T,onCopyDocuments:E,onCutDocuments:D,onPasteDocuments:O,onImportDocuments:k,onSelectionChange:A,pastedDocumentIds:j,onPurgeDocuments:f?void 0:M,disablePurgeDocuments:N,backendSearchQueries:oe,onBackendSearch:V,serverSort:U,onServerSortChange:se,onRemoveBackendQuery:H,scope:W,onScopeChange:ce,canSaveChanges:!K&&le,isSavingChanges:ue,onSaveChanges:de,linkTree:G},f??`documents`)]})]})]})}var gE=[{id:`todos`,label:`Todo list`},{id:`todo-app`,label:`Todo App`},{id:`notes`,label:`Notes list`},{id:`notes-app`,label:`Notes App`},{id:`sketch`,label:`Sketch`}];function _E(e){return e?.kind===`app`&&e.app===`notes`?`data/schema/note`:void 0}var vE={id:`default`,name:`All`,kind:`documents`};function yE(){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 bE(e){let t=e?.views;if(!Array.isArray(t))return[vE];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`&&(gE.some(e=>e.id===t.app)||t.app===`filters`||t.app===`lens`)});return n.length>0?n:[vE]}var xE={todos:Vt,"todo-app":Vt,notes:Kn,"notes-app":Kn,filters:Un,sketch:le,lens:cr};function SE({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=v.current;if(!e)return;let t=t=>{if(t.ctrlKey||e.scrollWidth<=e.clientWidth)return;let n=Math.abs(t.deltaX)>Math.abs(t.deltaY)?t.deltaX:t.deltaY,r=t.deltaMode===1?16:t.deltaMode===2?e.clientWidth:1;t.preventDefault(),e.scrollLeft+=n*r};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[]),(0,Q.useEffect)(()=>{v.current?.querySelector(`[aria-pressed="true"], input`)?.scrollIntoView({block:`nearest`,inline:`nearest`})},[t,c]);let y=()=>{h(null),_(null)},b=()=>{if(m&&g&&m!==g.id){let t=e.find(e=>e.id===m),n=e.filter(e=>e.id!==m),i=n.findIndex(e=>e.id===g.id);t&&i>=0&&(n.splice(g.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!c)return;let t=u.trim();t&&r(e.map(e=>e.id===c?{...e,name:t}:e)),l(null)},S=(t,n)=>{p(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?gE.find(e=>e.id===n)?.label??`App`:`List`,o=t===`columns`?{id:i,name:a,kind:t,columns:yE()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),l(i),d(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[vE],n===t?i[0]?.id??vE.id:void 0)};return(0,$.jsxs)(`div`,{className:J(`relative flex h-full min-w-0 items-end`,a),children:[(0,$.jsx)(`div`,{ref:v,className:`flex min-w-0 items-end gap-0.5 overflow-x-auto overscroll-x-contain pt-1 [scrollbar-width:none]`,children:e.map(r=>{let a=r.id===t,f=r.kind===`columns`?rr:r.kind===`app`&&r.app?xE[r.app]:Kt;return c===r.id?(0,$.jsx)(`input`,{autoFocus:!0,"aria-label":`Tab name`,value:u,onChange:e=>d(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&l(null)},className:J(`relative h-[2.3rem] w-28 shrink-0 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs outline-none ring-0`,a?J(`z-[2] bg-background font-medium`,o?Fm(o):`text-foreground`):`bg-muted text-muted-foreground`),style:{backgroundColor:a?o:void 0}},r.id):(0,$.jsxs)(`button`,{type:`button`,"aria-pressed":a,onClick:()=>n(r.id),onDoubleClick:()=>{i||(l(r.id),d(r.name))},title:i?r.name:`${r.name}: double-click to rename, drag to reorder`,draggable:!i,onDragStart:e=>{e.dataTransfer.setData(`text/plain`,r.name),e.dataTransfer.effectAllowed=`move`,h(r.id)},onDragOver:e=>{if(!m||m===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;_(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:J(`group relative flex h-[2.3rem] shrink-0 items-center gap-1.5 rounded-t-[.5rem] border-0 px-3 pb-1 text-xs transition-colors`,a?J(`z-[2] bg-background font-medium`,o?Fm(o):`text-foreground`):`bg-muted text-muted-foreground hover:bg-accent hover:text-foreground`,m===r.id&&`opacity-50`),style:{backgroundColor:a?o:void 0,boxShadow:g?.id===r.id?`inset ${g.before?`2px`:`-2px`} 0 0 var(--primary)`:void 0},children:[(0,$.jsx)(f,{className:`h-3 w-3 shrink-0`}),(0,$.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,$.jsx)(Ze,{className:`h-3 w-3 shrink-0 opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-60`,"aria-label":`Open to the side`,onClick:e=>{e.stopPropagation(),s(r.id)}}),!i&&e.length>1&&(0,$.jsx)(G,{className:J(`h-3 w-3 shrink-0 transition-opacity hover:text-destructive`,a?`opacity-60 hover:opacity-100`:`opacity-0 group-hover:opacity-100`),onClick:e=>{e.stopPropagation(),C(r.id)}})]},r.id)})}),!i&&(f?(0,$.jsxs)(`span`,{className:`absolute left-0 top-full z-30 flex w-full min-w-64 flex-wrap items-center gap-2 rounded-b-xl border bg-card p-2 shadow-lg`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(Kt,{className:`h-3 w-3`}),` List`]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(rr,{className:`h-3 w-3`}),` Board`]}),gE.map(e=>{let t=xE[e.id];return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-10 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,$.jsx)(t,{className:`h-3 w-3`}),` `,e.label]},e.id)}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,$.jsx)(G,{className:`h-3 w-3`})})]}):(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(!0),title:`Add view`,"aria-label":`Add view`,className:`relative ml-1 flex h-[2.3rem] w-10 shrink-0 items-center justify-center rounded-md pb-1 text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,$.jsx)(sn,{className:`h-3.5 w-3.5`})}))]})}function CE(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let o=!1;return to(e,n,t,{limit:200,allOf:[r],...i?{sortBy:i,order:`asc`}:{}}).then(e=>{o||l({key:a,docs:e.payload||[]})}).catch(()=>{o||l({key:a,docs:[]})}),()=>{o=!0}},[a,o]);let u=c?.key===a?c.docs:[],d=c?.key!==a;return(0,Q.useEffect)(()=>{let e=()=>s(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]),{docs:u,isLoading:d,refresh:(0,Q.useCallback)(()=>s(e=>e+1),[])}}function wE({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=CE(e,t,n,Ji,`tasks`),[o,s]=(0,Q.useState)(!1),c=o?r.filter(e=>e.data?.status!==`completed`):r,l=r.filter(e=>{let t=e.data?.status;return t!==`completed`&&t!==`cancelled`}).length;return(0,$.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,$.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,$.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,$.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,$.jsx)(Ax,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function TE({app:e,contextId:t,...n}){let r=t&&e!==`lens`?{mode:`context`,contextId:t}:{mode:`workspace`,workspaceName:n.workspaceId,treeName:n.treeName,path:n.path,treeType:n.treeName===`directory`||n.treeName===`backends`?`directory`:`context`},i=e===`todo-app`?`todo`:e===`notes-app`?`notes`:e,a=Dw.find(e=>e.id===i);return(0,$.jsx)(kw,{target:r,children:e===`todos`?(0,$.jsx)(wE,{...n}):a?(0,$.jsx)(a.Component,{}):null})}var EE=[{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 DE(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function OE({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)({}),[d,f]=(0,Q.useState)({}),p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1),g=(0,Q.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,Q.useEffect)(()=>{let e=p.current;if(!e)return;let t=new ResizeObserver(()=>g());return t.observe(e),()=>t.disconnect()},[g]);let _=(e,t)=>{e.preventDefault();let i=e.currentTarget.parentElement;if(!i)return;let a=e.clientX,o=i.getBoundingClientRect().width,s=o,c=e=>{s=Math.min(900,Math.max(220,o+e.clientX-a)),f(e=>({...e,[t]:s}))},l=()=>{window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),r(n.map(e=>e.id===t?{...e,width:Math.round(s)}:e))};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l)},v=e=>{f(t=>{let n={...t};return delete n[e],n}),r(n.map(t=>t.id===e?{...t,width:void 0}:t))},y=e=>{let t=l[e];if(t===void 0)return;let i=n.find(t=>t.id===e);i&&(i.filter||``)!==t&&r(n.map(n=>n.id===e?{...n,filter:t||void 0}:n))},b=EE.filter(e=>!n.some(t=>t.id===e.id));return(0,$.jsxs)(`div`,{className:`relative h-full`,children:[(0,$.jsx)(`div`,{ref:p,onScroll:g,className:`flex h-full snap-x snap-mandatory gap-3 overflow-x-auto overscroll-x-contain p-2`,"data-testid":`schema-columns-board`,children:n.map(t=>{let a=(l[t.id]??t.filter??``).toLowerCase(),s=e.filter(e=>DE(e,t.schemas)).filter(e=>{if(!a)return!0;let t=Yr(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,$.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-(--card-radius) border bg-muted/20 ${c?`sm:basis-[var(--col-w)]`:`sm:basis-[48%] lg:basis-[32%] xl:basis-[24%]`}`,style:c?{"--col-w":`${c}px`}:void 0,children:[!i&&(0,$.jsx)(`div`,{onPointerDown:e=>_(e,t.id),onDoubleClick:()=>v(t.id),title:`Drag to resize; double-click to reset`,className:`absolute right-0 inset-y-0 z-10 w-2 cursor-col-resize touch-none rounded-r-lg transition-colors hover:bg-primary/25 active:bg-primary/40 max-sm:hidden`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,$.jsx)(`span`,{className:`flex-1`}),!i&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(n.filter(e=>e.id!==t.id)),title:`Remove column`,className:`rounded-sm p-0.5 text-muted-foreground hover:text-destructive`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(`div`,{className:`px-3 pb-2`,children:(0,$.jsx)(`input`,{value:l[t.id]??t.filter??``,onChange:e=>u(n=>({...n,[t.id]:e.target.value})),onBlur:()=>y(t.id),onKeyDown:e=>{e.key===`Enter`&&y(t.id)},placeholder:`Filter…`,readOnly:i,className:`h-7 w-full rounded-md border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})}),(0,$.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=Yr(e);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>o(e),className:`w-full min-w-0 rounded-md border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(Gm,{document:e,size:3.5}),(0,$.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,$.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,$.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground/70`,children:new Date(e.updatedAt||e.createdAt).toLocaleDateString()})]},e.id)}),s.length===0&&(0,$.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground/60`,children:`Empty`})]})]},t.id)})}),(!i&&b.length>0||m)&&(0,$.jsxs)(`div`,{className:`pointer-events-none absolute inset-y-0 right-0 z-20 flex w-7 flex-col items-end bg-gradient-to-l from-background via-background/60 to-transparent py-2`,children:[!i&&b.length>0&&(0,$.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(e=>!e),title:`Add column`,"aria-label":`Add column`,className:`flex h-7 w-6 items-center justify-center rounded-l-md border border-r-0 bg-background text-muted-foreground shadow-elevation-1 hover:bg-accent hover:text-foreground`,children:(0,$.jsx)(sn,{className:`h-3.5 w-3.5`})}),s&&(0,$.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,$.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>{c(!1),r([...n,{...e}])},className:`w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:e.label},e.id)),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`mt-1 w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/60 hover:bg-accent/50`,children:`Cancel`})]})]}),m&&(0,$.jsx)(hr,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,$.jsx)(Hy,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var kE=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function AE(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function jE(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>jE(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:AE(e)}];let r=kE(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:AE(e)}))}function ME(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 NE(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 PE(e,t,n=new Map){let r=kE(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:AE(n)}],ids:ME(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...jE(r.context,`context`,n),...jE(r.directory,`directory`,n)],a=kE(r.changed);a&&i.push(...jE(a.context,`context`,n),...jE(a.directory,`directory`,n));let o=ME(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 FE(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function IE(e,t){if(e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree)return!1;if(t.kind===`context`){let n=e=>AE(e).split(`/`).filter(Boolean).map(e=>e.normalize(`NFKC`).trim().replace(/\s+/g,` `).replace(/[^\p{L}\p{N}\p{M} .+_@-]/gu,`_`).replace(/_+/g,`_`).toLowerCase()||`_`),r=new Set(n(e.path)),i=n(t.path);return r.size===0||i.length===0||i.some(e=>r.has(e))}return FE(e.path,t.path)}function LE(e){return PE(`tree.refresh`,{treeName:e?.treeName,path:e?.path||`/`})}function RE(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>IE(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 zE=(0,Q.createContext)(null);function BE(){let e=(0,Q.useContext)(zE);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function VE(e,t,n={}){return hd.request(td,{workspace:e,specs:t,opts:n})}function HE(e,t,n){return hd.request(nd,{sessionId:e,label:t,spec:n})}function UE(e){return hd.request(rd,{sessionId:e})}function WE(e,t={}){return hd.request(id,{sessionId:e,...t})}function GE(e){return hd.request(ad,{sessionId:e})}function KE(e){return hd.on(od,e)}var qE=100;function JE({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),f=(0,Q.useRef)([]),p=(0,Q.useRef)(new Map),m=(0,Q.useRef)(null),h=(0,Q.useRef)(null),g=(0,Q.useRef)(null),_=(0,Q.useRef)({}),v=(0,Q.useRef)(null),y=(0,Q.useMemo)(()=>JSON.stringify(t),[t]),b=(0,Q.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,Q.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,Q.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=qE){let i=e.slice(r,r+qE),a=await Na(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,Q.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),x(),r.length===0)return;let a=await S(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}x()},[S,x]),w=(0,Q.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await C(a,[],t)},[C]);(0,Q.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await VE(e,JSON.parse(y),JSON.parse(b));if(t){GE(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=hd.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&GE(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,Q.useEffect)(()=>{if(!c)return;let e=KE(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,Q.useCallback)(async()=>{let e=m.current;if(e)try{let t=await UE(e);await w(t.ids,t.count)}catch{}},[w]),E=(0,Q.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await HE(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await w(r.ids,r.count)},[w]),D=(0,Q.useCallback)(async(e,t={})=>{let n=m.current;if(!n)throw Error(`No open query session`);if(g.current=e,_.current=t,e===null){await T();return}let r=await WE(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,Q.useEffect)(()=>{v.current=D},[D]);let O=(0,Q.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await WE(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 HE(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 YE=`canvas:query-debug`,XE=`canvas:query-debug-changed`;function ZE(){try{return localStorage.getItem(YE)===`1`}catch{return!1}}function QE(e){try{e?localStorage.setItem(YE,`1`):localStorage.removeItem(YE)}catch{}window.dispatchEvent(new CustomEvent(XE,{detail:e}))}function $E(){let[e,t]=(0,Q.useState)(ZE);return(0,Q.useEffect)(()=>{let e=()=>t(ZE());return window.addEventListener(XE,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(XE,e),window.removeEventListener(`storage`,e)}},[]),e}function eD({data:e,className:t}){let[n,r]=(0,Q.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,Q.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,$.jsxs)(`div`,{className:J(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let s=a>0?i[a].distance:null;return(0,$.jsxs)(`div`,{className:J(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,$.jsx)(Xe,{className:`h-3.5 w-3.5`}):(0,$.jsx)(hr,{className:`h-3.5 w-3.5`}),`Query debug`,(0,$.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,$.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,s===null?(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,$.jsxs)($.Fragment,{children:[` A jump at `,(0,$.jsx)(`span`,{className:`font-mono`,children:s.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,$.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,$.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,$.jsx)(`tbody`,{children:i.map((e,t)=>(0,$.jsxs)(`tr`,{className:J(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,$.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,$.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,$.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,$.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}function tD(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 nD=new Map;function rD(e,t,n){return`${e}\0${t}\0${n}`}function iD(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${rD(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function aD(e,t,n){let r=rD(e,t,n);for(let e of nD.keys())e.startsWith(r)&&nD.delete(e)}function oD(e,t){let n=`${e}\0`;for(let[e,r]of nD){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);RE(t,{tree:i,kind:ka(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&nD.delete(e)}}function sD(e,t){oD(t?.workspaceName??e,LE(t))}function cD(){let{workspaceName:e}=bl();return e?(0,$.jsx)(pE,{workspaceName:e,children:(0,$.jsx)(lD,{})}):null}function lD(){let{workspaceName:e,treeName:t}=bl(),n=pl(),r=gl(),{showToast:i,showProgress:a}=Vr(),o=new URLSearchParams(n.search),s=(()=>{let e=o.getAll(`q`).map(e=>e.trim()).filter(Boolean);if(e.length>0)return e;let t=(o.get(`search`)||``).trim();return t?[t]:[]})(),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(!0),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(0),v=$E(),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(v);x!==v&&(S(v),v||b(null));let[C,w]=(0,Q.useState)(`path`),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(``),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),[z,ee]=(0,Q.useState)(null),[te,ne]=(0,Q.useState)(1),[B,re]=(0,Q.useState)(50),[ie,ae]=(0,Q.useState)(s),[oe,V]=(0,Q.useState)(null),{state:H,saveFilters:U,setSort:se,setAccentColor:W,setMapDocuments:ce}=zs(),le=H.filters.features.allOf,ue=H.filters.features.anyOf,de=H.filters.features.noneOf,fe=Xy(H.filters.timeline),pe=qy(H.filters.geo),me=Jy(H.filters.lens,H.filters.geo.includeUnlocated),G=H.filters.lens.ids,he=[...fe,...pe,...me],ge=H.filters.sort??Wy,_e=JSON.stringify({a:le,b:ue,c:de,d:he,i:G,s:ge}),ve=JSON.stringify({a:le,b:ue,c:de,d:he,s:ge}),K=Px(n.pathname).path,q=t??`context`,ye=q===`backends`,[be,xe]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{!ye||!e||pa(e).then(xe).catch(()=>xe([]))},[ye,e]);let Se=ye?oo(K,be):null,[Ce,we]=(0,Q.useState)(!1),Te=`${q}\0${K}`,[Ee,De]=(0,Q.useState)(Te);Ee!==Te&&(De(Te),we(!1));let Oe=o.get(`layer`)===`1`,ke=o.get(`layerId`)||null,[Ae,je]=(0,Q.useState)(null),[Me,Ne]=(0,Q.useState)(null),Pe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{Pe.current=Me},[Me]);let[Fe,Ie]=(0,Q.useState)(`left`),[Le,Re]=(0,Q.useState)([]),{openM1Drawer:ze,openM2Drawer:Be,goBack:Ve}=PT(),[He,Ue]=(0,Q.useState)([]),We=(0,Q.useMemo)(()=>{if(!Ae||K===`/`||Oe)return null;let e=K.split(`/`).filter(Boolean),t=Ae;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Ae,K,Oe]),Ge=We?.type===`canvas`?`canvas`:null,Ke=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{!e||!Ae||Oe||Ke.current===`${e}/${q}`&&(K!==`/`&&!We||oT(e,q,K))},[e,Ae,Oe,K,We,q]);let qe=(0,Q.useMemo)(()=>Oe||C===`workspace`||ie.length>0||ka(q)!==`directory`?[]:tD(Ae,K),[Ae,K,q,Oe,C,ie]),Je=Oe?null:K===`/`?Ae:We,Ye=`${q}\0${K}`,[Xe,Ze]=(0,Q.useState)(null),Qe=Xe?.key===Ye?Xe.views:bE(Je?.metadata),$e=Xe?.key===Ye?Xe.activeId:Qe[0]?.id??vE.id,et=Qe.find(e=>e.id===$e)??Qe[0]??vE,tt=ye?void 0:_E(et),nt=tt?[...le,tt]:le,rt=e=>{ne(1),Re([]),Ze({key:Ye,views:Qe,activeId:e})},it=(t,n)=>{n&&n!==$e&&(ne(1),Re([])),Ze({key:Ye,views:t,activeId:n??$e}),zi(e,K,{metadata:{...Je?.metadata??{},views:t}},q).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},at=Ge===`canvas`&&typeof We?.querySpec?.query==`string`?We.querySpec.query:``,ot=Ge===`canvas`?{label:We?.label,description:We?.description,color:We?.color}:null,{isPinned:st,pin:ct,unpin:lt,pins:ut}=BE(),dt=c?.name,ft=(0,Q.useMemo)(()=>dt&&Ge===`canvas`&&!Oe?{workspaceName:dt,treeName:q,path:K}:null,[dt,Ge,Oe,q,K]),pt=ft?st(ft):!1,mt=We?.id,ht=We?.label,gt=(0,Q.useCallback)(async()=>{if(ft)try{let e=ut.find(e=>e.workspaceName===ft.workspaceName&&e.treeName===ft.treeName&&e.path===ft.path);e?await lt(e.id):await ct({...ft,layerId:mt,label:ht})}catch(e){console.error(`Failed to update home pins:`,e)}},[ft,ut,ct,lt,mt,ht]),_t=e?`${e}://${K===`/`?``:K.replace(/^\//,``)}`:``,vt=Nm(c?.color)||null;(0,Q.useEffect)(()=>(W(vt),()=>W(null)),[vt,W]);let yt=(0,Q.useCallback)(async t=>{let n=G;if(t?.anyOf?.length&&ue.length&&(n=((await to(e,K,q,{limit:0,anyOf:ue,ids:G,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await to(e,K,q,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...le,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:ue,noneOf:de,filters:he,ids:n,queries:[...ie,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,K,q,_e,ie]);(0,Q.useEffect)(()=>{e&&(async()=>{d(!0);try{let t=await X.get(`${xr.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,l(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;i({title:`Error`,description:n,variant:`destructive`}),l(null)}finally{d(!1)}})()},[e,i]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&l(e=>e&&(t===e.name||t===e.id)&&e.status!==`active`?{...e,status:`active`}:e)};return window.addEventListener(`workspace:autostarted`,e),()=>window.removeEventListener(`workspace:autostarted`,e)},[]);let bt=(G?.length??0)>0&&!Oe&&!(Ce&&Se)&&ie.length<=1,{documents:xt,count:St,ready:Ct,setCue:wt,resync:Tt,rank:Et}=JE({workspaceRef:e,specs:(0,Q.useMemo)(()=>{let e={features:{allOf:nt,anyOf:ue,noneOf:de},filters:he};return C!==`workspace`&&(ka(q)===`directory`?e.directory={tree:q,path:K}:e.context=K),[{label:`scope`,spec:e}]},[ve,K,q,C,tt]),opts:(0,Q.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:bt}),Dt=bt&&Ct,Ot=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{Ot.current=Dt},[Dt]);let kt=ie.length===1?ie[0].trim():``;(0,Q.useEffect)(()=>{Ct&&Et(kt?{text:kt}:null,{limit:B,offset:(te-1)*B}).catch(()=>{})},[Ct,kt,B,te,Et]);let At=(G??[]).join(`,`);(0,Q.useEffect)(()=>{Ct&&wt(`lens`,{ids:G??[]}).catch(()=>{})},[Ct,At,wt,G]);let jt=Dt?xt:f,Mt=Dt?St:g,Nt=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{Nt.current=new Set(jt.map(e=>Number(e.id)))},[jt]);let Pt=H.geoSelection;(0,Q.useEffect)(()=>{ce(jt,c?.name??null)},[jt,c?.name,ce]),(0,Q.useEffect)(()=>()=>ce([]),[ce]);let Ft=(0,Q.useMemo)(()=>Pt?jt.filter(e=>Ly(e,Pt,H.filters.geo.includeUnlocated)):jt,[jt,Pt,H.filters.geo.includeUnlocated]),It=Sa(K,nt,{treeName:q,treeType:ka(q),scope:C,queries:ie,anyOf:ue,noneOf:de,filters:he,ids:G,layerId:Oe&&ke?ke:void 0}),Lt=JSON.stringify([e,It]),[Rt,zt]=(0,Q.useState)(``),[Bt,Vt]=(0,Q.useState)(!1),Ht=(0,Q.useRef)(!1),Ut=m||Bt||Rt!==Lt||Dt||!!Pt,Wt=(0,Q.useRef)(0),Gt=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{Wt.current++,Gt.current=null},[]);let Kt=(0,Q.useRef)(``),qt=(0,Q.useCallback)(async t=>{if(!e)return;if(pb(q,K)){Wt.current++,Gt.current=null,Kt.current=``,p([]),_(0),h(!1);return}if(Ot.current)return;let n=`${Ce&&Se?`${C}:unfiled`:C}:${tt??``}`,r=(G?.length??0)>0,a=iD(e,q,K,te,B,ie.join(`␟`),ve,Oe&&ke?ke:``,n),o=r&&a===Kt.current;Kt.current=a;let s=iD(e,q,K,te,B,ie.join(`␟`),_e,Oe&&ke?ke:``,n),c=`${s}\0${v}`;if(t?.silent&&Gt.current?.key===c){Gt.current.refreshPending=!0;return}let l=++Wt.current,u=t?.silent||r||v?void 0:nD.get(s);u&&(p(u.documents),_(u.totalCount),zt(Lt),h(!1)),(t?.silent??(o||!!u))||h(!0);let d={key:c,refreshPending:!1};Gt.current=d;try{let t;t=Ce&&Se?await vo(e,Se.driver,Se.address,{linked:!1,limit:B,offset:(te-1)*B}):Oe&&ke&&C!==`workspace`?await ua(e,q,ke,{limit:B,page:te,queries:ie,allOf:nt,anyOf:ue,noneOf:de,filters:he,ids:G,sortBy:ge.sortBy||void 0,order:ge.order}):await Na(e,K,nt,{limit:B,page:te,treeName:q,treeType:q===`directory`||q===`backends`?`directory`:`context`,queries:ie,anyOf:ue,noneOf:de,filters:he,ids:G,sortBy:ge.sortBy||void 0,order:ge.order,scope:C,debug:v&&ie.length>0,debugLimit:200});let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&nD.set(s,{documents:n,totalCount:i}),l!==Wt.current)return;let a=t.debug,c=a?.imageDistances??a?.distances??null;b(c?{query:ie[ie.length-1]??``,distances:c}:null),p(o?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),_(i),zt(Lt)}catch(e){if(l!==Wt.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),p([]),_(0)}finally{Gt.current===d&&(Gt.current=null),l===Wt.current&&h(!1),l===Wt.current&&d.refreshPending&&qt({silent:!0})}},[e,K,q,ke,Oe,te,B,c?.status,ie,_e,C,Ce,v,tt]);(0,Q.useEffect)(()=>{qt()},[qt]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Ne({treeName:n.treeName||`context`,path:Mx(n.path||`/`)}),Ie(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,q,K]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;if(!(n?.workspaceName&&n.workspaceName!==e)&&(e&&sD(e,n),RE(LE(n),{tree:q,kind:ka(q),path:K,wholeWorkspace:C===`workspace`}))){if(e&&aD(e,q,K),Ot.current){Tt();return}qt({silent:!0})}};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[qt,e,K,q,C,Tt]);let Jt=c?.name,Yt=c?.id;(0,Q.useEffect)(()=>{if(!e||!Jt&&!Yt)return;let t=[Jt,Yt].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>hd.emit(`subscribe`,{channel:e}));n();let r=hd.on(`connect`,n),i=new Map,a=!1,o=()=>{Di(e).then(e=>{a||(i=NE(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,Ot.current){Tt();return}qt({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=PE(t,n,i);oD(e,r);let a={tree:q,kind:ka(q),path:K,wholeWorkspace:C===`workspace`},f=Pe.current;f&&RE(r,{tree:f.treeName,kind:ka(f.treeName),path:f.path})&&(u=f),RE(r,a,Nt.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.inserted.batch`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>hd.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>hd.off(e,t))}},[e,Yt,Jt,q,K,C,qt,Tt]);let Xt=`${K}\0${q}\0${ke??``}\0${C}`,[Zt,Qt]=(0,Q.useState)(Xt);Zt!==Xt&&(Qt(Xt),ne(1),V(null));let $t=`${K}\0${q}\0${ke??``}`,[en,tn]=(0,Q.useState)($t);en!==$t&&(tn($t),w(`path`));let nn=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;M(n),A({parentPath:e,captureView:t})},rn=o.get(`createCanvas`)===`1`,[an,on]=(0,Q.useState)(!1);an!==rn&&(on(rn),rn&&nn(K,!1)),(0,Q.useEffect)(()=>{if(!rn)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}${n.hash}`,{replace:!0})},[rn,K]);let sn=(0,Q.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let i=t.toString();r(`${n.pathname}${i?`?${i}`:``}${n.hash}`)},[n.pathname,n.search,n.hash,r]),cn=JSON.stringify([o.has(`q`),...s]),[ln,un]=(0,Q.useState)(cn);ln!==cn&&(un(cn),ae(s),ne(1));let dn=`${cn}\0${Ge??``}\0${at}\0${K}\0${oe??``}`,[fn,pn]=(0,Q.useState)(dn);fn!==dn&&(pn(dn),o.has(`q`)||s.length>0||Ge!==`canvas`||oe===K||(ae(at?[at]:[]),ne(1)));let mn=(0,Q.useCallback)(e=>{let t=e.trim();t&&(V(null),ae(e=>{if(e.includes(t))return e;let n=[...e,t];return sn(n),ne(1),n}))},[sn,V,ae,ne]),hn=(0,Q.useCallback)(e=>{ae(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&V(K),sn(n),ne(1),n})},[sn,K,V,ae,ne]),gn=ie.join(` `).trim(),_n=!!H.activeContextType&&(H.isDirty||gn!==(Ge===`canvas`?at:H.savedSearchQuery||``));!e&&Ae!==null&&je(null),(0,Q.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&Da(e,q),vi(e,q).then(i=>{!t&&a===n&&(r=!0,Ke.current=`${e}/${q}`,je(i))}).catch(()=>{!t&&a===n&&!r&&je(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==q||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=Ab(e,Yt);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,q,Yt]),!(e&&Ge===`canvas`&&!Oe)&&z!==null&&ee(null),(0,Q.useEffect)(()=>{let t=!1;if(!(!e||Ge!==`canvas`||Oe))return ra(e,K,q).then(e=>{t||ee(e)}).catch(()=>{t||ee(null)}),()=>{t=!0}},[e,K,q,Ge,Oe]);let vn=async()=>{if(c){E(!0);try{let t=await so(e||c.id);l(t),i({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;i({title:`Error`,description:t,variant:`destructive`})}finally{E(!1)}}},yn=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`Document from "${K}"`});try{await _i(e||c.id,[t],K,[],q,Dn,{trashIfOrphaned:!0}),aD(e||c.id,q,K),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document removed from workspace path.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},bn=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`Document from "${K}"`});try{await ai(e||c.id,[t],K,[],q,Dn),aD(e||c.id,q,K),p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Success`,description:`Document deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},xn=async t=>{if(!c)return;let n=a({title:`Removing…`,description:`${t.length} document(s) from "${K}"`});try{await _i(e||c.id,t,K,[],q,Dn,{trashIfOrphaned:!0}),aD(e||c.id,q,K),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},Sn=async t=>{if(!c)return;let n=a({title:`Deleting…`,description:`${t.length} document(s)`});try{await ai(e||c.id,t,K,[],q,Dn),aD(e||c.id,q,K),p(e=>e.filter(e=>!t.includes(e.id))),_(e=>Math.max(0,e-t.length)),n.done({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},Cn=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`Document and its backend copies`});try{let r=await La(e||c.id,[t]);if(r.failed?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}p(e=>e.filter(e=>e.id!==t)),_(e=>Math.max(0,e-1)),n.done({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},wn=async t=>{if(!c)return;let n=a({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await La(e||c.id,t),i=new Set(r.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);p(e=>e.filter(e=>!i.has(e.id))),_(e=>Math.max(0,e-i.size));let a=[r.successful?.length?`${r.successful.length} destroyed`:null,r.failed?.length?`${r.failed.length} failed`:null].filter(Boolean).join(`, `);r.failed?.length?n.fail({title:`Destroy incomplete`,description:a,variant:`destructive`}):n.done({title:`Destroyed`,description:a||`No documents destroyed`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},Tn=e=>{O({documentIds:e,operation:`copy`,sourcePath:K,sourceTreeName:q}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},En=e=>{O({documentIds:e,operation:`cut`,sourcePath:K,sourceTreeName:q}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Dn=ka(q),On=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??q,o=r.targetTreeType??Dn,s=r.move??D?.operation===`cut`,c=a({title:s?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let a=await Qr(e,t,n,i,o);if(a){aD(e,i,t);let a=r.sourceTreeName||D?.sourceTreeName,o=r.sourcePath||D?.sourcePath;if((r.move??D?.operation===`cut`)&&o&&a){let t=ka(a);await _i(e,n,o,[],a,t),aD(e,a,o),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:o,treeName:a}}))}c.done({title:`Success`,description:`${n.length} document(s) ${s?`moved`:`pasted`} to "${t}"`}),O(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await qt(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else c.done();return a}catch(e){return c.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},kn=async(t,n)=>{if(!e)return!1;try{let r=(await ya(e,n,t,q,Dn)).length>0;return r&&(kb(e,q,n),i({title:`Success`,description:`Imported ${t.length} document(s) to "${n}"`})),r}catch(e){return i({title:`Error`,description:e instanceof Error?e.message:`Failed to import documents`,variant:`destructive`}),!1}},An=async()=>{if(!c||Mt===0||Ut||Ht.current||window.prompt(`Type PURGE to permanently delete all ${Mt} matching documents across all pages.`)!==`PURGE`)return;Ht.current=!0,Vt(!0);let t=a({title:`Purging…`,description:`${Mt} matching document(s)`});try{let n=await pi(e||c.id,It,Mt);n.deleted===n.requested?t.done({title:`Success`,description:`${n.deleted} document(s) purged.`}):t.fail({title:`Purge incomplete`,description:`${n.deleted} of ${n.requested} document(s) purged. Refresh and review the remaining results before retrying.`})}catch(e){t.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}finally{aD(e||c.id,q,K),await qt({silent:!0}),Ht.current=!1,Vt(!1)}},jn=()=>nn(K,!0),Mn=async()=>{if(!(!e||!k||!j.trim())){P(!0);try{let t=j.trim(),n=k.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`,a={...H.filters,features:{...H.filters.features,allOf:nt}};await So(e,i,q,k.captureView?{metadata:{toolbox:a},querySpec:{features:a.features,filters:[...Xy(H.filters.timeline),...qy(H.filters.geo)],query:gn||void 0,sort:H.filters.sort?.sortBy?H.filters.sort:null}}:{}),A(null),Da(e,q);try{let t=await vi(e,q,{force:!0});je(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(Fx(e,i,q))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{P(!1)}}},Nn=async()=>{if(!(!e||Ge!==`canvas`)){I(!0);try{let t=z||await To(e,K,q);ee(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)}}},Pn=async()=>{if(z){I(!0);try{await $r(z.code),ee(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:q}})),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)}}},Fn=async()=>{if(!e||Ge!==`canvas`||K===`/`)return;let t=ot?.label||K.split(`/`).pop()||`canvas`,n=z?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){R(!0);try{if(z)await $r(z.code),ee(null);else if(We?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await na(e,K,!1,q);let n=K.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:q}})),r(Fx(e,a,q)),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{R(!1)}}},In=(0,Q.useCallback)(async t=>{if(!e||!Me)return;let n={treeName:q,path:K},r=Fe===`left`?n:Me,o=Fe===`left`?Me:n,s=Fe===`left`?Le:He;if(s.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let c=ka(o.treeName),l=a({title:t?`Moving…`:`Copying…`,description:`${s.length} document(s) → "${o.path}"`});try{if(!await Qr(e,o.path,s,o.treeName,c)){l.done();return}if(aD(e,o.treeName,o.path),t){let t=ka(r.treeName);await _i(e,s,r.path,[],r.treeName,t),aD(e,r.treeName,r.path)}[r,o].forEach(t=>window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t.path,treeName:t.treeName}}))),l.done({title:t?`Moved`:`Copied`,description:`${s.length} document(s) → "${o.path}"`})}catch(e){l.fail({title:`Error`,description:e instanceof Error?e.message:`Transfer failed`,variant:`destructive`})}},[e,Me,Fe,q,K,Le,He,i,a]);if((0,Q.useEffect)(()=>{if(!Me)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),In(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Me,In]),u)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!c)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let Ln=Ge===`canvas`&&!Oe&&!!We,Rn=!Ln&&!ye&&Je?(0,$.jsx)(SE,{views:Qe,activeId:$e,onSelect:rt,onSave:it,accentColor:Nm(c.color),onOpenToSide:e=>{Ne({treeName:q,path:K,viewId:e}),Ie(`right`)}}):void 0,zn=Se||c.status!==`active`?(0,$.jsxs)($.Fragment,{children:[Se&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{we(!Ce),ne(1)},"aria-pressed":Ce,className:J(`min-h-10 rounded-md border px-2 text-xs`,Ce&&`bg-warning/15 text-warning`),children:`Unfiled only`}),c.status!==`active`&&(0,$.jsx)(`button`,{type:`button`,onClick:vn,disabled:T,className:`min-h-10 rounded-md border px-2 text-xs`,children:T?`Starting…`:`Start`})]}):void 0,Bn=pb(q,K)?K===`/Trash`?(0,$.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,$.jsx)(dE,{workspaceName:e||c.id})}):(0,$.jsx)(sE,{workspace:e||c.id,path:K,onNavigate:t=>r(Fx(e,t,`backends`))},e):(0,$.jsx)(hE,{navigationTabs:Rn,navigationActions:zn,onBack:Ve,accentColor:Nm(c.color),urlType:Oe?ka(q)===`directory`?`${q}-layer`:`context-layer`:Ge===`canvas`?`canvas`:ka(q)===`directory`?q:`context`,urlDisplay:_t,contextPath:K,treeName:q,workspaceId:e||c.id,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,documentSchema:tt,documents:Ft,isLoading:m,totalCount:Mt,currentPage:te,pageSize:B,onPageChange:ne,onPageSizeChange:e=>{re(e),ne(1)},onRemoveDocument:K===`/`?void 0:yn,onDeleteDocument:bn,onDestroyDocument:Cn,onRemoveDocuments:K===`/`?void 0:xn,onDeleteDocuments:Sn,onDestroyDocuments:wn,onCopyDocuments:Tn,onCutDocuments:En,onPasteDocuments:ye?void 0:On,onImportDocuments:ye?void 0:kn,onSelectionChange:Re,onBrowseTree:()=>Be(`workspaces`,`detail`,e??null),onBrowseWorkspaces:()=>ze(`workspaces`),onNavigatePath:t=>r(Fx(e,t,q)),folders:qe,onOpenFolder:t=>r(Fx(e,Mx(t),q)),scope:C,onScopeChange:w,pastedDocumentIds:D?.documentIds,linkTree:Ae,onPurgeDocuments:ye?void 0:An,disablePurgeDocuments:Ut,canvasInfo:ot??void 0,isCanvasPinned:pt,onTogglePinCanvas:ft?gt:void 0,onSaveAsCanvas:Ae&&Ge!==`canvas`&&!Oe&&!ye?jn:void 0,onShareCanvas:Ge===`canvas`&&!Oe?Nn:void 0,onUnshareCanvas:z?Pn:void 0,onDeleteCanvas:Ge===`canvas`&&!Oe?Fn:void 0,isSharingCanvas:F,isDeletingCanvas:L,isCanvasShared:!!z,isCanvasLocked:!!We?.locked,backendSearchQueries:ie,onBackendSearch:mn,serverSort:H.filters.sort,onServerSortChange:se,onRemoveBackendQuery:hn,canSaveChanges:_n,isSavingChanges:H.isSaving,onSaveChanges:U,contentBanner:v&&y?(0,$.jsx)(eD,{data:y,className:`mb-3`}):null,children:Ln&&We?(0,$.jsx)(iS,{workspaceId:e||c.id,treeName:q,path:K,layerId:We.id,querySpec:We.querySpec,metadata:We.metadata,isLocked:!!We.locked,fetchDocuments:H.isDirty?yt:void 0}):!ye&&et.kind===`columns`?(0,$.jsx)(OE,{documents:Ft,workspaceId:e||c.id,columns:et.columns??[],onColumnsChange:e=>it(Qe.map(t=>t.id===et.id?{...t,columns:e}:t))}):!ye&&et.kind===`app`&&et.app&&et.app!==`notes`?(0,$.jsx)(TE,{app:et.app,workspaceId:e||c.id,treeName:q,path:K}):null});return(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0`,children:[(0,$.jsx)(mE,{workspaceId:c.id,workspaceName:c.label||c.name},c.id),pb(q,K)&&(0,$.jsx)(Zg,{workspace:c.label||c.name,workspaceIcon:c.icon,tree:q,path:K,onBack:Ve,onBrowseTree:()=>Be(`workspaces`,`detail`,e||c.id),onBrowseWorkspaces:()=>ze(`workspaces`),onNavigatePath:t=>r(Fx(e,t,q)),accentColor:Nm(c.color)}),k&&(0,$.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,$.jsx)($w,{title:`New canvas`,onClose:()=>A(null),children:(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Mn()},className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,$.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:j,onChange:e=>M(e.target.value),onKeyDown:e=>{e.key===`Escape`&&A(null)},autoFocus:!0})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,$.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:k.parentPath===`/`?`/`:k.parentPath})]})]}),(0,$.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:k.captureView,onChange:e=>A({...k,captureView:e.target.checked})}),(0,$.jsxs)(`span`,{children:[`Capture the current view`,(0,$.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{type:`submit`,disabled:!j.trim()||N,children:N?`Creating…`:`Create canvas`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})})}),(0,$.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2`,children:[(0,$.jsx)(`div`,{"data-canvas-pane":!0,className:J(`flex-1 min-w-0 bg-background overflow-hidden`,Me&&(Fe===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||Ie(`left`)},children:Bn}),Me&&e&&(0,$.jsx)(dD,{workspaceName:e,workspaceLabel:c.label||c.name,workspaceIcon:c.icon,pane:Me,isFocused:Fe===`right`,clipboard:D,setClipboard:O,onFocus:()=>Ie(`right`),onSelectionChange:Ue,onNavigate:e=>Ne(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Ne(null),Ie(`left`),Ue([])}})]})]})}function uD(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 dD({workspaceName:e,workspaceLabel:t,workspaceIcon:n,pane:r,isFocused:i=!1,clipboard:a,setClipboard:o,onFocus:s,onSelectionChange:c,onNavigate:l,onClose:u}){let{openM1Drawer:d,openM2Drawer:f}=PT(),{showToast:p,showProgress:m}=Vr(),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(!1),[x,S]=(0,Q.useState)(0),[C,w]=(0,Q.useState)(1),[T,E]=(0,Q.useState)(50),D=ka(r.treeName),O=uD(h,r.path),k=O?.type===`canvas`,A=(0,Q.useMemo)(()=>D===`directory`?tD(h,r.path):[],[h,r.path,D]),j=r.viewId?bE(O?.metadata).find(e=>e.id===r.viewId)??null:null,M=`${e}://${r.path===`/`?``:r.path.replace(/^\//,``)}`,N=_E(j),P=(0,Q.useCallback)(async()=>{if(pb(r.treeName,r.path)){v([]),S(0),b(!1);return}let t=iD(e,r.treeName,r.path,C,T,``,N??``),n=nD.get(t);if(n){v(n.documents),S(n.totalCount);return}b(!0);try{let n=await Na(e,r.path,N?[N]:[],{limit:T,page:C,treeName:r.treeName,treeType:D}),i=n.payload||[],a=n.totalCount||n.count||0;v(i),S(a),nD.set(t,{documents:i,totalCount:a})}catch(e){p({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),v([]),S(0)}finally{b(!1)}},[e,r.path,r.treeName,D,T,C,p,N]);(0,Q.useEffect)(()=>{let t=!1,n=0,i=!1,a=(a=!1)=>{let o=++n;a&&Da(e,r.treeName),vi(e,r.treeName).then(e=>{!t&&o===n&&(i=!0,g(e))}).catch(()=>{!t&&o===n&&!i&&g(null)})};a(!1);let o=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==r.treeName||a(!n?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{t=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,r.treeName]),(0,Q.useEffect)(()=>{P()},[P]),(0,Q.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(sD(e,n),RE(LE(n),{tree:r.treeName,kind:ka(r.treeName),path:r.path})&&(aD(e,r.treeName,r.path),P()))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[P,e,r.treeName,r.path]);let F=(0,Q.useCallback)(async(t,n,i={})=>{let s=i.targetTreeName??r.treeName,c=i.targetTreeType??D,l=i.move??a?.operation===`cut`,u=m({title:l?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let r=await Qr(e,t,n,s,c);if(r){aD(e,s,t);let r=i.sourcePath||a?.sourcePath,c=i.sourceTreeName||a?.sourceTreeName;if((i.move??a?.operation===`cut`)&&r&&c){let t=ka(c);await _i(e,n,r,[],c,t),aD(e,c,r),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:r,treeName:c}}))}u.done({title:`Success`,description:`${n.length} document(s) ${l?`moved`:`pasted`} to "${t}"`}),o(null),await P(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:s}}))}else u.done();return r}catch(e){return u.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,r.treeName,D,P,m,a,o]),I=(0,Q.useCallback)(()=>{aD(e,r.treeName,r.path),P()},[e,r.treeName,r.path,P]),L=(0,Q.useCallback)(async t=>{let n=m({title:`Removing…`,description:`${t.length} document(s) from "${r.path}"`});try{await _i(e,t,r.path,[],r.treeName,D),I(),n.done({title:`Removed`,description:`${t.length} document(s) removed from "${r.path}"`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,I,m]),R=(0,Q.useCallback)(async t=>{let n=m({title:`Deleting…`,description:`${t.length} document(s)`});try{await ai(e,t,r.path,[],r.treeName,D),I(),n.done({title:`Deleted`,description:`${t.length} document(s) deleted.`})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,r.path,r.treeName,D,I,m]),z=(0,Q.useCallback)(async t=>{let n=m({title:`Destroying…`,description:`${t.length} document(s) and their backend copies`});try{let r=await La(e,t);if(r.failed?.length&&!r.successful?.length){n.fail({title:`Error`,description:r.failed[0].reason,variant:`destructive`});return}I();let i=`${r.successful?.length??0} document(s) destroyed${r.failed?.length?` · ${r.failed.length} failed`:``}.`;r.failed?.length?n.fail({title:`Destroy incomplete`,description:i,variant:`destructive`}):n.done({title:`Destroyed`,description:i})}catch(e){n.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,I,m]);return(0,$.jsxs)(`div`,{className:J(`relative flex-1 min-w-0 rounded-(--sheet-radius) border bg-background overflow-hidden`,i?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||s()},children:[u&&(0,$.jsx)(`button`,{type:`button`,onClick:u,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),pb(r.treeName,r.path)?r.path===`/Trash`?(0,$.jsx)(`div`,{className:`h-full overflow-auto p-4`,children:(0,$.jsx)(dE,{workspaceName:e})}):(0,$.jsx)(sE,{workspace:e,path:r.path,onNavigate:l||(()=>{})}):(0,$.jsx)(hE,{frameContent:!1,onBrowseWorkspaces:()=>d(`workspaces`),onBrowseTree:()=>f(`workspaces`,`detail`,e),urlType:k?`canvas`:D===`directory`?r.treeName:`context`,urlDisplay:M,contextPath:r.path,treeName:r.treeName,workspaceId:e,workspaceLabel:t,workspaceIcon:n,documentSchema:N,documents:_,isLoading:y,totalCount:x,currentPage:C,pageSize:T,onPageChange:w,onPageSizeChange:e=>{E(e),w(1)},onRemoveDocument:r.path===`/`?void 0:e=>L([e]),onRemoveDocuments:r.path===`/`?void 0:L,onDeleteDocument:e=>R([e]),onDeleteDocuments:R,onDestroyDocument:e=>z([e]),onDestroyDocuments:z,onCopyDocuments:e=>{o({documentIds:e,operation:`copy`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{o({documentIds:e,operation:`cut`,sourcePath:r.path,sourceTreeName:r.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:r.treeName===`backends`?void 0:F,onSelectionChange:c,pastedDocumentIds:a?.documentIds,linkTree:h,folders:A,onOpenFolder:l,onNavigatePath:l,canvasInfo:k?{label:O?.label,description:O?.description,color:O?.color}:void 0,children:j?.kind===`columns`?(0,$.jsx)(OE,{documents:_,workspaceId:e,columns:j.columns??[],onColumnsChange:()=>{},readOnly:!0}):j?.kind===`app`&&j.app&&j.app!==`notes`?(0,$.jsx)(TE,{app:j.app,workspaceId:e,treeName:r.treeName,path:r.path}):null})]})}function fD(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(!e)return;let t=!1,r=()=>{qr(e).then(r=>{t||n({ref:e,workspace:r})}).catch(()=>{})};return r(),window.addEventListener(`workspaces:refresh`,r),()=>{t=!0,window.removeEventListener(`workspaces:refresh`,r)}},[e]),t?.ref===e?t?.workspace:void 0}function pD(){let{workspaceName:e}=bl();return e?(0,$.jsx)(pE,{workspaceName:e,children:(0,$.jsx)(mD,{})}):(0,$.jsx)(`p`,{role:`alert`,className:`p-6`,children:`Workspace not specified.`})}function mD(){let{workspaceName:e=``,documentId:t=``,algo:n=``,checksum:r=``}=bl(),i=gl(),a=pl(),{goBack:o,openM1Drawer:s,openM2Drawer:c}=PT(),l=fD(e),u=!!n&&!!r,d=u?`${n}/${r}`:t,f=JSON.stringify([e,t,n,r]),p=Number(t),m=/^\d+$/.test(t)&&Number.isSafeInteger(p)&&p>0,h=u||m,[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(null),b=v?.identity===f?v:null,x=h&&(!b||b.revision!==g);(0,Q.useEffect)(()=>{let t=!1;if(h)return(u?ao(e,n,r):Ja(e,p)).then(e=>{t||y({identity:f,revision:g,document:e||null,missing:!e,error:``})}).catch(e=>{t||y({identity:f,revision:g,document:null,missing:e?.statusCode===404,error:e instanceof Error?e.message:`Unable to retrieve this document.`})}),()=>{t=!0}},[e,p,f,g,h,u,n,r]);let S={workspace:l?.label||e,workspaceIcon:l?.icon,path:`/`,tree:`context`,document:b?.document?Yr(b.document).title:`Document ${d}`,onBack:o,onBrowseWorkspaces:()=>s(`workspaces`),onBrowseTree:()=>c(`workspaces`,`detail`,e),onNavigatePath:t=>i(Fx(e,t,`context`))},C=a.hash.slice(1),w=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`].includes(C)?C:`view`;return(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[!b?.document&&(0,$.jsx)(Zg,{...S}),b?.document?(0,$.jsx)(By,{document:b.document,workspaceId:e,onChanged:()=>_(e=>e+1),navigation:S,initialTab:w,onTabChange:e=>i(`${a.pathname}${a.search}#${e}`,{replace:!0}),tabActions:(0,$.jsx)(Z,{variant:`ghost`,disabled:x,onClick:()=>_(e=>e+1),children:`Refresh`})},f):x?(0,$.jsx)(`p`,{role:`status`,className:`p-6 text-sm text-muted-foreground`,children:`Loading document…`}):(0,$.jsxs)(`div`,{role:`alert`,className:`space-y-2 p-6 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium`,children:b?.missing?`Document ${d} not found`:`Unable to load document`}),h&&(0,$.jsx)(Z,{variant:`outline`,onClick:()=>_(e=>e+1),children:`Retry`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:h?b?.missing?`This record is no longer available in this workspace. Subtree exports skip missing records and report their IDs.`:b?.error:`Document ID must be a positive integer.`})]})]})}function hD(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 gD={id:`sketch`,label:`Sketch`,icon:le,schemas:[Mi],canCreate:!0,canEdit:e=>e.schema===Mi,createUrl(e){let t=hD(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=hD(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},_D=[{kind:`message`,label:`New Message`,icon:b},{kind:`note`,label:`Note`,icon:Kn},{kind:`link`,label:`Link`,icon:_n},{kind:`todo`,label:`Todo`,icon:Vt},{kind:`identity`,label:`Identity`,icon:We},{kind:`sketch`,label:`Sketch`,icon:le},{kind:`plaintext`,label:`Plaintext file`,icon:nn},{kind:`file`,label:`File`,icon:Qe},{kind:`photo`,label:`Photo/Video`,icon:Ke},{kind:`existing`,label:`Existing document`,icon:En},{kind:`folder`,label:`Folder`,icon:st}];function vD(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?_D:_D.filter(e=>e.kind!==`photo`)}function yD({onSelect:e,variant:t=`list`,omit:n}){let r=vD().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,$.jsx)($.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex items-center gap-2 rounded-full bg-card px-3 py-1.5 text-sm font-medium shadow-elevation-3 transition-transform hover:scale-105`,children:[n,(0,$.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,$.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted`,children:[(0,$.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}function bD(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 xD({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,Q.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{role:`switch`,"aria-checked":e.enabled,"aria-disabled":i,"aria-label":`Geotag this document`,"aria-describedby":`${t}-hint`,tabIndex:i?-1:0,onClick:()=>!i&&e.setEnabled(!e.enabled),onKeyDown:t=>{i||(t.key===` `||t.key===`Enter`)&&(t.preventDefault(),e.setEnabled(!e.enabled))},className:J(`flex flex-1 items-center justify-between gap-3 select-none outline-none rounded focus-visible:ring-2 focus-visible:ring-ring`,i?`cursor-not-allowed opacity-50`:`cursor-pointer`),children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,$.jsx)(Yn,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,$.jsx)(tn,{className:J(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,$.jsx)(`div`,{className:J(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,$.jsx)(`div`,{className:J(`absolute top-[2px] h-4 w-4 rounded-full bg-background shadow-elevation-1 transition-transform`,e.enabled?`translate-x-[22px]`:`translate-x-[2px]`)})})]}),(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(!0),title:`Pick a point on the map`,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,$.jsx)(Ln,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.setManual(null),"aria-label":`Remove custom pin`,title:`Remove custom pin`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]}),(0,$.jsx)(`p`,{id:`${t}-hint`,className:J(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:bD(e)}),n&&(0,$.jsx)(dg,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}function SD(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 CD({title:e,icon:t,onClose:n,onSave:r,navigateAfterSave:i=!1,canSave:a=!1,saving:o=!1,saveProgress:s,successMessage:c=`Saved`,lockedWorkspaceName:l,fillParent:u=!1,fullWidthContent:d=!1,relationSubjectId:f,frame:p,children:m,maximized:h,onMaximizedChange:g}){let _=gl(),[v,y]=(0,Q.useState)(`portrait`),[b,x]=(0,Q.useState)(!1),S=h??b,C=e=>{x(e),g?.(e)},[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),A=o||O;Fp(()=>T(!1),w&&!A),Fp(()=>C(!1),S&&!w);let M=(0,Q.useRef)(null),N=l_(),{showSuccessToast:P,showErrorToast:F}=Wr(),I=N&&!u&&!S,[L,R]=(0,Q.useState)(!1),z=!u&&!S&&!p&&!L;(0,Q.useEffect)(()=>{w&&M.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[w]);let ee=async(e,t)=>{if(!(!r||A)){k(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>Qr(t.workspaceName,e,a,t.treeName,t.treeType))),P(c),n(),i&&_(SD({...t,path:e[0]}),{replace:!0})}catch(e){F(e instanceof Error?e.message:`Failed to save`)}finally{k(!1)}}},te=async e=>{if(!(!f||!l||e.targetIds.length===0)){D(!0);try{await go(l,f,e.predicate,e.targetIds,e.direction),P(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Rg(),T(!1)}catch(e){F(e instanceof Error?e.message:`Failed to create relations`)}finally{D(!1)}}},ne=S?w?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:I?void 0:v===`portrait`?{aspectRatio:`0.707 / 1`,height:`calc(var(--viewport-h) * 0.85)`,width:`auto`,maxWidth:`min(90vw, 100%)`,flexShrink:0}:{aspectRatio:`1 / 0.707`,width:`min(90vw, 900px)`,maxWidth:`100%`,height:`auto`,maxHeight:`calc(var(--viewport-h) * 0.85)`,flexShrink:0},B=!!(f&&l),re=r&&w&&(0,$.jsx)(ih,{onClose:()=>T(!1),onConfirm:ee,fixedWorkspaceName:l,saving:A||E,savingContent:s,tabs:B?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:B?te:void 0,relationWorkspaceName:l,relationExcludeIds:B?new Set([f]):void 0,sizeClassName:p?`h-full max-h-full w-full min-w-0 rounded-none border-0 shadow-none`:u?`h-full max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`:void 0}),ie=(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>y(e=>e===`portrait`?`landscape`:`portrait`),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground max-md:hidden touch-target`,"aria-label":`Toggle orientation`,title:`Toggle orientation`,children:(0,$.jsx)(j,{className:`h-4 w-4`})}),r&&(typeof m==`function`?(0,$.jsx)(`button`,{type:`button`,onClick:()=>T(!0),disabled:!a||A,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":A?`Saving…`:`Add relations / Link to…`,title:`Add relations / Link to…`,children:(0,$.jsx)(Zt,{className:`h-4 w-4`})}):(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:()=>T(!0),disabled:!a||A,children:A?`Saving…`:`Save / Link to…`})),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p&&!S?p.onToggleExpanded():C(!S),className:J(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`,!S&&!p&&`max-md:hidden`),"aria-label":p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,title:p&&!S?p.expanded?`Card size`:`Expand to full width`:S?`Restore`:`Maximize`,children:S||p?.expanded?(0,$.jsx)(lt,{className:`h-4 w-4`}):(0,$.jsx)(xn,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{type:`button`,onClick:n,disabled:A,className:J(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,typeof m==`function`&&`flex h-8 w-8 items-center justify-center`),"aria-label":`Close`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),ae=(0,$.jsxs)(`div`,{style:{...p&&!S?{width:`100%`,height:`100%`,minWidth:0}:ne,"--document-reading-width":S&&!d?`48rem`:`100%`},onAnimationEnd:e=>{z&&e.target===e.currentTarget&&R(!0)},className:J(`flex flex-col overflow-hidden`,p&&!S?`strip-document-card`:`rounded-(--card-radius) border bg-card shadow-elevation-4 transition-[width,height]`,u&&!S&&!p&&`w-full`,I&&`fixed inset-2 z-40 shadow-elevation-5`,z&&`animate-card-in`),children:[typeof m!=`function`&&(0,$.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,$.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate`,children:e})]}),ie]}),(0,$.jsx)(zg.Provider,{value:()=>C(!S),children:(0,$.jsx)(`div`,{className:J(`min-h-0 flex-1 overflow-y-auto`,S&&!d&&typeof m!=`function`&&`mx-auto w-full max-w-3xl`),children:p&&re?re:typeof m==`function`?m(ie):m})})]});return S?(0,Ip.createPortal)((0,$.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[ae,re&&(0,$.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:re})]}),document.body):(0,$.jsxs)($.Fragment,{children:[ae,!p&&re&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!A&&T(!1),"aria-hidden":!0}),(0,$.jsx)(`div`,{ref:M,className:`relative shrink-0 md:z-panel md:ml-2 md:pr-2 max-md:fixed max-md:bottom-2 max-md:left-2 max-md:right-2 max-md:top-2 max-md:z-card-overlay max-md:animate-fade-in`,children:re})]})]})}function wD({onClose:e,initialData:t,draftId:n}){let r=yS(void 0,void 0,`home-card:${n}`);return(0,Q.useEffect)(()=>{t?.title&&r.setTitle(t.title),t?.content&&r.setContent(t.content)},[]),(0,$.jsx)(CD,{title:`New Note`,icon:Kn,onClose:e,onSave:async e=>{let t=await r.save({mode:`workspace`,...e});return r.finish(),t},canSave:r.canSave,saving:r.saving,successMessage:`Note created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`qa-note-title`,value:r.title,onChange:e=>r.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,$.jsx)(Gu,{children:`Body`}),(0,$.jsx)(`div`,{className:`flex-1`,children:(0,$.jsx)(Ho,{kind:`markdown`,value:r.content,onChange:r.setContent,placeholder:`Write your note…`})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:r.tags,onChange:r.setTags})]}),(0,$.jsx)(Go,{...r,onRetry:r.retry}),(0,$.jsx)(xD,{geotag:r.geotag,idPrefix:`qa-note-geotag`})]})})}var TD=`data/schema/tab`,ED=`2.0`;function DD(e){try{return new URL(e),!0}catch{return!1}}function OD(){let[e,t]=(0,Q.useState)(``),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),c=R_(),l=e.trim(),u=DD(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:TD,schemaVersion:ED,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:Yo(i),...t?{geo:t}:{}}};return await ys(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 kD({onClose:e,initialData:t}){let n=OD();return(0,Q.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,$.jsx)(CD,{title:`New Link`,icon:_n,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-link-url`,children:`URL`}),(0,$.jsx)(Y,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-link-title`,children:`Title`}),(0,$.jsx)(Y,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsx)(xD,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function AD({onClose:e,initialData:t}){let n=J_();return(0,Q.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,$.jsx)(CD,{title:`New Todo`,icon:Vt,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsx)(Gv,{...n,idPrefix:`qa-todo`}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`qa-todo-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,$.jsx)(xD,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function jD({onClose:e,initialData:t}){let n=ey();return(0,Q.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,$.jsx)(CD,{title:`New Identity`,icon:We,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsx)(ay,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:n.tags,onChange:n.setTags})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`qa-identity-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]})]})})}var MD=3;function ND(e){return`${e.name}:${e.size}:${e.lastModified}`}function PD(e=[]){let[t,n]=(0,Q.useState)(()=>e.map(e=>({id:ND(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(t),o=(0,Q.useRef)(null),s=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,Q.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,Q.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,Q.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(ND(e))).map(e=>({id:ND(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,Q.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,Q.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,Q.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,Q.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await Ms(e),d=r===`backends`?await ks(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(MD,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 Ur(n,{...d,key:hs(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 Ns(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 Kr(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(MD,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 Hr(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 ys(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`)&&_s(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 FD(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ID(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 FD(e.file.size)}}function LD({item:e}){switch(e.status){case`done`:return(0,$.jsx)(oe,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,$.jsx)(z,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,$.jsx)(Rn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,$.jsx)(Yn,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function RD({item:e}){if(e.status===`queued`)return null;let t=e.status===`done`||e.status===`error`||e.status===`linking`?1:e.status===`checking`?0:e.progress;return(0,$.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:J(`h-full rounded-full transition-[width] duration-normal`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function zD({items:e,running:t,onRemove:n}){let r=e.filter(e=>e.status===`done`).length,i=e.filter(e=>e.status===`error`).length;return(0,$.jsx)($.Fragment,{children:e.length>0&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(Gu,{children:[e.length,` file(s)`,r>0&&(0,$.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,$.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,$.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(LD,{item:e}),(0,$.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,$.jsx)(`span`,{className:J(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:ID(e)}),!t&&e.status!==`done`&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}),(0,$.jsx)(RD,{item:e})]},e.id))})]})})}function BD({items:e,running:t,onCancel:n}){return(0,$.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,$.jsx)(zD,{items:e,running:!0,onRemove:()=>{}}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function VD(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return Xr(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var HD=`data/schema/file`,UD=`3.0`;function WD(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:VD(e),geotag:R_()}}function GD(e,t,n={}){let r=Yo(n.tags??[]),i=n.comment?.trim();return{schema:HD,schemaVersion:UD,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 KD=`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 qD({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`${t}-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`${t}-comment`,value:e.comment,onChange:t=>e.setComment(t.target.value),rows:3,placeholder:`Optional; searchable, and the only text a photo has`,className:KD}),n&&e.tags.length+e.comment.trim().length>0&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,$.jsx)(xD,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var JD={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 YD(e){return/^(image|video)\//.test(e.type)}async function XD(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
22
22
  
23
- `)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&&JD[o]||i;return s===e.type?e:new File([e],e.name,{type:s,lastModified:e.lastModified})}));return{kind:t.length>0&&t.every(YD)?`photo`:`file`,files:t}}function ZD({file:e}){let t=(0,Q.useRef)(null),[n,r]=(0,Q.useState)(!1);return(0,Q.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,$.jsx)(`div`,{className:`flex min-h-24 items-center justify-center overflow-hidden rounded-md border border-input bg-muted/30`,children:n?(0,$.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,$.jsx)(`video`,{ref:t,controls:!0,preload:`metadata`,"aria-label":e.name,onError:()=>r(!0),className:`max-h-64 max-w-full`}):(0,$.jsx)(`img`,{ref:t,alt:e.name,onError:()=>r(!0),className:`max-h-64 max-w-full object-contain`})})}function QD({onClose:e,initialData:t}){let n=(0,Q.useRef)(null),r=PD(t?.files),i=r.items.map(e=>e.file),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),{state:l}=zs(),u=WD(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,$.jsx)(CD,{title:`Upload File`,icon:Qe,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)=>GD(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,$.jsx)(BD,{items:r.items,running:r.running,onCancel:r.cancel}),successMessage:`File(s) uploaded`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:f,onClick:()=>n.current?.click(),className:J(`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,$.jsx)(Qe,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Drag & drop files here`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`or click to browse`}),(0,$.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=>YD(e.file)).map(e=>(0,$.jsx)(ZD,{file:e.file},e.id)),(0,$.jsx)(zD,{items:r.items,running:s,onRemove:r.removeItem}),(0,$.jsx)(qD,{fields:u,idPrefix:`qa-file`,multiple:i.length>1})]})})}function $D({onClose:e,initialData:t}){let n=PD(t?.files),r=(0,Q.useRef)(null),i=n.items.length>0,[a,o]=(0,Q.useState)(!1),{state:s}=zs(),c=WD(s.activeWorkspaceName),l=e=>{!a&&e&&n.addFiles([e])};return(0,$.jsx)(CD,{title:`Photo/Video`,icon:Ke,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)=>GD(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,$.jsx)(BD,{items:n.items,running:n.running,onCancel:n.cancel}),successMessage:`Upload saved`,children:(0,$.jsxs)(`div`,{className:J(`flex h-full flex-col gap-4 p-4`,!i&&`items-center justify-center`),children:[i?(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(ZD,{file:t}),(0,$.jsxs)(`div`,{className:`flex w-full items-center gap-2 rounded border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(Rn,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`flex-1 truncate`,children:t.name}),(0,$.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[(t.size/1024/1024).toFixed(1),` MB`]}),(0,$.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,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e))}),(0,$.jsx)(`div`,{className:`w-full shrink-0 space-y-4`,children:(0,$.jsx)(qD,{fields:c,idPrefix:`qa-photo`,multiple:n.items.length>1})})]}):(0,$.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,$.jsx)(Ke,{className:`h-8 w-8 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-sm`,children:`Open camera`})]}),(0,$.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 eO=`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 tO({onClose:e}){let{showSuccessToast:t,showErrorToast:n}=Wr(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(!1);return r?(0,$.jsx)(ih,{sizeClassName:eO,documentCount:r.length,saving:a,onClose:e,onConfirm:async(i,a)=>{o(!0);try{await Promise.all(i.map(e=>Qr(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,$.jsx)(Cg,{sizeClassName:eO,onConfirm:e=>{e.length&&i(e)},onClose:e})}function nO(){let e=qo(`new:home-card:`);try{return Object.keys(localStorage).filter(t=>t.startsWith(e)&&t.endsWith(`:home`)).filter(e=>{let t=JSON.parse(localStorage.getItem(e)||`null`)?.value;return t&&(t.title||t.content||t.comment||t.tags?.length)}).map(t=>t.slice(e.length,-5))}catch{return[]}}var rO=0;function iO(){return rO+=1,`card-${rO}`}function aO({initialKind:e,initialData:t,onInitialCardClose:n,onCardsOpenChange:r}){let[i,a]=(0,Q.useState)(!1),o=l_(),s=es(),c=!!(s?.state.t1Open||s?.state.addOpen),[l,u]=(0,Q.useState)(()=>e?[{id:`initial`,kind:e,initialData:t,noteDraftId:crypto.randomUUID()}]:nO().map(e=>({id:e,kind:`note`,noteDraftId:e}))),d=l.length>0,f=(0,Q.useRef)(r);(0,Q.useEffect)(()=>{f.current=r},[r]),(0,Q.useEffect)(()=>{f.current?.(d)},[d]),c&&i&&a(!1);let p=gl(),m=e=>{if(e===`sketch`){a(!1),p(gD.createUrl(null));return}let t=e===`note`?nO().find(e=>!l.some(t=>t.noteDraftId===e))||crypto.randomUUID():void 0;u(n=>[...n,{id:iO(),kind:e,noteDraftId:t}]),a(!1)},h=e=>{u(t=>t.filter(t=>t.id!==e)),e===`initial`&&n?.()},g=(0,$.jsxs)(`div`,{className:J(`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,$.jsx)(`div`,{className:J(`flex flex-col items-end gap-2 transition-all duration-fast`,i?`pointer-events-auto opacity-100`:`pointer-events-none translate-y-2 opacity-0`),children:(0,$.jsx)(yD,{variant:`stack`,omit:[`plaintext`,`folder`,`message`],onSelect:m})}),(0,$.jsx)(`div`,{className:`pointer-events-none flex w-16 justify-center`,children:(0,$.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,$.jsx)(G,{className:`h-5 w-5`}):(0,$.jsx)(sn,{className:`h-5 w-5`})})})]});return(0,$.jsxs)(`div`,{className:`relative flex h-full w-full flex-col`,children:[l.length>0&&(0,$.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,$.jsx)(wD,{draftId:e.noteDraftId,onClose:t,initialData:e.initialData},e.id);case`link`:return(0,$.jsx)(kD,{onClose:t,initialData:e.initialData},e.id);case`todo`:return(0,$.jsx)(AD,{onClose:t,initialData:e.initialData},e.id);case`identity`:return(0,$.jsx)(jD,{onClose:t,initialData:e.initialData},e.id);case`file`:return(0,$.jsx)(QD,{onClose:t,initialData:e.initialData},e.id);case`photo`:return(0,$.jsx)($D,{onClose:t,initialData:e.initialData},e.id);case`existing`:return(0,$.jsx)(tO,{onClose:t},e.id);case`sketch`:return null;case`folder`:case`message`:return null}})}),o?(0,Ip.createPortal)(g,document.body):g]})}function oO(e){let t=`${e.workspaceName}\0${e.treeName}\0${e.path}`,[n,r]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let n=!1;return ga(e.workspaceName,e.treeName).then(i=>{n||r({key:t,node:di(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 sO(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 cO=`application/x-canvas-pin`;function lO({pin:e,onUnpin:t,onMinimize:n,onDropPin:r}){let i=oO(e),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.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(cO);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,Q.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]),(0,$.jsxs)(`section`,{...d,className:a?`fixed inset-0 z-picker flex flex-col bg-background`:`flex flex-col rounded-(--card-radius) border bg-background overflow-hidden min-h-0 min-w-0 ${s?`ring-2 ring-primary/60`:``}`,children:[(0,$.jsxs)(`header`,{draggable:l,onDragStart:l?t=>{t.dataTransfer.setData(cO,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,$.jsx)(T,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-hidden":!0}),m&&(0,$.jsx)(`div`,{className:`w-1 h-5 rounded-full shrink-0`,style:{backgroundColor:m}}),(0,$.jsx)(gt,{className:`w-4 h-4 shrink-0 text-primary`}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:p}),(0,$.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono`,children:[e.workspaceName,`://`,e.path.replace(/^\//,``)]})]}),n&&(0,$.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,$.jsx)(ue,{className:`w-3.5 h-3.5`})}),(0,$.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,$.jsx)(lt,{className:`w-3.5 h-3.5`}):(0,$.jsx)(xn,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(Nu,{to:sO(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,$.jsx)(Ht,{className:`w-3.5 h-3.5`})}),(0,$.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,$.jsx)(ee,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0`,children:[i.state===`loading`&&(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}),i.state===`missing`&&(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 px-4 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This canvas is no longer available.`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`It may have been renamed, moved or deleted.`}),(0,$.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,$.jsx)(iS,{workspaceId:e.workspaceName,treeName:e.treeName,path:e.path,layerId:i.node.id,querySpec:i.node.querySpec,metadata:i.node.metadata,readOnly:!0})]})]})}function uO(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 dO(e,t){return e.minimized===!0||t.has(e.id)}function fO(e){return e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`}function pO({pins:e,onRestore:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(e.length);return i!==e.length&&(a(e.length),e.length===0&&r(!1)),e.length===0?null:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`pointer-events-none absolute bottom-0 left-0 right-0 z-40 max-md:hidden`,children:(0,$.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,$.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),title:`Restore ${fO(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,$.jsx)(gt,{className:`h-3.5 w-3.5 shrink-0 text-primary`}),(0,$.jsx)(`span`,{className:`truncate`,children:fO(e)})]},e.id))})}),n&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-drawer md:hidden`,onClick:()=>r(!1),"aria-hidden":!0}),(0,$.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,$.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,$.jsx)(gt,{className:`h-4 w-4 shrink-0 text-primary`}),(0,$.jsx)(`span`,{className:`truncate`,children:fO(e)})]},e.id))})]}),(0,$.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,$.jsx)(gt,{className:`h-5 w-5`}),(0,$.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 mO(){let{pins:e,unpin:t,movePin:n,setMinimized:r,isLoading:i}=BE(),{showErrorToast:a}=Wr(),[o,s]=(0,Q.useState)(new Set),c=(0,Q.useRef)(e);(0,Q.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,Q.useCallback)(e=>{s(e?new Set(c.current.filter(e=>!e.minimized).map(e=>e.id)):new Set)},[]),f=e.filter(e=>!dO(e,o)),p=e.filter(e=>dO(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,$.jsxs)(`div`,{className:`relative h-full`,children:[(0,$.jsx)(`div`,{className:`h-full overflow-y-auto`,children:i?(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}):(0,$.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,$.jsx)(lO,{pin:e,onUnpin:()=>{t(e.id)},onMinimize:()=>l(e.id),onDropPin:(t,n)=>m(t,e,n)},e.id))})}),(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,children:(0,$.jsx)(aO,{onCardsOpenChange:d})}),(0,$.jsx)(pO,{pins:p,onRestore:u})]})}function hO(){return(0,$.jsx)(`div`,{className:`h-full w-full`,"aria-hidden":!0})}var gO=`share-target-inbox`,_O={"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 vO(e){let t=await caches.open(gO),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 XD(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||(xO(o)?o:``);return s?{kind:`link`,data:{url:s,title:n.title}}:{kind:`note`,data:{title:n.title,content:n.text}}}var yO=new Map;function bO(e){let t=yO.get(e);return t||(t=vO(e),yO.set(e,t),t.finally(()=>setTimeout(()=>yO.delete(e),6e4)).catch(()=>{})),t}function xO(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 SO(){let[e]=zu(),t=gl(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null);(0,Q.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 bO(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,$.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 px-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:_O[i]??_O.expired}),(0,$.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,$.jsx)(`button`,{type:`button`,onClick:o,className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Go to Canvas`})]}):n?(0,$.jsx)(aO,{initialKind:n.kind,initialData:n.data,onInitialCardClose:o}):(0,$.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 CO(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 wO(e,t,n=`An error occurred`){return console.error(t,e),CO(e,n)}function TO(){let e=gl(),[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(`context`),[h,g]=(0,Q.useState)(`/`),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(`/`),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(!1),[D,O]=tT(),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(null),{showToast:N}=Vr();(0,Q.useEffect)(()=>{hd.isConnected()||(console.log(`Socket not connected, attempting to connect...`),hd.reconnect())},[]);let P=(0,Q.useCallback)(async()=>{try{o(!0);let[e,t]=await Promise.all([ps(),Ni()]),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===C);(!C||!e)&&w(a[0].id)}else w(``);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),N({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[C,N]);(0,Q.useEffect)(()=>{P()},[P]),(0,Q.useEffect)(()=>{let e=()=>hd.emit(`subscribe`,{channel:`context`}),t=()=>hd.emit(`unsubscribe`,{channel:`context`}),r=hd.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])=>hd.on(e,t)),()=>{console.log(`Unsubscribing from context events`),t(),r?.(),c.forEach(([e,t])=>hd.off(e,t))}},[]);let F=async t=>{if(t.preventDefault(),!h.trim()||!C||!l.trim()){N({title:`Missing Fields`,description:`Context ID, Context URL and Workspace are required.`,variant:`destructive`});return}E(!0);try{let t={id:l,name:d.trim()||void 0,url:h,description:_.trim()||void 0,metadata:{ui:{color:y}},workspaceId:C,baseUrl:x||void 0,treeType:p},n=await xs(t);u(``),f(``),g(`/`),v(``),b(null),S(`/`),await P(),N({title:`Success`,description:`Context created successfully`}),O(!1),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e(`/contexts/${n.id}`)}catch(e){let t=wO(e,`Context creation error:`,`Failed to create context`);N({title:`Error`,description:t,variant:`destructive`})}finally{E(!1)}},I=async e=>{let n=t.find(t=>t.id===e);if(n&&n.url&&(n.url.endsWith(`/default`)||n.url.includes(`://default`))){N({title:`Error`,description:`Cannot delete the default context`,variant:`destructive`});return}M(e)},L=async()=>{if(j)try{await As(j),n(e=>e.filter(e=>!ss(e,{id:j}))),N({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`}N({title:`Error`,description:t,variant:`destructive`})}finally{M(null)}},R=t=>{let n=t.isShared||t.type===`shared`;e(n?`/contexts/${t.id}?ownerId=${encodeURIComponent(t.userId)}`:`/contexts/${t.id}`)},z=e=>{A(e)},ee=async e=>{if(e.preventDefault(),k)try{n(e=>e.map(e=>e.id===k.id&&e.userId===k.userId?k:e)),N({title:`Success`,description:`Context updated successfully (mock update)`}),A(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update context`;N({title:`Error`,description:t,variant:`destructive`})}},te=(0,Q.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:ne,sort:B,toggleSort:re}=Ig(t.filter(e=>e!=null),te);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`Contexts`,description:`Create and manage contexts in your workspaces. View contexts shared with you.`,actions:!D&&(0,$.jsxs)(Z,{onClick:()=>O(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create context`,title:`Create context`,children:[(0,$.jsx)(sn,{className:`h-4 w-4 sm:mr-2`}),(0,$.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Context`})]})}),D&&(0,$.jsx)($w,{title:`Create New Context`,onClose:()=>O(!1),children:(0,$.jsxs)(`form`,{onSubmit:F,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`workspace`,className:`block text-sm font-medium mb-1`,children:`Workspace`}),(0,$.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:C,onChange:e=>w(e.target.value),disabled:T||r.length===0,children:[r.length===0&&(0,$.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),r.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label||e.name},`${e.owner}-${e.id}`))]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`newContextId`,className:`block text-sm font-medium mb-1`,children:`Context ID`}),(0,$.jsx)(Y,{id:`newContextId`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g., my-new-context`,disabled:T})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,$.jsx)(ah,{id:`url`,value:h,onChange:g,placeholder:`e.g., /project/path/resource`,disabled:T,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&&w(n.id)}})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`baseUrl`,className:`block text-sm font-medium mb-1`,children:`Base URL (Optional)`}),(0,$.jsx)(ah,{id:`baseUrl`,value:x,onChange:S,format:`path`,placeholder:`e.g., /base/path`,disabled:T,pickerTitle:`Base path…`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`description`,className:`block text-sm font-medium mb-1`,children:`Description (Optional)`}),(0,$.jsx)(Y,{id:`description`,value:_,onChange:e=>v(e.target.value),placeholder:`Description`,disabled:T})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`contextColor`,className:`block text-sm font-medium mb-1`,children:`Color (Optional)`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Y,{id:`contextColor`,type:`color`,value:y||`#808080`,onChange:e=>b(e.target.value),className:`h-10 w-16 p-1`,disabled:T}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:T||y===null,onClick:()=>b(null),children:`Use inherited color`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:y===null?`Uses the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`contextName`,className:`block text-sm font-medium mb-1`,children:`Name (Optional)`}),(0,$.jsx)(Y,{id:`contextName`,value:d,onChange:e=>f(e.target.value),placeholder:`My Context`,disabled:T})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`treeType`,className:`block text-sm font-medium mb-1`,children:`Tree`}),(0,$.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:T,children:[(0,$.jsx)(`option`,{value:`context`,children:`Context tree`}),(0,$.jsx)(`option`,{value:`directory`,children:`Directory tree`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Which workspace tree this context navigates.`})]})]}),(0,$.jsxs)(Z,{type:`submit`,disabled:T||!h.trim()||!C||!l.trim(),children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),`Create Context`]})]})}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Contexts & Shared Contexts`}),a&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading contexts...`}),s&&(0,$.jsx)(`div`,{className:`text-center text-destructive`,children:(0,$.jsx)(`p`,{children:s})}),!a&&!s&&t.length===0&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No contexts found. Create one above.`}),t.length>0&&(0,$.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,$.jsxs)(Dg,{children:[(0,$.jsx)(Og,{children:(0,$.jsxs)(jg,{children:[(0,$.jsx)(Fg,{label:`Type`,sortKey:`type`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`ID`,sortKey:`id`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Owner`,sortKey:`owner`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Context URL`,sortKey:`url`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Workspace ID`,sortKey:`workspaceId`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Base URL`,sortKey:`baseUrl`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Path`,sortKey:`path`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Locked`,sortKey:`locked`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Created`,sortKey:`created`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Updated`,sortKey:`updated`,sort:B,onSort:re}),(0,$.jsx)(Mg,{className:`text-right`,children:`Actions`})]})}),(0,$.jsx)(kg,{children:ne.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,$.jsxs)(jg,{children:[(0,$.jsx)(Ng,{children:r?(0,$.jsxs)(`div`,{className:`flex items-center gap-1 text-info`,title:`Shared with you (${a})`,children:[(0,$.jsx)(jn,{className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`text-xs`,children:`Shared`})]}):(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Owned`})}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.id||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,title:r?`Owned by: ${i}`:`You are the owner`,children:i}),(0,$.jsx)(Ng,{className:`font-mono text-sm max-w-xs truncate`,title:e.url||`-`,children:e.url||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.workspaceId||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.baseUrl||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.path||`-`}),(0,$.jsx)(Ng,{children:e.locked?`Yes`:`No`}),(0,$.jsx)(Ng,{children:t}),(0,$.jsx)(Ng,{children:n}),(0,$.jsx)(Ng,{className:`text-right`,children:(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[!r&&(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>z(e),title:`Edit Context`,children:(0,$.jsx)(rn,{className:`h-4 w-4`})}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>R(e),title:r?`Open Shared Context`:`Open Context Details`,children:(0,$.jsx)(_t,{className:`h-4 w-4`})}),!r&&(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>I(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,$.jsx)(ot,{className:`h-4 w-4`})})]})})]},`${e.userId}-${e.id}`)})})]})})]}),k&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Edit Context`}),(0,$.jsxs)(`form`,{onSubmit:ee,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-context-id`,className:`block text-sm font-medium mb-1`,children:`Context ID (read-only)`}),(0,$.jsx)(Y,{id:`edit-context-id`,value:k.id,disabled:!0,className:`bg-muted`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-context-url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,$.jsx)(ah,{id:`edit-context-url`,value:k.url,onChange:e=>A(t=>t?{...t,url:e}:null),placeholder:`workspace://path or /path`,pickerTitle:`Context URL path…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Use format: workspace://path or /path for current workspace`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-base-url`,className:`block text-sm font-medium mb-1`,children:`Base URL (optional)`}),(0,$.jsx)(ah,{id:`edit-base-url`,value:k.baseUrl||``,onChange:e=>A(t=>t?{...t,baseUrl:e||null}:null),format:`path`,placeholder:`/base/path`,pickerTitle:`Base path…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Restricts context navigation to this base path`})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{type:`submit`,children:`Save Changes`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})]}),(0,$.jsx)(Ir,{open:j!==null,onOpenChange:e=>!e&&M(null),children:(0,$.jsxs)(Or,{children:[(0,$.jsxs)(Fr,{children:[(0,$.jsx)(Cr,{children:`Delete Context`}),(0,$.jsx)(Sr,{children:`Are you sure you want to delete this context? This action cannot be undone.`})]}),(0,$.jsxs)(Mr,{children:[(0,$.jsx)(Pr,{children:`Cancel`}),(0,$.jsx)(jr,{onClick:L,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:`Delete`})]})]})})]})}function EO(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 DO(){let{contextId:e}=bl(),t=pl(),n=gl(),r=new URLSearchParams(t.search).get(`ownerId`)||void 0,i=(0,Q.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,showProgress:o}=Vr(),{state:s,saveFilters:c,setSort:l,setAccentColor:u,setMapDocuments:d}=zs(),{openM1Drawer:f,openM2Drawer:p,goBack:m}=PT(),h=s.filters.features.allOf,g=s.filters.features.anyOf,_=s.filters.features.noneOf,v=[...Xy(s.filters.timeline),...qy(s.filters.geo),...Jy(s.filters.lens,s.filters.geo.includeUnlocated)],y=JSON.stringify({a:h,b:g,c:_,d:v,ids:s.filters.lens.ids,sort:s.filters.sort,geoSelection:s.geoSelection,includeUnlocated:s.filters.geo.includeUnlocated}),b=(0,Q.useMemo)(()=>JSON.parse(y),[y]),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!0),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)([]),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(0),[N,P]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(1),[L,R]=(0,Q.useState)(50),[z,ee]=(0,Q.useState)(i),[te,ne]=(0,Q.useState)(!1),[B,re]=(0,Q.useState)(null),[ie,ae]=(0,Q.useState)(!1),oe=(0,Q.useRef)(!1),V=B?.id===x?.id&&B?.url===x?.url?B?.path:null,H=new URLSearchParams(t.search).get(`layer`),U=!!r,se=fD(U?void 0:x?.workspaceName||x?.workspaceId),W=x?EO(x.url,x.workspaceName):`/`,ce=H?`context-layer`:`context`,le=!s.liveEnabled&&typeof x?.metadata?.toolboxSearchQuery==`string`?x.metadata.toolboxSearchQuery:``,ue=U?null:x?.workspaceName??null,[de,fe]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!ue)return;let e=!1;return vi(ue,lo).then(t=>{e||fe({key:ue,tree:t})}).catch(()=>{e||fe({key:ue,tree:null})}),()=>{e=!0}},[ue]);let pe=ue&&de?.key===ue?de.tree:null,me=!H&&!U&&pe?W===`/`?pe:di(pe,W):null,G=`${x?.workspaceName??``}\0${W}`,[he,ge]=(0,Q.useState)(null),_e=he?.key===G?he.views:bE(me?.metadata),ve=he?.key===G?he.activeId:_e[0]?.id??vE.id,K=_e.find(e=>e.id===ve)??_e[0]??vE,q=_E(K),ye=e=>{I(1),ge({key:G,views:_e,activeId:e})},be=(e,t)=>{t&&t!==ve&&I(1),ge({key:G,views:e,activeId:t??ve}),x?.workspaceName&&zi(x.workspaceName,W,{metadata:{...me?.metadata??{},views:e}},lo).catch(()=>{a({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},xe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>xe.current?.abort(),[]);let Se=(0,Q.useCallback)(async()=>{if(!e)return;xe.current?.abort();let t=new AbortController;xe.current=t,A(!0);try{let n=await Ss(e,q?[...b.a,q]:b.a,b.d,{...b.sort,geoSelection:b.geoSelection,includeUnlocated:b.includeUnlocated,ids:b.ids,signal:t.signal,limit:L,page:F,queries:z.length?z:void 0,anyOf:b.b,noneOf:b.c,applyContextSpec:!1},r);if(t.signal.aborted)return;O(n),M(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`}),O([]),M(0)}finally{t.signal.aborted||A(!1)}},[e,F,L,r,z,b,a,q]),Ce=(0,Q.useCallback)(async()=>{if(e){w(!0);try{let t=U?await Cs(e,r):await Cs(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)||``;S({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}),E(null)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch context ${e}`;E(n),S(null),a({title:`Error`,description:n,variant:`destructive`})}w(!1)}},[e,r,U,a]);(0,Q.useEffect)(()=>{Ce()},[Ce]);let we=Nm(x?.color)||null;(0,Q.useEffect)(()=>(u(we),()=>u(null)),[we,u]);let Te=s.geoSelection,Ee=x?.workspaceName||x?.workspaceId||null;(0,Q.useEffect)(()=>{d(D,Ee)},[D,Ee,d]),(0,Q.useEffect)(()=>()=>d([]),[d]);let De=(0,Q.useMemo)(()=>Te?D.filter(e=>Ly(e,Te,s.filters.geo.includeUnlocated)):D,[D,Te,s.filters.geo.includeUnlocated]),Oe=x?.id,ke=x?.url;(0,Q.useEffect)(()=>{Oe&&Se()},[Oe,ke,Se]),(0,Q.useEffect)(()=>{let e=()=>Se();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[Se]);let[Ae,je]=(0,Q.useState)(y);Ae!==y&&(je(y),I(1));let[Me,Ne]=(0,Q.useState)(e);Me!==e&&(Ne(e),I(1),ne(!1));let[Pe,Fe]=(0,Q.useState)(i);Pe!==i&&(Fe(i),ee(i),I(1));let[Ie,Le]=(0,Q.useState)({urlSearchQueries:i,ignoreSavedSearch:te,savedContextSearchQuery:le});(Ie.urlSearchQueries!==i||Ie.ignoreSavedSearch!==te||Ie.savedContextSearchQuery!==le)&&(Le({urlSearchQueries:i,ignoreSavedSearch:te,savedContextSearchQuery:le}),!new URLSearchParams(t.search).has(`q`)&&!i.length&&!te&&(ee(le?[le]:[]),I(1)));let Re=(0,Q.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.hash}`)},[t.pathname,t.search,t.hash,n]),ze=(0,Q.useCallback)(e=>{let t=e.trim();if(!t)return;ne(!1);let n=z.includes(t)?z:[...z,t];ee(n),Re(n)},[z,Re]),Be=(0,Q.useCallback)(e=>{let t=e<0?[]:z.filter((t,n)=>n!==e);t.length===0&&ne(!0),ee(t),Re(t)},[z,Re]),Ve=(z[0]||``).trim(),He=!!s.activeContextType&&(s.isDirty||Ve!==(s.savedSearchQuery||le||``));(0,Q.useEffect)(()=>{if(!e)return;let t=`context:${r?`${r}/`:``}${e}`,n=()=>hd.emit(`subscribe`,{channel:t}),i=()=>hd.emit(`unsubscribe`,{channel:t}),a=hd.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)&&(S(e=>e?{...e,...r}:null),r.url&&Se())},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)&&(S(e=>e?{...e,url:i}:null),Se())},u=t=>{let n=t;(n?.contextId||n?.id||n?.context?.id)===e&&s(`doc:changed`,n)&&Se()},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])=>hd.on(e,t)),()=>{a(),i(),d.forEach(([e,t])=>hd.off(e,t))}},[e,r,Se]);let Ue=async e=>{if(x)try{await Es(x.id,[e],r,W),O(t=>t.filter(t=>t.id!==e)),M(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`})}},We=async e=>{if(x)try{await Os(x.id,[e],r,W),O(t=>t.filter(t=>t.id!==e)),M(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`})}},Ge=async e=>{if(x)try{await Es(x.id,e,r,W),O(t=>t.filter(t=>!e.includes(t.id))),M(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`})}},Ke=async e=>{if(x)try{await Os(x.id,e,r,W),O(t=>t.filter(t=>!e.includes(t.id))),M(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`})}},qe=e=>{P(e),a({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Je=async(e,t,n={})=>{if(!x)return!1;let i=o({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`});try{let a=n.targetTreeName&&!U?await Qr(x.workspaceName||x.workspaceId,e,t,n.targetTreeName,n.targetTreeType):await rs(x.id,e,t,r);return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(P([]),await Se()),a}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Ye=async(e,t)=>{if(!x)return!1;try{let n=await Rs(x.workspaceId,t,e);return n&&(kb(x.workspaceName||x.workspaceId,`context`,t),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}},Xe=async()=>{if(!x||!V||U||oe.current)return;let e={id:x.id,url:x.url,path:V};oe.current=!0,ae(!0);try{let t=await is(e.id,`${x.workspaceName}://${e.path.replace(/^\/+/,``)}`);S(n=>n?.id===e.id&&n.url===e.url?{...n,url:t.url,path:e.path}:n),re(null),I(1),window.dispatchEvent(new CustomEvent(`contexts:refresh`,{detail:{contextId:e.id}})),a({title:`Saved`,description:`Context path updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Could not update context path`,variant:`destructive`})}finally{oe.current=!1,ae(!1)}};if(C)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading context...`})]})});if(T&&!x)return(0,$.jsxs)(`div`,{className:`flex items-center justify-center h-full text-destructive`,children:[`Error: `,T]});if(!x)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Context not found.`});let Ze=Nm(x.color);return(0,$.jsx)(`div`,{className:`flex flex-col h-full min-h-0`,children:(0,$.jsx)(hE,{onBack:m,accentColor:Ze,navigationTabs:me?(0,$.jsx)(SE,{views:_e,activeId:ve,onSelect:ye,onSave:be,accentColor:Ze}):void 0,workspaceLabel:se?.label||x.workspaceName||x.workspaceId,workspaceIcon:se?.icon,treeName:lo,urlType:ce,urlDisplay:x.url,contextPath:W,workspaceId:x.workspaceName||x.workspaceId,documentSchema:q,linkTree:pe,documents:De,isLoading:k,totalCount:j,currentPage:F,pageSize:L,onPageChange:I,onPageSizeChange:e=>{R(e),I(1)},onRemoveDocument:W===`/`?void 0:Ue,onDeleteDocument:We,onRemoveDocuments:W===`/`?void 0:Ge,onDeleteDocuments:Ke,onCopyDocuments:qe,onPasteDocuments:Je,onImportDocuments:U?void 0:Ye,pastedDocumentIds:N,backendSearchQueries:z,onBackendSearch:ze,serverSort:s.filters.sort,onServerSortChange:l,onRemoveBackendQuery:Be,canSaveChanges:He,isSavingChanges:s.isSaving,onSaveChanges:c,onBrowseTree:!U&&e?()=>p(`contexts`,`detail`,e):void 0,onBrowseWorkspaces:()=>f(`workspaces`),onNavigatePath:U?void 0:e=>{oe.current||re({id:x.id,url:x.url,path:e})},contentBanner:V?(0,$.jsxs)(`div`,{className:`border-b bg-warning/10 px-4 py-2`,role:`status`,children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Set this context to the selected path? Contents stay at the current path until you apply it.`}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(Km,{items:qm(V,x.workspaceName),label:`Selected context path`}),(0,$.jsx)(`button`,{type:`button`,disabled:ie,onClick:()=>void Xe(),className:`shrink-0 rounded border px-3 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:ie?`Setting…`:`Set`}),(0,$.jsx)(`button`,{type:`button`,disabled:ie,onClick:()=>re(null),className:`shrink-0 rounded px-2 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:`Cancel`})]})]}):void 0,children:K.kind===`columns`?(0,$.jsx)(OE,{documents:De,workspaceId:x.workspaceName||x.workspaceId,columns:K.columns??[],onColumnsChange:e=>be(_e.map(t=>t.id===K.id?{...t,columns:e}:t))}):K.kind===`app`&&K.app&&K.app!==`notes`?(0,$.jsx)(TE,{app:K.app,contextId:e,workspaceId:x.workspaceName||x.workspaceId,treeName:lo,path:W}):null})})}function OO(){let{goBack:e}=PT();return e}function kO(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),{showToast:m}=Vr(),h=(0,Q.useRef)(null),g=(0,Q.useCallback)(async()=>{try{r(!0);let e=await X.get(xr.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,Q.useEffect)(()=>{g()},[g]);let _=async()=>{if(!(!o.trim()||c)){l(!0);try{let e=await X.post(xr.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 X.delete(`${xr.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,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`API Tokens`,onBack:OO(),description:`Create and manage API tokens for programmatic access`}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Generate New API Token`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Token Name (e.g., 'CLI Access', 'Automation')`,disabled:c,className:`flex-1`}),(0,$.jsxs)(Z,{type:`button`,disabled:c||!o.trim(),onClick:_,children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),c?`Generating...`:`Generate`]})]}),u&&(0,$.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,$.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,$.jsx)(`h3`,{className:`font-semibold`,children:`Your New API Token`}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>y(u),children:f?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(oe,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(A,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,$.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,$.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,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your API Tokens`}),n&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading API tokens...`}),i&&(0,$.jsx)(`div`,{className:`text-center text-destructive`,children:(0,$.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No API tokens found`}),e.length>0&&(0,$.jsx)(`div`,{className:`border rounded-md`,children:(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Last Used`}),(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Expires`}),(0,$.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>(0,$.jsxs)(`tr`,{className:`border-t`,children:[(0,$.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,$.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,$.jsx)(`td`,{className:`p-3`,children:e.lastUsedAt?new Date(e.lastUsedAt).toLocaleDateString():`Never`}),(0,$.jsx)(`td`,{className:`p-3`,children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,$.jsx)(`td`,{className:`p-3 text-right`,children:(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>v(e.id),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,children:(0,$.jsx)(ot,{className:`h-4 w-4`})})})]},e.id))})]})})})]})]})}async function AO(){return await X.get(xr.devices)||[]}async function jO(e,t){return await X.patch(`${xr.devices}/${encodeURIComponent(e)}`,t)}async function MO(e){await X.delete(`${xr.devices}/${encodeURIComponent(e)}`)}async function NO(e){return await X.get(`${xr.workspaces}/${e}/devices`)||[]}async function PO(e,t){let n=await X.post(`${xr.workspaces}/${e}/devices`,{deviceId:t});return Array.isArray(n)?n:[n]}async function FO(e,t){await X.delete(`${xr.workspaces}/${e}/devices/${encodeURIComponent(t)}`)}function IO({device:e,onUpdated:t,onRemoved:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(e.name),[s,c]=(0,Q.useState)(e.description??``),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(!1),{showToast:h}=Vr(),g=Object.values(e.mirrors??{}),_=async()=>{m(!0);try{await MO(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 jO(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,$.jsx)(`div`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,$.jsx)(Fn,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[r?(0,$.jsxs)(`div`,{className:`space-y-2 mb-2`,children:[(0,$.jsx)(Y,{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,$.jsx)(Y,{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,$.jsxs)(`div`,{className:`mb-1`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] font-mono text-muted-foreground`,children:[(0,$.jsx)(`span`,{title:`Device ID`,children:e.deviceId}),e.platform&&(0,$.jsx)(`span`,{children:e.platform}),e.arch&&(0,$.jsx)(`span`,{children:e.arch}),e.type&&(0,$.jsx)(`span`,{className:`capitalize`,children:e.type})]}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 text-[11px] text-muted-foreground`,children:[e.createdAt&&(0,$.jsxs)(`span`,{children:[`registered `,b(e.createdAt)]}),e.updatedAt&&e.updatedAt!==e.createdAt&&(0,$.jsxs)(`span`,{children:[`updated `,b(e.updatedAt)]}),e.lastSeen&&(0,$.jsxs)(`span`,{children:[`seen `,b(e.lastSeen)]})]}),g.length>0&&(0,$.jsx)(`div`,{className:`mt-3 space-y-1.5`,children:g.map(e=>(0,$.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,$.jsx)(fe,{className:`h-3.5 w-3.5 text-muted-foreground shrink-0`}),(0,$.jsx)(`span`,{className:`font-medium`,children:e.workspaceName||e.workspaceId}),e.client&&(0,$.jsx)(`span`,{className:`font-mono uppercase text-muted-foreground`,children:e.client}),e.path&&(0,$.jsx)(`span`,{className:`font-mono text-muted-foreground truncate max-w-[24rem]`,title:e.path,children:e.path}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:e.state||`idle`}),(e.pending??0)>0&&(0,$.jsxs)(`span`,{className:`text-muted-foreground`,children:[`pending `,e.pending]}),(e.conflicts??0)>0&&(0,$.jsxs)(`span`,{className:`text-amber-600 dark:text-amber-400`,children:[`conflicts `,e.conflicts]}),(0,$.jsxs)(`span`,{className:`text-muted-foreground`,children:[`synced `,b(e.lastSync)]})]},e.workspaceId))})]})]}),(0,$.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:d?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`destructive`,size:`sm`,onClick:_,disabled:p,children:p?`Revoking…`:`Confirm revoke`}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!1),disabled:p,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}):r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:v,disabled:l||!a.trim(),children:(0,$.jsx)(oe,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:y,disabled:l,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>i(!0),title:`Edit name / description`,children:(0,$.jsx)(_e,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!0),title:`Revoke this device: its tokens stop working and its mirrors stop syncing`,children:(0,$.jsx)(Zn,{className:`h-3.5 w-3.5`})})]})})]})})}function LO(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),{showToast:i}=Vr(),a=async()=>{r(!0);try{t(await AO())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}};(0,Q.useEffect)(()=>{(async()=>{try{t(await AO())}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,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 space-y-6`,children:[(0,$.jsx)(qw,{compact:!0,title:`Devices`,onBack:OO(),description:`All devices registered to your account. Link them to individual workspaces in Workspace › Settings › Devices.`,actions:(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:a,disabled:n,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${n?`animate-spin`:``}`}),`Refresh`]})}),n?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):e.length===0?(0,$.jsxs)(`div`,{className:`rounded-lg border p-6 text-center text-sm text-muted-foreground space-y-2`,children:[(0,$.jsx)(Fn,{className:`h-8 w-8 mx-auto text-muted-foreground/40`}),(0,$.jsx)(`p`,{children:`No devices registered yet.`}),(0,$.jsxs)(`p`,{className:`text-xs`,children:[`Devices register themselves automatically on first connection via`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]})]}):(0,$.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,$.jsx)(IO,{device:e,onUpdated:o,onRemoved:s},e.deviceId))}),e.length>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-dashed p-3 text-xs text-muted-foreground`,children:[(0,$.jsx)(Zt,{className:`h-3.5 w-3.5 shrink-0`}),`To link a device to a workspace, go to Workspace › Settings › Devices.`]})]})})}var RO=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:$t},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:gn},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:Pe},{id:`db`,label:`Search & indexing`,description:`Rebuild indexes, tune search and choose embedding models`,icon:er},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:Fn},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:P},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:Jt},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:Zt},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:fe},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:Je}],zO={embedding:`db`,trash:`data`};function BO(e){return e?zO[e]?zO[e]:RO.some(t=>t.id===e)?e:`general`:`general`}var VO=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:$t},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:Zt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:ie}];function HO(e){return e&&VO.some(t=>t.id===e)?e:`general`}var UO=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:$t},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:q},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:Tt},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:Ne},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:k},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:ct},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:ft}];function WO(e){return e&&UO.some(t=>t.id===e)?e:`identity`}var GO=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(`
23
+ `)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&&JD[o]||i;return s===e.type?e:new File([e],e.name,{type:s,lastModified:e.lastModified})}));return{kind:t.length>0&&t.every(YD)?`photo`:`file`,files:t}}function ZD({file:e}){let t=(0,Q.useRef)(null),[n,r]=(0,Q.useState)(!1);return(0,Q.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,$.jsx)(`div`,{className:`flex min-h-24 items-center justify-center overflow-hidden rounded-md border border-input bg-muted/30`,children:n?(0,$.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,$.jsx)(`video`,{ref:t,controls:!0,preload:`metadata`,"aria-label":e.name,onError:()=>r(!0),className:`max-h-64 max-w-full`}):(0,$.jsx)(`img`,{ref:t,alt:e.name,onError:()=>r(!0),className:`max-h-64 max-w-full object-contain`})})}function QD({onClose:e,initialData:t}){let n=(0,Q.useRef)(null),r=PD(t?.files),i=r.items.map(e=>e.file),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),{state:l}=zs(),u=WD(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,$.jsx)(CD,{title:`Upload File`,icon:Qe,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)=>GD(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,$.jsx)(BD,{items:r.items,running:r.running,onCancel:r.cancel}),successMessage:`File(s) uploaded`,children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:f,onClick:()=>n.current?.click(),className:J(`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,$.jsx)(Qe,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,$.jsx)(`p`,{className:`text-sm`,children:`Drag & drop files here`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`or click to browse`}),(0,$.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=>YD(e.file)).map(e=>(0,$.jsx)(ZD,{file:e.file},e.id)),(0,$.jsx)(zD,{items:r.items,running:s,onRemove:r.removeItem}),(0,$.jsx)(qD,{fields:u,idPrefix:`qa-file`,multiple:i.length>1})]})})}function $D({onClose:e,initialData:t}){let n=PD(t?.files),r=(0,Q.useRef)(null),i=n.items.length>0,[a,o]=(0,Q.useState)(!1),{state:s}=zs(),c=WD(s.activeWorkspaceName),l=e=>{!a&&e&&n.addFiles([e])};return(0,$.jsx)(CD,{title:`Photo/Video`,icon:Ke,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)=>GD(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,$.jsx)(BD,{items:n.items,running:n.running,onCancel:n.cancel}),successMessage:`Upload saved`,children:(0,$.jsxs)(`div`,{className:J(`flex h-full flex-col gap-4 p-4`,!i&&`items-center justify-center`),children:[i?(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(ZD,{file:t}),(0,$.jsxs)(`div`,{className:`flex w-full items-center gap-2 rounded border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(Rn,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`flex-1 truncate`,children:t.name}),(0,$.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[(t.size/1024/1024).toFixed(1),` MB`]}),(0,$.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,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e))}),(0,$.jsx)(`div`,{className:`w-full shrink-0 space-y-4`,children:(0,$.jsx)(qD,{fields:c,idPrefix:`qa-photo`,multiple:n.items.length>1})})]}):(0,$.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,$.jsx)(Ke,{className:`h-8 w-8 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-sm`,children:`Open camera`})]}),(0,$.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 eO=`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 tO({onClose:e}){let{showSuccessToast:t,showErrorToast:n}=Wr(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(!1);return r?(0,$.jsx)(ih,{sizeClassName:eO,documentCount:r.length,saving:a,onClose:e,onConfirm:async(i,a)=>{o(!0);try{await Promise.all(i.map(e=>Qr(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,$.jsx)(Cg,{sizeClassName:eO,onConfirm:e=>{e.length&&i(e)},onClose:e})}function nO(){let e=qo(`new:home-card:`);try{return Object.keys(localStorage).filter(t=>t.startsWith(e)&&t.endsWith(`:home`)).filter(e=>{let t=JSON.parse(localStorage.getItem(e)||`null`)?.value;return t&&(t.title||t.content||t.comment||t.tags?.length)}).map(t=>t.slice(e.length,-5))}catch{return[]}}var rO=0;function iO(){return rO+=1,`card-${rO}`}function aO({initialKind:e,initialData:t,onInitialCardClose:n,onCardsOpenChange:r}){let[i,a]=(0,Q.useState)(!1),o=l_(),s=es(),c=!!(s?.state.t1Open||s?.state.addOpen),[l,u]=(0,Q.useState)(()=>e?[{id:`initial`,kind:e,initialData:t,noteDraftId:crypto.randomUUID()}]:nO().map(e=>({id:e,kind:`note`,noteDraftId:e}))),d=l.length>0,f=(0,Q.useRef)(r);(0,Q.useEffect)(()=>{f.current=r},[r]),(0,Q.useEffect)(()=>{f.current?.(d)},[d]),c&&i&&a(!1);let p=gl(),m=e=>{if(e===`sketch`){a(!1),p(gD.createUrl(null));return}let t=e===`note`?nO().find(e=>!l.some(t=>t.noteDraftId===e))||crypto.randomUUID():void 0;u(n=>[...n,{id:iO(),kind:e,noteDraftId:t}]),a(!1)},h=e=>{u(t=>t.filter(t=>t.id!==e)),e===`initial`&&n?.()},g=(0,$.jsxs)(`div`,{className:J(`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,$.jsx)(`div`,{className:J(`flex flex-col items-end gap-2 transition-all duration-fast`,i?`pointer-events-auto opacity-100`:`pointer-events-none translate-y-2 opacity-0`),children:(0,$.jsx)(yD,{variant:`stack`,omit:[`plaintext`,`folder`,`message`],onSelect:m})}),(0,$.jsx)(`div`,{className:`pointer-events-none flex w-16 justify-center`,children:(0,$.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,$.jsx)(G,{className:`h-5 w-5`}):(0,$.jsx)(sn,{className:`h-5 w-5`})})})]});return(0,$.jsxs)(`div`,{className:`relative flex h-full w-full flex-col`,children:[l.length>0&&(0,$.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,$.jsx)(wD,{draftId:e.noteDraftId,onClose:t,initialData:e.initialData},e.id);case`link`:return(0,$.jsx)(kD,{onClose:t,initialData:e.initialData},e.id);case`todo`:return(0,$.jsx)(AD,{onClose:t,initialData:e.initialData},e.id);case`identity`:return(0,$.jsx)(jD,{onClose:t,initialData:e.initialData},e.id);case`file`:return(0,$.jsx)(QD,{onClose:t,initialData:e.initialData},e.id);case`photo`:return(0,$.jsx)($D,{onClose:t,initialData:e.initialData},e.id);case`existing`:return(0,$.jsx)(tO,{onClose:t},e.id);case`sketch`:return null;case`folder`:case`message`:return null}})}),o?(0,Ip.createPortal)(g,document.body):g]})}function oO(e){let t=`${e.workspaceName}\0${e.treeName}\0${e.path}`,[n,r]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let n=!1;return ga(e.workspaceName,e.treeName).then(i=>{n||r({key:t,node:di(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 sO(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 cO=`application/x-canvas-pin`;function lO({pin:e,onUnpin:t,onMinimize:n,onDropPin:r}){let i=oO(e),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.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(cO);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,Q.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]),(0,$.jsxs)(`section`,{...d,className:a?`fixed inset-0 z-picker flex flex-col bg-background`:`flex flex-col rounded-(--card-radius) border bg-background overflow-hidden min-h-0 min-w-0 ${s?`ring-2 ring-primary/60`:``}`,children:[(0,$.jsxs)(`header`,{draggable:l,onDragStart:l?t=>{t.dataTransfer.setData(cO,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,$.jsx)(T,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-hidden":!0}),m&&(0,$.jsx)(`div`,{className:`w-1 h-5 rounded-full shrink-0`,style:{backgroundColor:m}}),(0,$.jsx)(gt,{className:`w-4 h-4 shrink-0 text-primary`}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:p}),(0,$.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono`,children:[e.workspaceName,`://`,e.path.replace(/^\//,``)]})]}),n&&(0,$.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,$.jsx)(ue,{className:`w-3.5 h-3.5`})}),(0,$.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,$.jsx)(lt,{className:`w-3.5 h-3.5`}):(0,$.jsx)(xn,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(Nu,{to:sO(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,$.jsx)(Ht,{className:`w-3.5 h-3.5`})}),(0,$.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,$.jsx)(ee,{className:`w-3.5 h-3.5`})})]}),(0,$.jsxs)(`div`,{className:`flex-1 min-h-0`,children:[i.state===`loading`&&(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}),i.state===`missing`&&(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 px-4 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`This canvas is no longer available.`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`It may have been renamed, moved or deleted.`}),(0,$.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,$.jsx)(iS,{workspaceId:e.workspaceName,treeName:e.treeName,path:e.path,layerId:i.node.id,querySpec:i.node.querySpec,metadata:i.node.metadata,readOnly:!0})]})]})}function uO(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 dO(e,t){return e.minimized===!0||t.has(e.id)}function fO(e){return e.label||e.path.split(`/`).filter(Boolean).pop()||`Canvas`}function pO({pins:e,onRestore:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(e.length);return i!==e.length&&(a(e.length),e.length===0&&r(!1)),e.length===0?null:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`pointer-events-none absolute bottom-0 left-0 right-0 z-40 max-md:hidden`,children:(0,$.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,$.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),title:`Restore ${fO(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,$.jsx)(gt,{className:`h-3.5 w-3.5 shrink-0 text-primary`}),(0,$.jsx)(`span`,{className:`truncate`,children:fO(e)})]},e.id))})}),n&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-drawer md:hidden`,onClick:()=>r(!1),"aria-hidden":!0}),(0,$.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,$.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,$.jsx)(gt,{className:`h-4 w-4 shrink-0 text-primary`}),(0,$.jsx)(`span`,{className:`truncate`,children:fO(e)})]},e.id))})]}),(0,$.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,$.jsx)(gt,{className:`h-5 w-5`}),(0,$.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 mO(){let{pins:e,unpin:t,movePin:n,setMinimized:r,isLoading:i}=BE(),{showErrorToast:a}=Wr(),[o,s]=(0,Q.useState)(new Set),c=(0,Q.useRef)(e);(0,Q.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,Q.useCallback)(e=>{s(e?new Set(c.current.filter(e=>!e.minimized).map(e=>e.id)):new Set)},[]),f=e.filter(e=>!dO(e,o)),p=e.filter(e=>dO(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,$.jsxs)(`div`,{className:`relative h-full`,children:[(0,$.jsx)(`div`,{className:`h-full overflow-y-auto`,children:i?(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-xs text-muted-foreground`,children:`Loading…`}):(0,$.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,$.jsx)(lO,{pin:e,onUnpin:()=>{t(e.id)},onMinimize:()=>l(e.id),onDropPin:(t,n)=>m(t,e,n)},e.id))})}),(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,children:(0,$.jsx)(aO,{onCardsOpenChange:d})}),(0,$.jsx)(pO,{pins:p,onRestore:u})]})}function hO(){return(0,$.jsx)(`div`,{className:`h-full w-full`,"aria-hidden":!0})}var gO=`share-target-inbox`,_O={"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 vO(e){let t=await caches.open(gO),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 XD(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||(xO(o)?o:``);return s?{kind:`link`,data:{url:s,title:n.title}}:{kind:`note`,data:{title:n.title,content:n.text}}}var yO=new Map;function bO(e){let t=yO.get(e);return t||(t=vO(e),yO.set(e,t),t.finally(()=>setTimeout(()=>yO.delete(e),6e4)).catch(()=>{})),t}function xO(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 SO(){let[e]=zu(),t=gl(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null);(0,Q.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 bO(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,$.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 px-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:_O[i]??_O.expired}),(0,$.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,$.jsx)(`button`,{type:`button`,onClick:o,className:`text-sm font-medium text-primary underline underline-offset-4`,children:`Go to Canvas`})]}):n?(0,$.jsx)(aO,{initialKind:n.kind,initialData:n.data,onInitialCardClose:o}):(0,$.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 CO(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 wO(e,t,n=`An error occurred`){return console.error(t,e),CO(e,n)}function TO(){let e=gl(),[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(!0),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(`context`),[h,g]=(0,Q.useState)(`/`),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(`/`),[C,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(!1),[D,O]=tT(),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(null),{showToast:N}=Vr();(0,Q.useEffect)(()=>{hd.isConnected()||(console.log(`Socket not connected, attempting to connect...`),hd.reconnect())},[]);let P=(0,Q.useCallback)(async()=>{try{o(!0);let[e,t]=await Promise.all([ps(),Ni()]),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===C);(!C||!e)&&w(a[0].id)}else w(``);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),N({title:`Error`,description:t,variant:`destructive`})}finally{o(!1)}},[C,N]);(0,Q.useEffect)(()=>{P()},[P]),(0,Q.useEffect)(()=>{let e=()=>hd.emit(`subscribe`,{channel:`context`}),t=()=>hd.emit(`unsubscribe`,{channel:`context`}),r=hd.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])=>hd.on(e,t)),()=>{console.log(`Unsubscribing from context events`),t(),r?.(),c.forEach(([e,t])=>hd.off(e,t))}},[]);let F=async t=>{if(t.preventDefault(),!h.trim()||!C||!l.trim()){N({title:`Missing Fields`,description:`Context ID, Context URL and Workspace are required.`,variant:`destructive`});return}E(!0);try{let t={id:l,name:d.trim()||void 0,url:h,description:_.trim()||void 0,metadata:{ui:{color:y}},workspaceId:C,baseUrl:x||void 0,treeType:p},n=await xs(t);u(``),f(``),g(`/`),v(``),b(null),S(`/`),await P(),N({title:`Success`,description:`Context created successfully`}),O(!1),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e(`/contexts/${n.id}`)}catch(e){let t=wO(e,`Context creation error:`,`Failed to create context`);N({title:`Error`,description:t,variant:`destructive`})}finally{E(!1)}},I=async e=>{let n=t.find(t=>t.id===e);if(n&&n.url&&(n.url.endsWith(`/default`)||n.url.includes(`://default`))){N({title:`Error`,description:`Cannot delete the default context`,variant:`destructive`});return}M(e)},L=async()=>{if(j)try{await As(j),n(e=>e.filter(e=>!ss(e,{id:j}))),N({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`}N({title:`Error`,description:t,variant:`destructive`})}finally{M(null)}},R=t=>{let n=t.isShared||t.type===`shared`;e(n?`/contexts/${t.id}?ownerId=${encodeURIComponent(t.userId)}`:`/contexts/${t.id}`)},z=e=>{A(e)},ee=async e=>{if(e.preventDefault(),k)try{n(e=>e.map(e=>e.id===k.id&&e.userId===k.userId?k:e)),N({title:`Success`,description:`Context updated successfully (mock update)`}),A(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update context`;N({title:`Error`,description:t,variant:`destructive`})}},te=(0,Q.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:ne,sort:B,toggleSort:re}=Ig(t.filter(e=>e!=null),te);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`Contexts`,description:`Create and manage contexts in your workspaces. View contexts shared with you.`,actions:!D&&(0,$.jsxs)(Z,{onClick:()=>O(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create context`,title:`Create context`,children:[(0,$.jsx)(sn,{className:`h-4 w-4 sm:mr-2`}),(0,$.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Context`})]})}),D&&(0,$.jsx)($w,{title:`Create New Context`,onClose:()=>O(!1),children:(0,$.jsxs)(`form`,{onSubmit:F,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`workspace`,className:`block text-sm font-medium mb-1`,children:`Workspace`}),(0,$.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:C,onChange:e=>w(e.target.value),disabled:T||r.length===0,children:[r.length===0&&(0,$.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),r.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label||e.name},`${e.owner}-${e.id}`))]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`newContextId`,className:`block text-sm font-medium mb-1`,children:`Context ID`}),(0,$.jsx)(Y,{id:`newContextId`,value:l,onChange:e=>u(e.target.value),placeholder:`e.g., my-new-context`,disabled:T})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,$.jsx)(ah,{id:`url`,value:h,onChange:g,placeholder:`e.g., /project/path/resource`,disabled:T,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&&w(n.id)}})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`baseUrl`,className:`block text-sm font-medium mb-1`,children:`Base URL (Optional)`}),(0,$.jsx)(ah,{id:`baseUrl`,value:x,onChange:S,format:`path`,placeholder:`e.g., /base/path`,disabled:T,pickerTitle:`Base path…`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`description`,className:`block text-sm font-medium mb-1`,children:`Description (Optional)`}),(0,$.jsx)(Y,{id:`description`,value:_,onChange:e=>v(e.target.value),placeholder:`Description`,disabled:T})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`contextColor`,className:`block text-sm font-medium mb-1`,children:`Color (Optional)`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Y,{id:`contextColor`,type:`color`,value:y||`#808080`,onChange:e=>b(e.target.value),className:`h-10 w-16 p-1`,disabled:T}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:T||y===null,onClick:()=>b(null),children:`Use inherited color`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:y===null?`Uses the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`contextName`,className:`block text-sm font-medium mb-1`,children:`Name (Optional)`}),(0,$.jsx)(Y,{id:`contextName`,value:d,onChange:e=>f(e.target.value),placeholder:`My Context`,disabled:T})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`treeType`,className:`block text-sm font-medium mb-1`,children:`Tree`}),(0,$.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:T,children:[(0,$.jsx)(`option`,{value:`context`,children:`Context tree`}),(0,$.jsx)(`option`,{value:`directory`,children:`Directory tree`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Which workspace tree this context navigates.`})]})]}),(0,$.jsxs)(Z,{type:`submit`,disabled:T||!h.trim()||!C||!l.trim(),children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),`Create Context`]})]})}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Contexts & Shared Contexts`}),a&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading contexts...`}),s&&(0,$.jsx)(`div`,{className:`text-center text-destructive`,children:(0,$.jsx)(`p`,{children:s})}),!a&&!s&&t.length===0&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No contexts found. Create one above.`}),t.length>0&&(0,$.jsx)(`div`,{className:`border rounded-lg overflow-hidden`,children:(0,$.jsxs)(Dg,{children:[(0,$.jsx)(Og,{children:(0,$.jsxs)(jg,{children:[(0,$.jsx)(Fg,{label:`Type`,sortKey:`type`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`ID`,sortKey:`id`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Owner`,sortKey:`owner`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Context URL`,sortKey:`url`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Workspace ID`,sortKey:`workspaceId`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Base URL`,sortKey:`baseUrl`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Path`,sortKey:`path`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Locked`,sortKey:`locked`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Created`,sortKey:`created`,sort:B,onSort:re}),(0,$.jsx)(Fg,{label:`Updated`,sortKey:`updated`,sort:B,onSort:re}),(0,$.jsx)(Mg,{className:`text-right`,children:`Actions`})]})}),(0,$.jsx)(kg,{children:ne.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,$.jsxs)(jg,{children:[(0,$.jsx)(Ng,{children:r?(0,$.jsxs)(`div`,{className:`flex items-center gap-1 text-info`,title:`Shared with you (${a})`,children:[(0,$.jsx)(jn,{className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`text-xs`,children:`Shared`})]}):(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Owned`})}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.id||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,title:r?`Owned by: ${i}`:`You are the owner`,children:i}),(0,$.jsx)(Ng,{className:`font-mono text-sm max-w-xs truncate`,title:e.url||`-`,children:e.url||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.workspaceId||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.baseUrl||`-`}),(0,$.jsx)(Ng,{className:`font-mono text-sm`,children:e.path||`-`}),(0,$.jsx)(Ng,{children:e.locked?`Yes`:`No`}),(0,$.jsx)(Ng,{children:t}),(0,$.jsx)(Ng,{children:n}),(0,$.jsx)(Ng,{className:`text-right`,children:(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[!r&&(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>z(e),title:`Edit Context`,children:(0,$.jsx)(rn,{className:`h-4 w-4`})}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>R(e),title:r?`Open Shared Context`:`Open Context Details`,children:(0,$.jsx)(_t,{className:`h-4 w-4`})}),!r&&(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>I(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,$.jsx)(ot,{className:`h-4 w-4`})})]})})]},`${e.userId}-${e.id}`)})})]})})]}),k&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Edit Context`}),(0,$.jsxs)(`form`,{onSubmit:ee,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-context-id`,className:`block text-sm font-medium mb-1`,children:`Context ID (read-only)`}),(0,$.jsx)(Y,{id:`edit-context-id`,value:k.id,disabled:!0,className:`bg-muted`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-context-url`,className:`block text-sm font-medium mb-1`,children:`Context URL`}),(0,$.jsx)(ah,{id:`edit-context-url`,value:k.url,onChange:e=>A(t=>t?{...t,url:e}:null),placeholder:`workspace://path or /path`,pickerTitle:`Context URL path…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Use format: workspace://path or /path for current workspace`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`edit-base-url`,className:`block text-sm font-medium mb-1`,children:`Base URL (optional)`}),(0,$.jsx)(ah,{id:`edit-base-url`,value:k.baseUrl||``,onChange:e=>A(t=>t?{...t,baseUrl:e||null}:null),format:`path`,placeholder:`/base/path`,pickerTitle:`Base path…`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Restricts context navigation to this base path`})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Z,{type:`submit`,children:`Save Changes`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,onClick:()=>A(null),children:`Cancel`})]})]})]}),(0,$.jsx)(Ir,{open:j!==null,onOpenChange:e=>!e&&M(null),children:(0,$.jsxs)(Or,{children:[(0,$.jsxs)(Fr,{children:[(0,$.jsx)(Cr,{children:`Delete Context`}),(0,$.jsx)(Sr,{children:`Are you sure you want to delete this context? This action cannot be undone.`})]}),(0,$.jsxs)(Mr,{children:[(0,$.jsx)(Pr,{children:`Cancel`}),(0,$.jsx)(jr,{onClick:L,className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:`Delete`})]})]})})]})}function EO(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 DO(){let{contextId:e}=bl(),t=pl(),n=gl(),r=new URLSearchParams(t.search).get(`ownerId`)||void 0,i=(0,Q.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,showProgress:o}=Vr(),{state:s,saveFilters:c,setSort:l,setAccentColor:u,setMapDocuments:d}=zs(),{openM1Drawer:f,openM2Drawer:p,goBack:m}=PT(),h=s.filters.features.allOf,g=s.filters.features.anyOf,_=s.filters.features.noneOf,v=[...Xy(s.filters.timeline),...qy(s.filters.geo),...Jy(s.filters.lens,s.filters.geo.includeUnlocated)],y=JSON.stringify({a:h,b:g,c:_,d:v,ids:s.filters.lens.ids,sort:s.filters.sort,geoSelection:s.geoSelection,includeUnlocated:s.filters.geo.includeUnlocated}),b=(0,Q.useMemo)(()=>JSON.parse(y),[y]),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!0),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)([]),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(0),[N,P]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(1),[L,R]=(0,Q.useState)(50),[z,ee]=(0,Q.useState)(i),[te,ne]=(0,Q.useState)(!1),[B,re]=(0,Q.useState)(null),[ie,ae]=(0,Q.useState)(!1),oe=(0,Q.useRef)(!1),V=B?.id===x?.id&&B?.url===x?.url?B?.path:null,H=new URLSearchParams(t.search).get(`layer`),U=!!r,se=fD(U?void 0:x?.workspaceName||x?.workspaceId),W=x?EO(x.url,x.workspaceName):`/`,ce=H?`context-layer`:`context`,le=!s.liveEnabled&&typeof x?.metadata?.toolboxSearchQuery==`string`?x.metadata.toolboxSearchQuery:``,ue=U?null:x?.workspaceName??null,[de,fe]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!ue)return;let e=!1;return vi(ue,lo).then(t=>{e||fe({key:ue,tree:t})}).catch(()=>{e||fe({key:ue,tree:null})}),()=>{e=!0}},[ue]);let pe=ue&&de?.key===ue?de.tree:null,me=!H&&!U&&pe?W===`/`?pe:di(pe,W):null,G=`${x?.workspaceName??``}\0${W}`,[he,ge]=(0,Q.useState)(null),_e=he?.key===G?he.views:bE(me?.metadata),ve=he?.key===G?he.activeId:_e[0]?.id??vE.id,K=_e.find(e=>e.id===ve)??_e[0]??vE,q=_E(K),ye=e=>{I(1),ge({key:G,views:_e,activeId:e})},be=(e,t)=>{t&&t!==ve&&I(1),ge({key:G,views:e,activeId:t??ve}),x?.workspaceName&&zi(x.workspaceName,W,{metadata:{...me?.metadata??{},views:e}},lo).catch(()=>{a({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},xe=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>xe.current?.abort(),[]);let Se=(0,Q.useCallback)(async()=>{if(!e)return;xe.current?.abort();let t=new AbortController;xe.current=t,A(!0);try{let n=await Ss(e,q?[...b.a,q]:b.a,b.d,{...b.sort,geoSelection:b.geoSelection,includeUnlocated:b.includeUnlocated,ids:b.ids,signal:t.signal,limit:L,page:F,queries:z.length?z:void 0,anyOf:b.b,noneOf:b.c,applyContextSpec:!1},r);if(t.signal.aborted)return;O(n),M(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`}),O([]),M(0)}finally{t.signal.aborted||A(!1)}},[e,F,L,r,z,b,a,q]),Ce=(0,Q.useCallback)(async()=>{if(e){w(!0);try{let t=U?await Cs(e,r):await Cs(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)||``;S({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}),E(null)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch context ${e}`;E(n),S(null),a({title:`Error`,description:n,variant:`destructive`})}w(!1)}},[e,r,U,a]);(0,Q.useEffect)(()=>{Ce()},[Ce]);let we=Nm(x?.color)||null;(0,Q.useEffect)(()=>(u(we),()=>u(null)),[we,u]);let Te=s.geoSelection,Ee=x?.workspaceName||x?.workspaceId||null;(0,Q.useEffect)(()=>{d(D,Ee)},[D,Ee,d]),(0,Q.useEffect)(()=>()=>d([]),[d]);let De=(0,Q.useMemo)(()=>Te?D.filter(e=>Ly(e,Te,s.filters.geo.includeUnlocated)):D,[D,Te,s.filters.geo.includeUnlocated]),Oe=x?.id,ke=x?.url;(0,Q.useEffect)(()=>{Oe&&Se()},[Oe,ke,Se]),(0,Q.useEffect)(()=>{let e=()=>Se();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[Se]);let[Ae,je]=(0,Q.useState)(y);Ae!==y&&(je(y),I(1));let[Me,Ne]=(0,Q.useState)(e);Me!==e&&(Ne(e),I(1),ne(!1));let[Pe,Fe]=(0,Q.useState)(i);Pe!==i&&(Fe(i),ee(i),I(1));let[Ie,Le]=(0,Q.useState)({urlSearchQueries:i,ignoreSavedSearch:te,savedContextSearchQuery:le});(Ie.urlSearchQueries!==i||Ie.ignoreSavedSearch!==te||Ie.savedContextSearchQuery!==le)&&(Le({urlSearchQueries:i,ignoreSavedSearch:te,savedContextSearchQuery:le}),!new URLSearchParams(t.search).has(`q`)&&!i.length&&!te&&(ee(le?[le]:[]),I(1)));let Re=(0,Q.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.hash}`)},[t.pathname,t.search,t.hash,n]),ze=(0,Q.useCallback)(e=>{let t=e.trim();if(!t)return;ne(!1);let n=z.includes(t)?z:[...z,t];ee(n),Re(n)},[z,Re]),Be=(0,Q.useCallback)(e=>{let t=e<0?[]:z.filter((t,n)=>n!==e);t.length===0&&ne(!0),ee(t),Re(t)},[z,Re]),Ve=(z[0]||``).trim(),He=!!s.activeContextType&&(s.isDirty||Ve!==(s.savedSearchQuery||le||``));(0,Q.useEffect)(()=>{if(!e)return;let t=`context:${r?`${r}/`:``}${e}`,n=()=>hd.emit(`subscribe`,{channel:t}),i=()=>hd.emit(`unsubscribe`,{channel:t}),a=hd.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)&&(S(e=>e?{...e,...r}:null),r.url&&Se())},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)&&(S(e=>e?{...e,url:i}:null),Se())},u=t=>{let n=t;(n?.contextId||n?.id||n?.context?.id)===e&&s(`doc:changed`,n)&&Se()},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])=>hd.on(e,t)),()=>{a(),i(),d.forEach(([e,t])=>hd.off(e,t))}},[e,r,Se]);let Ue=async e=>{if(x)try{await Es(x.id,[e],r,W),O(t=>t.filter(t=>t.id!==e)),M(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`})}},We=async e=>{if(x)try{await Os(x.id,[e],r,W),O(t=>t.filter(t=>t.id!==e)),M(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`})}},Ge=async e=>{if(x)try{await Es(x.id,e,r,W),O(t=>t.filter(t=>!e.includes(t.id))),M(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`})}},Ke=async e=>{if(x)try{await Os(x.id,e,r,W),O(t=>t.filter(t=>!e.includes(t.id))),M(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`})}},qe=e=>{P(e),a({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},Je=async(e,t,n={})=>{if(!x)return!1;let i=o({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`});try{let a=n.targetTreeName&&!U?await Qr(x.workspaceName||x.workspaceId,e,t,n.targetTreeName,n.targetTreeType):await rs(x.id,e,t,r);return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(P([]),await Se()),a}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},Ye=async(e,t)=>{if(!x)return!1;try{let n=await Rs(x.workspaceId,t,e);return n&&(kb(x.workspaceName||x.workspaceId,`context`,t),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}},Xe=async()=>{if(!x||!V||U||oe.current)return;let e={id:x.id,url:x.url,path:V};oe.current=!0,ae(!0);try{let t=await is(e.id,`${x.workspaceName}://${e.path.replace(/^\/+/,``)}`);S(n=>n?.id===e.id&&n.url===e.url?{...n,url:t.url,path:e.path}:n),re(null),I(1),window.dispatchEvent(new CustomEvent(`contexts:refresh`,{detail:{contextId:e.id}})),a({title:`Saved`,description:`Context path updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Could not update context path`,variant:`destructive`})}finally{oe.current=!1,ae(!1)}};if(C)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,$.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading context...`})]})});if(T&&!x)return(0,$.jsxs)(`div`,{className:`flex items-center justify-center h-full text-destructive`,children:[`Error: `,T]});if(!x)return(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Context not found.`});let Ze=Nm(x.color);return(0,$.jsx)(`div`,{className:`flex flex-col h-full min-h-0`,children:(0,$.jsx)(hE,{onBack:m,accentColor:Ze,navigationTabs:me?(0,$.jsx)(SE,{views:_e,activeId:ve,onSelect:ye,onSave:be,accentColor:Ze}):void 0,workspaceLabel:se?.label||x.workspaceName||x.workspaceId,workspaceIcon:se?.icon,treeName:lo,urlType:ce,urlDisplay:x.url,contextPath:W,workspaceId:x.workspaceName||x.workspaceId,documentSchema:q,linkTree:pe,documents:De,isLoading:k,totalCount:j,currentPage:F,pageSize:L,onPageChange:I,onPageSizeChange:e=>{R(e),I(1)},onRemoveDocument:W===`/`?void 0:Ue,onDeleteDocument:We,onRemoveDocuments:W===`/`?void 0:Ge,onDeleteDocuments:Ke,onCopyDocuments:qe,onPasteDocuments:Je,onImportDocuments:U?void 0:Ye,pastedDocumentIds:N,backendSearchQueries:z,onBackendSearch:ze,serverSort:s.filters.sort,onServerSortChange:l,onRemoveBackendQuery:Be,canSaveChanges:He,isSavingChanges:s.isSaving,onSaveChanges:c,onBrowseTree:!U&&e?()=>p(`contexts`,`detail`,e):void 0,onBrowseWorkspaces:()=>f(`workspaces`),onNavigatePath:U?void 0:e=>{oe.current||re({id:x.id,url:x.url,path:e})},contentBanner:V?(0,$.jsxs)(`div`,{className:`border-b bg-warning/10 px-4 py-2`,role:`status`,children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Set this context to the selected path? Contents stay at the current path until you apply it.`}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(Km,{items:qm(V,x.workspaceName),label:`Selected context path`}),(0,$.jsx)(`button`,{type:`button`,disabled:ie,onClick:()=>void Xe(),className:`shrink-0 rounded border px-3 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:ie?`Setting…`:`Set`}),(0,$.jsx)(`button`,{type:`button`,disabled:ie,onClick:()=>re(null),className:`shrink-0 rounded px-2 py-1 text-sm hover:bg-accent disabled:opacity-50`,children:`Cancel`})]})]}):void 0,children:K.kind===`columns`?(0,$.jsx)(OE,{documents:De,workspaceId:x.workspaceName||x.workspaceId,columns:K.columns??[],onColumnsChange:e=>be(_e.map(t=>t.id===K.id?{...t,columns:e}:t))}):K.kind===`app`&&K.app&&K.app!==`notes`?(0,$.jsx)(TE,{app:K.app,contextId:e,workspaceId:x.workspaceName||x.workspaceId,treeName:lo,path:W}):null})})}function OO(){let{goBack:e}=PT();return e}function kO(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(!1),{showToast:m}=Vr(),h=(0,Q.useRef)(null),g=(0,Q.useCallback)(async()=>{try{r(!0);let e=await X.get(xr.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,Q.useEffect)(()=>{g()},[g]);let _=async()=>{if(!(!o.trim()||c)){l(!0);try{let e=await X.post(xr.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 X.delete(`${xr.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,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`API Tokens`,onBack:OO(),description:`Create and manage API tokens for programmatic access`}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Generate New API Token`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Token Name (e.g., 'CLI Access', 'Automation')`,disabled:c,className:`flex-1`}),(0,$.jsxs)(Z,{type:`button`,disabled:c||!o.trim(),onClick:_,children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),c?`Generating...`:`Generate`]})]}),u&&(0,$.jsxs)(`div`,{className:`p-4 border rounded-md bg-muted/50`,children:[(0,$.jsxs)(`div`,{className:`flex justify-between items-center mb-2`,children:[(0,$.jsx)(`h3`,{className:`font-semibold`,children:`Your New API Token`}),(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>y(u),children:f?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(oe,{className:`mr-2 h-4 w-4`}),`Copied`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(A,{className:`mr-2 h-4 w-4`}),`Copy`]})})]}),(0,$.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,$.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,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your API Tokens`}),n&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading API tokens...`}),i&&(0,$.jsx)(`div`,{className:`text-center text-destructive`,children:(0,$.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,$.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No API tokens found`}),e.length>0&&(0,$.jsx)(`div`,{className:`border rounded-md`,children:(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`bg-muted/50`,children:[(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Name`}),(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Created`}),(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Last Used`}),(0,$.jsx)(`th`,{className:`text-left p-3 font-medium`,children:`Expires`}),(0,$.jsx)(`th`,{className:`text-right p-3 font-medium`,children:`Actions`})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>(0,$.jsxs)(`tr`,{className:`border-t`,children:[(0,$.jsx)(`td`,{className:`p-3 font-medium`,children:e.name}),(0,$.jsx)(`td`,{className:`p-3`,children:new Date(e.createdAt).toLocaleDateString()}),(0,$.jsx)(`td`,{className:`p-3`,children:e.lastUsedAt?new Date(e.lastUsedAt).toLocaleDateString():`Never`}),(0,$.jsx)(`td`,{className:`p-3`,children:e.expiresAt?new Date(e.expiresAt).toLocaleDateString():`Never`}),(0,$.jsx)(`td`,{className:`p-3 text-right`,children:(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>v(e.id),className:`text-destructive hover:bg-destructive/10 hover:text-destructive`,children:(0,$.jsx)(ot,{className:`h-4 w-4`})})})]},e.id))})]})})})]})]})}async function AO(){return await X.get(xr.devices)||[]}async function jO(e,t){return await X.patch(`${xr.devices}/${encodeURIComponent(e)}`,t)}async function MO(e){await X.delete(`${xr.devices}/${encodeURIComponent(e)}`)}async function NO(e){return await X.get(`${xr.workspaces}/${e}/devices`)||[]}async function PO(e,t){let{deviceId:n,name:r,description:i,platform:a,arch:o,type:s}=t,c=await X.post(`${xr.workspaces}/${e}/devices`,{devices:[{deviceId:n,name:r,description:i,platform:a,arch:o,type:s}]});return Array.isArray(c)?c:[c]}async function FO(e,t){await X.delete(`${xr.workspaces}/${e}/devices/${encodeURIComponent(t)}`)}function IO({device:e,onUpdated:t,onRemoved:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(e.name),[s,c]=(0,Q.useState)(e.description??``),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(!1),{showToast:h}=Vr(),g=async()=>{m(!0);try{await MO(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)}},_=async()=>{let n=a.trim();if(n){if(n===e.name&&s.trim()===(e.description??``)){i(!1);return}u(!0);try{let r=await jO(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)}}},v=()=>{o(e.name),c(e.description??``),i(!1)},y=e=>e?new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`}):`—`;return(0,$.jsx)(`div`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,$.jsx)(Fn,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[r?(0,$.jsxs)(`div`,{className:`space-y-2 mb-2`,children:[(0,$.jsx)(Y,{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`&&_(),e.key===`Escape`&&v()}}),(0,$.jsx)(Y,{value:s,onChange:e=>c(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,disabled:l,onKeyDown:e=>{e.key===`Enter`&&_(),e.key===`Escape`&&v()}})]}):(0,$.jsxs)(`div`,{className:`mb-1`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] font-mono text-muted-foreground`,children:[(0,$.jsx)(`span`,{title:`Device ID`,children:e.deviceId}),e.platform&&(0,$.jsx)(`span`,{children:e.platform}),e.arch&&(0,$.jsx)(`span`,{children:e.arch}),e.type&&(0,$.jsx)(`span`,{className:`capitalize`,children:e.type})]}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-x-4 text-[11px] text-muted-foreground`,children:[e.createdAt&&(0,$.jsxs)(`span`,{children:[`registered `,y(e.createdAt)]}),e.updatedAt&&e.updatedAt!==e.createdAt&&(0,$.jsxs)(`span`,{children:[`updated `,y(e.updatedAt)]}),e.lastSeen&&(0,$.jsxs)(`span`,{children:[`seen `,y(e.lastSeen)]})]})]})]}),(0,$.jsx)(`div`,{className:`flex shrink-0 items-center gap-2`,children:d?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`destructive`,size:`sm`,onClick:g,disabled:p,children:p?`Revoking…`:`Confirm revoke`}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!1),disabled:p,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}):r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:_,disabled:l||!a.trim(),children:(0,$.jsx)(oe,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:v,disabled:l,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>i(!0),title:`Edit name / description`,children:(0,$.jsx)(_e,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>f(!0),title:`Revoke this device: its tokens stop working and its mirrors stop syncing`,children:(0,$.jsx)(Zn,{className:`h-3.5 w-3.5`})})]})})]})})}function LO(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),{showToast:i}=Vr(),a=async()=>{r(!0);try{t(await AO())}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{r(!1)}};(0,Q.useEffect)(()=>{(async()=>{try{t(await AO())}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,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 space-y-6`,children:[(0,$.jsx)(qw,{compact:!0,title:`Devices`,onBack:OO(),description:`All devices registered to your account. Link them to individual workspaces in Workspace › Settings › Devices.`,actions:(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:a,disabled:n,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${n?`animate-spin`:``}`}),`Refresh`]})}),n?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):e.length===0?(0,$.jsxs)(`div`,{className:`rounded-lg border p-6 text-center text-sm text-muted-foreground space-y-2`,children:[(0,$.jsx)(Fn,{className:`h-8 w-8 mx-auto text-muted-foreground/40`}),(0,$.jsx)(`p`,{children:`No devices registered yet.`}),(0,$.jsxs)(`p`,{className:`text-xs`,children:[`Devices register themselves automatically on first connection via`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]})]}):(0,$.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,$.jsx)(IO,{device:e,onUpdated:o,onRemoved:s},e.deviceId))}),e.length>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md border border-dashed p-3 text-xs text-muted-foreground`,children:[(0,$.jsx)(Zt,{className:`h-3.5 w-3.5 shrink-0`}),`To link a device to a workspace, go to Workspace › Settings › Devices.`]})]})})}var RO=[{id:`general`,label:`Workspace details`,description:`Rename, change appearance or remove this workspace`,icon:$t},{id:`backups`,label:`Backups`,description:`Save or restore documents, relations and tree placements`,icon:gn},{id:`data`,label:`Files & storage`,description:`Connect folders and data sources, check disk usage or restore trash`,icon:Pe},{id:`db`,label:`Search & indexing`,description:`Rebuild indexes, tune search and choose embedding models`,icon:er},{id:`devices`,label:`Devices`,description:`Link devices to this workspace`,icon:Fn},{id:`sync`,label:`Synchronization`,description:`Manage device copies and resolve sync conflicts`,icon:P},{id:`services`,label:`Connected services`,description:`Configure Git, WebDAV, IMAP and other connectors`,icon:Jt},{id:`shares`,label:`Sharing & permissions`,description:`Create public links and manage workspace access`,icon:Zt},{id:`policies`,label:`Storage policies`,description:`Mirror folders of the virtual tree to physical backends`,icon:fe},{id:`hooks`,label:`Automation`,description:`Run hooks in response to workspace events`,icon:Je}],zO={embedding:`db`,trash:`data`};function BO(e){return e?zO[e]?zO[e]:RO.some(t=>t.id===e)?e:`general`:`general`}var VO=[{id:`general`,label:`Context details`,description:`Change the name, description or color, or remove this context`,icon:$t},{id:`location`,label:`Tree & path`,description:`Choose the workspace, tree and path this context opens`,icon:Zt},{id:`shares`,label:`Sharing & permissions`,description:`Choose who can access this context`,icon:ie}];function HO(e){return e&&VO.some(t=>t.id===e)?e:`general`}var UO=[{id:`identity`,label:`Identity & instructions`,description:`Set the agent’s name, role and instructions`,icon:$t},{id:`provider`,label:`AI connection`,description:`Connect a chat model provider and manage its credentials`,icon:q},{id:`models`,label:`Chat model`,description:`Choose the model and tune how it responds`,icon:Tt},{id:`tools`,label:`Tools & skills`,description:`Choose the skills and MCP tools the agent can use`,icon:Ne},{id:`access`,label:`Access & permissions`,description:`Choose which Canvas content the agent can access`,icon:k},{id:`memory`,label:`Memory`,description:`Configure how the agent remembers information`,icon:ct},{id:`integrations`,label:`Integrations`,description:`Connect mail, chat, databases and external APIs`,icon:ft}];function WO(e){return e&&UO.some(t=>t.id===e)?e:`identity`}var GO=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(`
24
24
  `),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}},KO=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 GO.handleStreamingResponse(t,{onChunk:e=>{try{GO.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)}}},qO=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 JO(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(`
25
25
  `)||``}function YO(e){return e?typeof e?.metadata?.reasoning==`string`&&e.metadata.reasoning.trim()?e.metadata.reasoning.trim():Array.isArray(e.content)?e.content.filter(e=>e?.type===`thinking`||e?.type===`reasoning`).map(e=>typeof e?.thinking==`string`?e.thinking:typeof e?.reasoning==`string`?e.reasoning:typeof e?.text==`string`?e.text:``).filter(Boolean).join(`
26
26
  `).trim():``:``}function XO(e){if(!e)return;let t=YO(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 ZO(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 QO(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:JO(e),timestamp:ZO(e.timestamp),...e.role===`assistant`?{metadata:XO(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function $O(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:QO(e?.messages||[])}}function ek(e){return{current:$O(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 qO(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new KO(e.apiKey||``,e.endpoint||`${Lr}/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 X.stream(`${Lr}/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 X.get(`${Lr}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await X.post(`${Lr}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function tk(e){return await X.get(`${Lr}/agents/${e}/access`)||null}async function nk(e,t){return await X.put(`${Lr}/agents/${e}/access`,t)}async function rk(e){return await X.post(`${Lr}/agents/${e}/access/token`)}async function ik(e){await X.delete(`${Lr}/agents/${e}/access`)}async function ak(e){return await X.get(`${Lr}/agents/${e}/tools`)||{tools:[],config:{}}}async function ok(){try{return await X.get(`${Lr}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function sk(e){return await X.get(`${Lr}/agents/${e}`)}async function ck(e){return $O(await X.get(`${Lr}/agents/${e}/session`))}async function lk(e){return await X.get(`${Lr}/agents/${e}/sessions`)}async function uk(e,t){return ek(await X.post(`${Lr}/agents/${e}/sessions`,t))}async function dk(e,t){return ek(await X.put(`${Lr}/agents/${e}/session`,t))}async function fk(e,t,n){return ek(await X.patch(`${Lr}/agents/${e}/sessions/${t}`,n))}async function pk(e,t){return ek(await X.delete(`${Lr}/agents/${e}/sessions/${t}`))}async function mk(e){return await X.get(`${Lr}/agents/${e}/skills`)||[]}async function hk(e,t){return await X.post(`${Lr}/agents/${e}/skills`,t)||[]}async function gk(e,t){return await X.delete(`${Lr}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function _k(e){return await X.post(`${Lr}/agents`,e)}async function vk(e,t){return await X.put(`${Lr}/agents/${e}`,t)}async function yk(e){await X.delete(`${Lr}/agents/${e}`)}async function bk(e){return await X.post(`${Lr}/agents/${e}/start`)}async function xk(e){return await X.post(`${Lr}/agents/${e}/stop`)}async function Sk(e){return await X.get(`${Lr}/agents/${e}/status`)}async function Ck(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 X.stream(`${Lr}/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(`
27
27
 
28
28
  `);f=t.pop()||``;for(let e of t){let t=e.split(`
29
- `).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||{},...XO(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function wk(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 X.post(`${Lr}/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:JO(i),metadata:XO(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function Tk(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function Ek(){return await X.get(`${Lr}/voice/status`)}async function Dk(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 X.post(`${Lr}/agents/${e}/voice${o}`,r)}var Ok=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:RO,load:async()=>(await Ni()).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:VO,load:async()=>(await ps()).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:UO,load:async()=>(await ok()).map(e=>({id:e.id,label:e.label||e.name}))}];function kk({to:e,label:t,description:n,icon:r}){return(0,$.jsxs)(Nu,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,$.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,$.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,$.jsx)(Dt,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function Ak({group:e,query:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(`loading`),[c,l]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>dT(t,e.label,n.label,n.description));return u.length?(0,$.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,$.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,$.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,$.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,$.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,$.jsx)(kk,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function jk(){let{state:e}=PT(),[t,n]=(0,Q.useState)(``),r=lT.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>dT(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Ok.some(e=>e.sections.some(n=>dT(t,e.label,n.label,n.description)));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,$.jsx)(qw,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,$.jsx)(Y,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(kk,{to:e.path,...e},e.path))})]},e.id)),Ok.map(e=>(0,$.jsx)(Ak,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(kk,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Mk=[{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`}],Nk=`/wallpapers`;function Pk(e){return Mk.find(t=>t.id===e)}function Fk(e,t={}){let n=typeof e==`string`?Pk(e):e;if(!n)return null;let{base:r=Nk,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 Ik(e,t=Nk){let n=typeof e==`string`?Pk(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var Lk=[{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`}],Rk=`canvas:wallpaper`,zk=`canvas-wallpaper`,Bk=`settings`,Vk=`builtin:`,Hk=Mk;function Uk(e){return Ik(e)??``}function Wk(e){return`${Vk}${e}`}function Gk(e){return e?.startsWith(Vk)?e.slice(8):null}function Kk(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function qk(){try{let e=localStorage.getItem(Rk);if(e){let t=Kk(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var Jk=qk(),Yk=null;function Xk(){return Jk}async function Zk(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(zk,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(Bk),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(Bk,e?`readwrite`:`readonly`),a=i.objectStore(Bk),o=e?a.put(e,Rk):a.get(Rk);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function Qk(){try{localStorage.removeItem(Rk)}catch{}}function $k(){return Yk||=(async()=>{try{let e=Kk(await Zk());e?Jk=e:await Zk(Jk),Qk()}catch{}return sA(Jk),Jk})(),Yk.then(()=>Jk)}async function eA(e){await $k(),await Zk(e),Jk=e,Qk(),sA(e)}function tA(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var nA=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function rA(e){if(!e)return null;let t=Gk(e);if(t===null)return`url("${e}")`;let n=Pk(t);if(!n)return null;let r=`url("${Fk(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!nA||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Fk(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function iA(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var aA=null;function oA(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function sA(e=Xk()){let t=document.documentElement.style,n=aA,r=e.image;if(r?.startsWith(`data:`))try{aA?.dataUrl!==r&&(aA={dataUrl:r,objectUrl:URL.createObjectURL(oA(r))}),r=aA.objectUrl}catch{aA=null,r=null}else aA=null;let i=rA(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,iA(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==aA&&URL.revokeObjectURL(n.objectUrl)}var cA=[{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.`}],lA=`canvas:treeStyle`;function uA(){try{let e=localStorage.getItem(lA);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var dA=uA(),fA=new Set;function pA(){return dA}function mA(e){try{e===`cards`?localStorage.removeItem(lA):localStorage.setItem(lA,e)}catch{}dA=e;for(let e of fA)e()}function hA(e){fA.add(e);let t=t=>{(t.key===lA||t.key===null)&&(dA=uA(),e())};return window.addEventListener(`storage`,t),()=>{fA.delete(e),window.removeEventListener(`storage`,t)}}function gA(){return(0,Q.useSyncExternalStore)(hA,pA,()=>`cards`)}function _A(){let e=gA(),t=l_();return e===`accordion`||e===`accordion-mobile`&&t}var vA=[{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)`]}],yA=vA.map(e=>e.id),bA=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],xA=[{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`}],SA={theme:`canvas`,scheme:`light`,density:`auto`},CA=`canvas.ui.theme`;function wA(e){return typeof e==`string`&&yA.includes(e)}function TA(e){return e===`light`||e===`dark`||e===`system`}function EA(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function DA(e){let t=typeof e==`object`&&e?e:{};return{theme:wA(t.theme)?t.theme:SA.theme,scheme:TA(t.scheme)?t.scheme:SA.scheme,density:EA(t.density)?t.density:SA.density}}var OA=`(prefers-color-scheme: dark)`;function kA(){return typeof document<`u`}function AA(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(OA).matches}function jA(e){return e===`system`?AA()?`dark`:`light`:e}function MA(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(OA),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function NA(e){return MA(e)}function PA(){return AA()?`dark`:`light`}function FA(){return`light`}function IA(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 LA(e,t=kA()?document.documentElement:void 0){let n=jA(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,IA(t),n):n}function RA(e,t=kA()?document.documentElement:void 0){if(!t||typeof window>`u`)return LA(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=LA(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function zA(e){let t=e??HA();if(!t)return SA;try{let e=t.getItem(CA);return e?DA(JSON.parse(e)):SA}catch{return SA}}function BA(e,t){let n=t??HA();if(n)try{n.setItem(CA,JSON.stringify(e))}catch{}}function VA(e){let t=e??HA();if(t)try{t.removeItem(CA)}catch{}}function HA(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function UA({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Q.useState)(()=>({...zA(n),...t})),o=(0,Q.useSyncExternalStore)(NA,PA,FA),s=i.scheme===`system`?o:i.scheme;(0,Q.useEffect)(()=>{RA({...i,scheme:s})},[i,s]),(0,Q.useEffect)(()=>{r&&BA(i,n)},[i,r,n]);let c=(0,Q.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Q.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Q.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Q.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?PA():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Q.useCallback)(()=>{VA(n),a(SA)},[n]),p=(0,Q.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,$.jsx)(Hs.Provider,{value:p,children:e})}var WA={system:Fn,light:Rt,dark:me};function GA(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Us(),c=qg(),l=xT(),u=gA(),d=AT();return(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,$.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:vA.map(t=>{let n=t.id===e;return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:J(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,$.jsx)(oe,{className:`size-4 shrink-0 text-primary`})]}),(0,$.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,$.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,$.jsx)(XA,{options:bA.map(e=>{let t=WA[e.id];return{id:e.id,label:e.name,icon:(0,$.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,$.jsx)(XA,{options:xA.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:xA.find(e=>e.id===n)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,$.jsx)(XA,{options:fT.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:yT}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:fT.find(e=>e.id===l)?.description}),l===`strip`&&(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,$.jsx)(XA,{options:ST.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:OT}),(0,$.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[ST.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,$.jsx)(XA,{options:cA.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:mA}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:cA.find(e=>e.id===u)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,$.jsx)(XA,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:Gg}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,$.jsx)(KA,{}),(0,$.jsx)(`section`,{children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s(),Gg(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function KA(){let[e,t]=(0,Q.useState)(Xk),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=!1;return $k().then(()=>{e||(t(Xk()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await tA(n)}:e;await eA(i),t(i),r(null)}catch(e){r(e instanceof Error&&e.name!==`QuotaExceededError`?e.message:`Could not store the wallpaper. Free some browser storage or try a smaller image.`)}finally{c.current=!1,s(!1)}}},u=t=>{t&&l(e,t)},d=e.image!==null&&Gk(e.image)===null,f=rA(e.image);return(0,$.jsx)(`section`,{children:(0,$.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,$.jsx)(YA,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,$.jsx)(JA,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,$.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),Hk.map(t=>(0,$.jsx)(JA,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:Gk(e.image)===t.id,onSelect:()=>l({...e,image:Wk(t.id)}),children:(0,$.jsx)(`img`,{src:Uk(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,$.jsx)(JA,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,$.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,$.jsx)(qA,{}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:iA(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,$.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>l({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,$.jsx)(XA,{options:Lk.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function qA(){let e=Hk.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function JA({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:J(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,$.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,$.jsx)(oe,{className:`size-3`})})]})}function YA({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function XA({options:e,value:t,onChange:n}){return(0,$.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:J(`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 ZA(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`Appearance`,onBack:OO(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,$.jsx)(GA,{})]})}var QA={previousTree:`Alt+Q`,nextTree:`Alt+W`},$A=`canvas:key-bindings`,ej=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function tj(){try{let e=JSON.parse(localStorage.getItem($A)||`{}`),t={...QA};for(let n of Object.keys(t))(e[n]===``||ej.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...QA}:t}catch{return{...QA}}}function nj(e){localStorage.setItem($A,JSON.stringify(e))}function rj(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 ij(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function aj(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function oj(){let[e,t]=(0,Q.useState)(tj),[n,r]=(0,Q.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{nj(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`Key bindings`,onBack:OO(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,$.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,$.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||QA[t].slice(-1)}`:``}),children:[(0,$.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]}),(0,$.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||QA[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,$.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...QA}),children:`Restore defaults`}),(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var sj=`offline-content-v1`,cj=`offline-api-v1`,lj=1073741824,uj={enabled:!1,budgetBytes:4*lj,excludedWorkspaces:[]},dj=1e3;function fj(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function pj(e,t,n){return`${e}:${t}:${fj(n)}`}var mj=`canvas-offline`,hj=2,gj=null;function _j(){return gj||(gj=new Promise((e,t)=>{let n=indexedDB.open(mj,hj);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(),gj=null},e(n.result)},n.onerror=()=>{gj=null,t(n.error)}}),gj)}function vj(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function yj(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function bj(e,t){return yj((await _j()).transaction(e).objectStore(e).get(t))}async function xj(e){return yj((await _j()).transaction(e).objectStore(e).getAll())}async function Sj(e,t,n){let r=(await _j()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),vj(r)}async function Cj(e,t){let n=(await _j()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),vj(n)}async function wj(e){let t=(await _j()).transaction(e,`readwrite`);return t.objectStore(e).clear(),vj(t)}async function Tj(){try{let e=await bj(`config`,`settings`);return e?{...uj,...e}:uj}catch{return uj}}async function Ej(e){await Sj(`config`,e,`settings`)}async function Dj(e,t){let n=(await _j()).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 vj(n)}async function Oj(e){let t=await xj(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-dj)),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(cj),caches.open(sj)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await Cj(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await Cj(`entries`,e.url)})])}async function kj(){let e=await xj(`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 Aj(){await Promise.all([caches.delete(sj),caches.delete(cj)]),await wj(`entries`),await wj(`scopes`)}async function jj(){return xj(`scopes`)}async function Mj(e){return bj(`scopes`,e)}async function Nj(e){await Sj(`scopes`,e)}async function Pj(e){let t=await bj(`scopes`,e);await Cj(`scopes`,e),t?.urls.length&&await Fj(t.urls)}async function Fj(e){let t=await xj(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await Dj(r,!1)}var Ij=3,Lj=`data/schema/file`,Rj=128;async function zj({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await Tj();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=pj(e,n,t),s=fj(t),c=await Mj(o),l=((await Na(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===Lj),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(Ij,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Oo(e,t.id);d+=n.size,u.push(`${xr.workspaces}/${e}/documents/${t.id}/content`);try{await Zr(e,t.id,Rj),u.push(`${xr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${Rj}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await Dj(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 Nj(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await Fj(t)}return g}var Bj=[{label:`1 GB`,bytes:1*lj},{label:`2 GB`,bytes:2*lj},{label:`4 GB`,bytes:4*lj},{label:`8 GB`,bytes:8*lj}];function Vj(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/lj).toFixed(2)} GB`}function Hj(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function Uj(){let{showSuccessToast:e,showErrorToast:t}=Wr(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)({}),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useCallback)(()=>{Tj().then(r).catch(()=>{}),kj().then(a).catch(()=>{}),jj().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,Q.useEffect)(()=>{v(),Ni().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await Ej(e),Hj(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),Oj(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 Aj(),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=pj(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await zj(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${Vj(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${Vj(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},C=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},w=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),T=async e=>{await Pj(e),v()};return n?(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Wj,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:J(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,$.jsx)(mr,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,$.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,$.jsx)(oe,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Bj.map(e=>(0,$.jsx)(Z,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,$.jsxs)(`span`,{children:[Vj(i.contentBytes),` of `,Vj(n.budgetBytes),` used`]}),(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${Vj(i.pinnedBytes)} pinned`:``]})]}),(0,$.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,$.jsx)(`div`,{children:(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,$.jsx)(Yn,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(nt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Wj,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,$.jsx)(`div`,{className:`mb-3`,children:(0,$.jsxs)(Z,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,$.jsx)(Oe,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,$.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,$.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${Vj(t.bytes)}`:`listing…`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[Vj(e.bytes),e.truncated?` (partial)`:``]}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>S(w(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,$.jsx)(P,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>T(e.id),"aria-label":`Unpin ${e.id}`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,$.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Wj,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,$.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(`span`,{className:J(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,$.jsx)(In,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,$.jsx)(Z,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,$.jsx)($p,{onClose:()=>_(!1),children:(0,$.jsx)(ih,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:C,onClose:()=>_(!1)})})]}):null}function Wj({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function Gj(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`Offline`,onBack:OO(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,$.jsx)(Uj,{})]})}function Kj(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 qj({name:e,version:t,detail:n}){return(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,$.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function Jj(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!0;return X.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 ${Kj(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`About`,onBack:OO(),description:`Versions of every Canvas component this installation is running.`}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,$.jsx)(qj,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.2`}),e?.version&&(0,$.jsx)(qj,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,$.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,$.jsx)(qj,{name:e,version:`v${t}`},e))})]}),n&&(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,$.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var Yj=[`onnx`,`clip`,`blip`,`openai`],Xj=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],Zj=[{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`}],Qj=e=>`${xr.workspaces}/${encodeURIComponent(e)}/inferd`;function $j(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 eM(e){return await X.get(`${Qj(e)}/status`)}async function tM(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await X.post(`${Qj(e)}/summarize/images`,n)}async function nM(e){return await X.post(`${Qj(e)}/summarize/images/stop`,{})}async function rM(e){return await X.get(`${Qj(e)}/config`)}async function iM(e,t){return await X.put(`${Qj(e)}/config`,t)}async function aM(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 X.post(`${Qj(e)}/reindex`,n)}async function oM(e){return await X.get(`${Qj(e)}/vector-tables`)}async function sM(e,t){return await X.delete(`${Qj(e)}/vector-tables/${encodeURIComponent(t)}`)}async function cM(){return await X.get(`${xr.inferd}/config`)}async function lM(e){return await X.put(`${xr.inferd}/config`,e)}async function uM(){return await X.get(`${xr.inferd}/defaults`)}async function dM(e){return await X.put(`${xr.inferd}/defaults`,e)}async function fM(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await X.post(`${xr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function pM(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await X.post(`${xr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var mM=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,hM=`font-semibold uppercase tracking-[0.08em]`,gM={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`}},_M=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],vM=[{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.`}],yM=12e4;function bM(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 xM({title:e,hint:t}){return(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`h3`,{className:J(`text-[11px] text-muted-foreground`,hM),children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function SM({overridden:e,source:t}){return e?(0,$.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function CM({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,$.jsx)(SM,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,$.jsx)(Y,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:J(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,$.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function wM({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,$.jsx)(SM,{overridden:n})]})}function TM({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,Q.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,$.jsx)(SM,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,$.jsxs)($.Fragment,{children:[`Stored: `,(0,$.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,$.jsx)(Y,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function EM({open:e,onClick:t,label:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,$.jsx)(Xe,{className:J(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var DM={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function OM({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}=Vr(),[f,p]=(0,Q.useState)(()=>structuredClone(e)),[m,h]=(0,Q.useState)(new Set),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},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?gM[i.type]?.url?.key:void 0,o=a?bM(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await fM(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 pM(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)}},L=(0,Q.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?gM[i]?.url?.key:void 0;if(!a)continue;let o=bM(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),R=(0,Q.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),z=async()=>{if(L.length>0){d({title:`Fix the endpoint first`,description:L.join(` · `),variant:`destructive`});return}await u($j(f,m)),h(new Set)},ee=e=>T(t=>t===e?null:e);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,$.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,$.jsx)(W,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,$.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(xM,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,$.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`span`,{className:J(`absolute inset-y-0 left-0 w-[3px]`,DM[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:J(`text-[11px]`,hM),children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,$.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,$.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,$.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,$.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,$.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,$.jsxs)(Z,{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,$.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,$.jsx)(EM,{open:m,onClick:()=>ee(p),label:`Edit ${e}`})]})]}),m&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,$.jsx)(SM,{overridden:s.provider!==void 0,source:u.provider})]}),(0,$.jsxs)(`select`,{className:mM,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]})]}),(0,$.jsx)(CM,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,$.jsx)(CM,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,$.jsx)(CM,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,$.jsx)(wM,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,$.jsx)(wM,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(xM,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=Xj.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?gM[l]:void 0,d=u?.url?bM(n[u.url.key]):null,p={...r,...n},h=_M.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,$.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(EM,{open:s,onClick:()=>ee(o),label:`Edit ${e}`})]})]}),s&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,$.jsx)(SM,{overridden:n.type!==void 0,source:r.type})]}),(0,$.jsxs)(`select`,{className:mM,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),Yj.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),l&&!Yj.includes(l)&&(0,$.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,$.jsx)(CM,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,$.jsx)(CM,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,$.jsx)(SM,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,$.jsxs)(`select`,{className:mM,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),vM.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:vM.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,$.jsx)(CM,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??yM,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,$.jsx)(Y,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,$.jsx)(TM,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[`Not used by type `,(0,$.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,$.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,$.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,$.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),Zj.filter(e=>!D.includes(e.id)).map(e=>(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:R?`default`:`outline`,onClick:z,disabled:s||!R||L.length>0,children:s?`Saving…`:l}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!R,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:L.length>0?(0,$.jsxs)(`span`,{className:`font-medium text-destructive`,children:[L.length,` endpoint `,L.length===1?`needs`:`need`,` fixing`]}):R?`Unsaved changes`:`Everything saved`})]})]})}function kM(){let{showToast:e}=Vr(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=(0,Q.useCallback)(()=>cM().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,Q.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,$.jsx)(qw,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:OO(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,$.jsx)(OM,{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 lM(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 AM(){let e=pl(),{showToast:t}=Vr(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,Q.useState)(i),[c,l]=(0,Q.useState)(a),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),g=(0,Q.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await X.get(e,{skipAuth:!0,headers:_()});d(t);let n=await X.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,Q.useRef)(v);return(0,Q.useEffect)(()=>{y.current()},[]),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(qw,{onBack:OO(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,$.jsx)(Z,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,$.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,$.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,$.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,$.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,$.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,$.jsx)(fd,{className:`mt-8`})]})}function jM(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 MM(){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 NM={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?`${xr.admin.users}?${n}`:xr.admin.users;return await X.get(r)},async getUser(e){return await X.get(`${xr.admin.users}/${e}`)},async createUser(e){return await X.post(xr.admin.users,e)},async updateUser(e,t){return await X.put(`${xr.admin.users}/${e}`,t)},async deleteUser(e){await X.delete(`${xr.admin.users}/${e}`)}},PM={async listAllWorkspaces(){return await X.get(xr.admin.workspaces)},async createWorkspace(e){return await X.post(xr.admin.workspaces,e)},async deleteWorkspace(e){await X.delete(`${xr.admin.workspaces}/${e}`)}},FM={async getLogs(e={}){return(await X.get(`${xr.admin.logs}${jM(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${xr.admin.logsStream}${jM(e)}`,{method:`GET`,headers:MM(),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(`
29
+ `).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||{},...XO(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function wk(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 X.post(`${Lr}/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:JO(i),metadata:XO(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function Tk(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function Ek(){return await X.get(`${Lr}/voice/status`)}async function Dk(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 X.post(`${Lr}/agents/${e}/voice${o}`,r)}var Ok=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:RO,load:async()=>(await Ni()).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:VO,load:async()=>(await ps()).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:UO,load:async()=>(await ok()).map(e=>({id:e.id,label:e.label||e.name}))}];function kk({to:e,label:t,description:n,icon:r}){return(0,$.jsxs)(Nu,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,$.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,$.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,$.jsx)(Dt,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function Ak({group:e,query:t}){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(`loading`),[c,l]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>dT(t,e.label,n.label,n.description));return u.length?(0,$.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,$.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,$.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,$.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,$.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,$.jsx)(kk,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function jk(){let{state:e}=PT(),[t,n]=(0,Q.useState)(``),r=lT.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>dT(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=Ok.some(e=>e.sections.some(n=>dT(t,e.label,n.label,n.description)));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,$.jsx)(qw,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,$.jsx)(Y,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(kk,{to:e.path,...e},e.path))})]},e.id)),Ok.map(e=>(0,$.jsx)(Ak,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,$.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,$.jsx)(kk,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var Mk=[{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`}],Nk=`/wallpapers`;function Pk(e){return Mk.find(t=>t.id===e)}function Fk(e,t={}){let n=typeof e==`string`?Pk(e):e;if(!n)return null;let{base:r=Nk,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 Ik(e,t=Nk){let n=typeof e==`string`?Pk(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var Lk=[{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`}],Rk=`canvas:wallpaper`,zk=`canvas-wallpaper`,Bk=`settings`,Vk=`builtin:`,Hk=Mk;function Uk(e){return Ik(e)??``}function Wk(e){return`${Vk}${e}`}function Gk(e){return e?.startsWith(Vk)?e.slice(8):null}function Kk(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.image!=`string`&&t.image!==null?null:{image:t.image,fit:t.fit===`fill`||t.fit===`center`?t.fit:`cover`}}function qk(){try{let e=localStorage.getItem(Rk);if(e){let t=Kk(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var Jk=qk(),Yk=null;function Xk(){return Jk}async function Zk(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(zk,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(Bk),n.onsuccess=()=>{if(r){n.result.close();return}n.result.onversionchange=()=>n.result.close(),e(n.result)},n.onerror=()=>t(n.error),n.onblocked=()=>{r=!0,t(Error(`Close other Canvas tabs and try again.`))}});try{return await new Promise((n,r)=>{let i=t.transaction(Bk,e?`readwrite`:`readonly`),a=i.objectStore(Bk),o=e?a.put(e,Rk):a.get(Rk);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function Qk(){try{localStorage.removeItem(Rk)}catch{}}function $k(){return Yk||=(async()=>{try{let e=Kk(await Zk());e?Jk=e:await Zk(Jk),Qk()}catch{}return sA(Jk),Jk})(),Yk.then(()=>Jk)}async function eA(e){await $k(),await Zk(e),Jk=e,Qk(),sA(e)}function tA(e){if(e.size>10485760)return Promise.reject(Error(`Image too large. Choose one up to 10 MB.`));let t=e.type||(/\.gif$/i.test(e.name)?`image/gif`:``);return t.startsWith(`image/`)?new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(String(i.result)),i.onerror=()=>r(Error(`Could not read the image. Try selecting it again.`)),i.onabort=()=>r(Error(`Reading the image was cancelled.`)),i.readAsDataURL(e.type?e:e.slice(0,e.size,t))}):Promise.reject(Error(`Pick an image file (animated GIFs are supported).`))}var nA=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function rA(e){if(!e)return null;let t=Gk(e);if(t===null)return`url("${e}")`;let n=Pk(t);if(!n)return null;let r=`url("${Fk(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!nA||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${Fk(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function iA(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var aA=null;function oA(e){let t=e.indexOf(`,`);if(t<0)throw Error(`Invalid wallpaper data URL`);let n=e.slice(5,t),r=e.slice(t+1),i;if(n.endsWith(`;base64`)){let e=atob(r);i=new Uint8Array(e.length);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t)}else i=new TextEncoder().encode(decodeURIComponent(r));return new Blob([i],{type:n.split(`;`)[0]})}function sA(e=Xk()){let t=document.documentElement.style,n=aA,r=e.image;if(r?.startsWith(`data:`))try{aA?.dataUrl!==r&&(aA={dataUrl:r,objectUrl:URL.createObjectURL(oA(r))}),r=aA.objectUrl}catch{aA=null,r=null}else aA=null;let i=rA(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,iA(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==aA&&URL.revokeObjectURL(n.objectUrl)}var cA=[{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.`}],lA=`canvas:treeStyle`;function uA(){try{let e=localStorage.getItem(lA);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var dA=uA(),fA=new Set;function pA(){return dA}function mA(e){try{e===`cards`?localStorage.removeItem(lA):localStorage.setItem(lA,e)}catch{}dA=e;for(let e of fA)e()}function hA(e){fA.add(e);let t=t=>{(t.key===lA||t.key===null)&&(dA=uA(),e())};return window.addEventListener(`storage`,t),()=>{fA.delete(e),window.removeEventListener(`storage`,t)}}function gA(){return(0,Q.useSyncExternalStore)(hA,pA,()=>`cards`)}function _A(){let e=gA(),t=l_();return e===`accordion`||e===`accordion-mobile`&&t}var vA=[{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)`]}],yA=vA.map(e=>e.id),bA=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],xA=[{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`}],SA={theme:`canvas`,scheme:`light`,density:`auto`},CA=`canvas.ui.theme`;function wA(e){return typeof e==`string`&&yA.includes(e)}function TA(e){return e===`light`||e===`dark`||e===`system`}function EA(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function DA(e){let t=typeof e==`object`&&e?e:{};return{theme:wA(t.theme)?t.theme:SA.theme,scheme:TA(t.scheme)?t.scheme:SA.scheme,density:EA(t.density)?t.density:SA.density}}var OA=`(prefers-color-scheme: dark)`;function kA(){return typeof document<`u`}function AA(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(OA).matches}function jA(e){return e===`system`?AA()?`dark`:`light`:e}function MA(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(OA),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function NA(e){return MA(e)}function PA(){return AA()?`dark`:`light`}function FA(){return`light`}function IA(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 LA(e,t=kA()?document.documentElement:void 0){let n=jA(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,IA(t),n):n}function RA(e,t=kA()?document.documentElement:void 0){if(!t||typeof window>`u`)return LA(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=LA(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function zA(e){let t=e??HA();if(!t)return SA;try{let e=t.getItem(CA);return e?DA(JSON.parse(e)):SA}catch{return SA}}function BA(e,t){let n=t??HA();if(n)try{n.setItem(CA,JSON.stringify(e))}catch{}}function VA(e){let t=e??HA();if(t)try{t.removeItem(CA)}catch{}}function HA(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function UA({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,Q.useState)(()=>({...zA(n),...t})),o=(0,Q.useSyncExternalStore)(NA,PA,FA),s=i.scheme===`system`?o:i.scheme;(0,Q.useEffect)(()=>{RA({...i,scheme:s})},[i,s]),(0,Q.useEffect)(()=>{r&&BA(i,n)},[i,r,n]);let c=(0,Q.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,Q.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,Q.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,Q.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?PA():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,Q.useCallback)(()=>{VA(n),a(SA)},[n]),p=(0,Q.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,$.jsx)(Hs.Provider,{value:p,children:e})}var WA={system:Fn,light:Rt,dark:me};function GA(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Us(),c=qg(),l=xT(),u=gA(),d=AT();return(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,$.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:vA.map(t=>{let n=t.id===e;return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:J(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,$.jsx)(oe,{className:`size-4 shrink-0 text-primary`})]}),(0,$.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,$.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,$.jsx)(XA,{options:bA.map(e=>{let t=WA[e.id];return{id:e.id,label:e.name,icon:(0,$.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,$.jsx)(XA,{options:xA.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:xA.find(e=>e.id===n)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,$.jsx)(XA,{options:fT.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:yT}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:fT.find(e=>e.id===l)?.description}),l===`strip`&&(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,$.jsx)(XA,{options:ST.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:OT}),(0,$.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[ST.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,$.jsx)(XA,{options:cA.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:mA}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:cA.find(e=>e.id===u)?.description})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(YA,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,$.jsx)(XA,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:Gg}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,$.jsx)(KA,{}),(0,$.jsx)(`section`,{children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s(),Gg(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function KA(){let[e,t]=(0,Q.useState)(Xk),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=!1;return $k().then(()=>{e||(t(Xk()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await tA(n)}:e;await eA(i),t(i),r(null)}catch(e){r(e instanceof Error&&e.name!==`QuotaExceededError`?e.message:`Could not store the wallpaper. Free some browser storage or try a smaller image.`)}finally{c.current=!1,s(!1)}}},u=t=>{t&&l(e,t)},d=e.image!==null&&Gk(e.image)===null,f=rA(e.image);return(0,$.jsx)(`section`,{children:(0,$.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,$.jsx)(YA,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,$.jsx)(JA,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,$.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),Hk.map(t=>(0,$.jsx)(JA,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:Gk(e.image)===t.id,onSelect:()=>l({...e,image:Wk(t.id)}),children:(0,$.jsx)(`img`,{src:Uk(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,$.jsx)(JA,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,$.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,$.jsx)(qA,{}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:iA(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,$.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>l({...e,image:null}),className:`focus-ring rounded-md border px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:`Remove`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,$.jsx)(XA,{options:Lk.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,$.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function qA(){let e=Hk.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,$.jsxs)($.Fragment,{children:[` `,(0,$.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function JA({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:J(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,$.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,$.jsx)(oe,{className:`size-3`})})]})}function YA({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function XA({options:e,value:t,onChange:n}){return(0,$.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:J(`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 ZA(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`Appearance`,onBack:OO(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,$.jsx)(GA,{})]})}var QA={previousTree:`Alt+Q`,nextTree:`Alt+W`},$A=`canvas:key-bindings`,ej=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function tj(){try{let e=JSON.parse(localStorage.getItem($A)||`{}`),t={...QA};for(let n of Object.keys(t))(e[n]===``||ej.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...QA}:t}catch{return{...QA}}}function nj(e){localStorage.setItem($A,JSON.stringify(e))}function rj(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 ij(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function aj(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function oj(){let[e,t]=(0,Q.useState)(tj),[n,r]=(0,Q.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{nj(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`Key bindings`,onBack:OO(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,$.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,$.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||QA[t].slice(-1)}`:``}),children:[(0,$.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]}),(0,$.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||QA[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,$.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...QA}),children:`Restore defaults`}),(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var sj=`offline-content-v1`,cj=`offline-api-v1`,lj=1073741824,uj={enabled:!1,budgetBytes:4*lj,excludedWorkspaces:[]},dj=1e3;function fj(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function pj(e,t,n){return`${e}:${t}:${fj(n)}`}var mj=`canvas-offline`,hj=2,gj=null;function _j(){return gj||(gj=new Promise((e,t)=>{let n=indexedDB.open(mj,hj);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(),gj=null},e(n.result)},n.onerror=()=>{gj=null,t(n.error)}}),gj)}function vj(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function yj(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function bj(e,t){return yj((await _j()).transaction(e).objectStore(e).get(t))}async function xj(e){return yj((await _j()).transaction(e).objectStore(e).getAll())}async function Sj(e,t,n){let r=(await _j()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),vj(r)}async function Cj(e,t){let n=(await _j()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),vj(n)}async function wj(e){let t=(await _j()).transaction(e,`readwrite`);return t.objectStore(e).clear(),vj(t)}async function Tj(){try{let e=await bj(`config`,`settings`);return e?{...uj,...e}:uj}catch{return uj}}async function Ej(e){await Sj(`config`,e,`settings`)}async function Dj(e,t){let n=(await _j()).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 vj(n)}async function Oj(e){let t=await xj(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-dj)),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(cj),caches.open(sj)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await Cj(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await Cj(`entries`,e.url)})])}async function kj(){let e=await xj(`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 Aj(){await Promise.all([caches.delete(sj),caches.delete(cj)]),await wj(`entries`),await wj(`scopes`)}async function jj(){return xj(`scopes`)}async function Mj(e){return bj(`scopes`,e)}async function Nj(e){await Sj(`scopes`,e)}async function Pj(e){let t=await bj(`scopes`,e);await Cj(`scopes`,e),t?.urls.length&&await Fj(t.urls)}async function Fj(e){let t=await xj(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await Dj(r,!1)}var Ij=3,Lj=`data/schema/file`,Rj=128;async function zj({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await Tj();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=pj(e,n,t),s=fj(t),c=await Mj(o),l=((await Na(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===Lj),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(Ij,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await Oo(e,t.id);d+=n.size,u.push(`${xr.workspaces}/${e}/documents/${t.id}/content`);try{await Zr(e,t.id,Rj),u.push(`${xr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${Rj}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await Dj(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 Nj(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await Fj(t)}return g}var Bj=[{label:`1 GB`,bytes:1*lj},{label:`2 GB`,bytes:2*lj},{label:`4 GB`,bytes:4*lj},{label:`8 GB`,bytes:8*lj}];function Vj(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/lj).toFixed(2)} GB`}function Hj(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function Uj(){let{showSuccessToast:e,showErrorToast:t}=Wr(),[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)({}),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),v=(0,Q.useCallback)(()=>{Tj().then(r).catch(()=>{}),kj().then(a).catch(()=>{}),jj().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,Q.useEffect)(()=>{v(),Ni().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await Ej(e),Hj(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),Oj(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 Aj(),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=pj(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await zj(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${Vj(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${Vj(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},C=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},w=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),T=async e=>{await Pj(e),v()};return n?(0,$.jsxs)(`div`,{className:`space-y-8`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Wj,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:J(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,$.jsx)(mr,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,$.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,$.jsx)(oe,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Bj.map(e=>(0,$.jsx)(Z,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,$.jsxs)(`span`,{children:[Vj(i.contentBytes),` of `,Vj(n.budgetBytes),` used`]}),(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${Vj(i.pinnedBytes)} pinned`:``]})]}),(0,$.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,$.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,$.jsx)(`div`,{children:(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,$.jsx)(Yn,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(nt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Wj,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,$.jsx)(`div`,{className:`mb-3`,children:(0,$.jsxs)(Z,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,$.jsx)(Oe,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,$.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,$.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,$.jsx)(Yn,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${Vj(t.bytes)}`:`listing…`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[Vj(e.bytes),e.truncated?` (partial)`:``]}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>S(w(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,$.jsx)(P,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,onClick:()=>T(e.id),"aria-label":`Unpin ${e.id}`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,$.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(Wj,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,$.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,$.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,$.jsx)(`span`,{className:J(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,$.jsx)(In,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,$.jsx)(Z,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,$.jsx)($p,{onClose:()=>_(!1),children:(0,$.jsx)(ih,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:C,onClose:()=>_(!1)})})]}):null}function Wj({title:e,description:t}){return(0,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function Gj(){return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`Offline`,onBack:OO(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,$.jsx)(Uj,{})]})}function Kj(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 qj({name:e,version:t,detail:n}){return(0,$.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,$.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function Jj(){let[e,t]=(0,Q.useState)(null),[n,r]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!0;return X.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 ${Kj(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,$.jsx)(qw,{className:`mb-6`,title:`About`,onBack:OO(),description:`Versions of every Canvas component this installation is running.`}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,$.jsx)(qj,{name:`Canvas Web`,detail:`this interface`,version:`v2.26.4`}),e?.version&&(0,$.jsx)(qj,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,$.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,$.jsx)(qj,{name:e,version:`v${t}`},e))})]}),n&&(0,$.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,$.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var Yj=[`onnx`,`clip`,`blip`,`openai`],Xj=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],Zj=[{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`}],Qj=e=>`${xr.workspaces}/${encodeURIComponent(e)}/inferd`;function $j(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 eM(e){return await X.get(`${Qj(e)}/status`)}async function tM(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await X.post(`${Qj(e)}/summarize/images`,n)}async function nM(e){return await X.post(`${Qj(e)}/summarize/images/stop`,{})}async function rM(e){return await X.get(`${Qj(e)}/config`)}async function iM(e,t){return await X.put(`${Qj(e)}/config`,t)}async function aM(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 X.post(`${Qj(e)}/reindex`,n)}async function oM(e){return await X.get(`${Qj(e)}/vector-tables`)}async function sM(e,t){return await X.delete(`${Qj(e)}/vector-tables/${encodeURIComponent(t)}`)}async function cM(){return await X.get(`${xr.inferd}/config`)}async function lM(e){return await X.put(`${xr.inferd}/config`,e)}async function uM(){return await X.get(`${xr.inferd}/defaults`)}async function dM(e){return await X.put(`${xr.inferd}/defaults`,e)}async function fM(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await X.post(`${xr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function pM(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await X.post(`${xr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var mM=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,hM=`font-semibold uppercase tracking-[0.08em]`,gM={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`}},_M=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],vM=[{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.`}],yM=12e4;function bM(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 xM({title:e,hint:t}){return(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`h3`,{className:J(`text-[11px] text-muted-foreground`,hM),children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function SM({overridden:e,source:t}){return e?(0,$.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function CM({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,$.jsx)(SM,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,$.jsx)(Y,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:J(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,$.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function wM({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,$.jsx)(SM,{overridden:n})]})}function TM({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,Q.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,$.jsx)(SM,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,$.jsxs)($.Fragment,{children:[`Stored: `,(0,$.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,$.jsx)(Y,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function EM({open:e,onClick:t,label:n}){return(0,$.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,$.jsx)(Xe,{className:J(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var DM={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function OM({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}=Vr(),[f,p]=(0,Q.useState)(()=>structuredClone(e)),[m,h]=(0,Q.useState)(new Set),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,Q.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},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?gM[i.type]?.url?.key:void 0,o=a?bM(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await fM(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 pM(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)}},L=(0,Q.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?gM[i]?.url?.key:void 0;if(!a)continue;let o=bM(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),R=(0,Q.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),z=async()=>{if(L.length>0){d({title:`Fix the endpoint first`,description:L.join(` · `),variant:`destructive`});return}await u($j(f,m)),h(new Set)},ee=e=>T(t=>t===e?null:e);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,$.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,$.jsx)(W,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,$.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(xM,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,$.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,$.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(`span`,{className:J(`absolute inset-y-0 left-0 w-[3px]`,DM[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:J(`text-[11px]`,hM),children:e}),(0,$.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,$.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,$.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,$.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,$.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,$.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,$.jsxs)(Z,{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,$.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,$.jsx)(EM,{open:m,onClick:()=>ee(p),label:`Edit ${e}`})]})]}),m&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,$.jsx)(SM,{overridden:s.provider!==void 0,source:u.provider})]}),(0,$.jsxs)(`select`,{className:mM,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]})]}),(0,$.jsx)(CM,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,$.jsx)(CM,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,$.jsx)(CM,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,$.jsx)(wM,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,$.jsx)(wM,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(xM,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,$.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=Xj.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?gM[l]:void 0,d=u?.url?bM(n[u.url.key]):null,p={...r,...n},h=_M.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,$.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,$.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,$.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,$.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(EM,{open:s,onClick:()=>ee(o),label:`Edit ${e}`})]})]}),s&&(0,$.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,$.jsx)(SM,{overridden:n.type!==void 0,source:r.type})]}),(0,$.jsxs)(`select`,{className:mM,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),Yj.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),l&&!Yj.includes(l)&&(0,$.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,$.jsx)(CM,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,$.jsx)(CM,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,$.jsx)(SM,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,$.jsxs)(`select`,{className:mM,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,$.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),vM.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:vM.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,$.jsx)(CM,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??yM,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,$.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,$.jsx)(Y,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,$.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,$.jsx)(TM,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[`Not used by type `,(0,$.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,$.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,$.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,$.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,$.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(Y,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,$.jsx)(sn,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),Zj.filter(e=>!D.includes(e.id)).map(e=>(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:R?`default`:`outline`,onClick:z,disabled:s||!R||L.length>0,children:s?`Saving…`:l}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!R,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:L.length>0?(0,$.jsxs)(`span`,{className:`font-medium text-destructive`,children:[L.length,` endpoint `,L.length===1?`needs`:`need`,` fixing`]}):R?`Unsaved changes`:`Everything saved`})]})]})}function kM(){let{showToast:e}=Vr(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=(0,Q.useCallback)(()=>cM().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,Q.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,$.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,$.jsx)(qw,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:OO(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,$.jsxs)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,$.jsx)(Z,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,$.jsx)(OM,{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 lM(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 AM(){let e=pl(),{showToast:t}=Vr(),n=new URLSearchParams(e.search),r=e=>{try{let t=new URL(e);return t.pathname.includes(`/rest/v2/workspaces/`)&&!t.pathname.includes(`/rest/v2/pub/`)?t.pathname=t.pathname.replace(`/rest/v2/workspaces/`,`/rest/v2/pub/workspaces/`):t.pathname.includes(`/rest/v2/contexts/`)&&!t.pathname.includes(`/rest/v2/pub/`)&&(t.pathname=t.pathname.replace(`/rest/v2/contexts/`,`/rest/v2/pub/contexts/`)),t.toString()}catch{return e}},i=r(n.get(`url`)||``),a=sessionStorage.getItem(`sharedToken:last`)||``,[o,s]=(0,Q.useState)(i),[c,l]=(0,Q.useState)(a),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(!1),g=(0,Q.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await X.get(e,{skipAuth:!0,headers:_()});d(t);let n=await X.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,Q.useRef)(v);return(0,Q.useEffect)(()=>{y.current()},[]),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsx)(qw,{onBack:OO(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,$.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,$.jsx)(Z,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,$.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,$.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,$.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,$.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,$.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,$.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,$.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,$.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,$.jsx)(fd,{className:`mt-8`})]})}function jM(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 MM(){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 NM={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?`${xr.admin.users}?${n}`:xr.admin.users;return await X.get(r)},async getUser(e){return await X.get(`${xr.admin.users}/${e}`)},async createUser(e){return await X.post(xr.admin.users,e)},async updateUser(e,t){return await X.put(`${xr.admin.users}/${e}`,t)},async deleteUser(e){await X.delete(`${xr.admin.users}/${e}`)}},PM={async listAllWorkspaces(){return await X.get(xr.admin.workspaces)},async createWorkspace(e){return await X.post(xr.admin.workspaces,e)},async deleteWorkspace(e){await X.delete(`${xr.admin.workspaces}/${e}`)}},FM={async getLogs(e={}){return(await X.get(`${xr.admin.logs}${jM(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${xr.admin.logsStream}${jM(e)}`,{method:`GET`,headers:MM(),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(`
30
30
  `),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(`
31
31
  `));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(`
32
32
 
@@ -47,9 +47,9 @@ set -euo pipefail
47
47
  `)===i.join(`
48
48
  `),onClick:()=>n(l.split(`
49
49
  `).map(e=>e.trim()).filter(Boolean)),children:`Save exclusions`}),o>0&&(0,$.jsxs)(`button`,{type:`button`,className:`text-[11px] text-muted-foreground hover:text-foreground`,onClick:()=>f(!d),children:[d?`Hide`:`Show`,` default patterns`]})]}),d&&(0,$.jsx)(`pre`,{className:`max-h-40 overflow-auto rounded-md bg-muted/50 p-2 font-mono text-[11px] text-muted-foreground`,children:a.filter(e=>!i.includes(e)).join(`
50
- `)})]})]})}function oI({device:e,linked:t,busy:n,onLink:r,onUnlink:i,onUpdate:a}){let[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(e.name),[u,d]=(0,Q.useState)(e.description??``),f=()=>{c.trim()&&(c!==e.name||u!==(e.description??``))&&a({name:c.trim(),description:u.trim()||void 0}),s(!1)},p=()=>{l(e.name),d(e.description??``),s(!1)};return(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,$.jsx)(Fn,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[o?(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}}),(0,$.jsx)(Y,{value:u,onChange:e=>d(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,$.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground font-mono`,children:[(0,$.jsx)(`span`,{children:e.deviceId}),e.platform&&(0,$.jsx)(`span`,{children:e.platform}),e.arch&&(0,$.jsx)(`span`,{children:e.arch}),e.type&&(0,$.jsx)(`span`,{children:e.type})]})]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:f,disabled:!c.trim(),children:(0,$.jsx)(oe,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:p,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}):(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>s(!0),title:`Edit name/description`,children:(0,$.jsx)(_e,{className:`h-3.5 w-3.5`})}),t?(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:i,className:`text-destructive hover:text-destructive`,title:`Remove from workspace`,children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})}):(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:r,title:`Link to workspace`,children:(0,$.jsx)(Zt,{className:`h-3.5 w-3.5`})}),t&&(0,$.jsx)(`span`,{className:`rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary`,children:`linked`})]})]})})}function sI({allDevices:e,linkedDevices:t,isLoading:n,deviceBusy:r,onRefresh:i,onLink:a,onUnlink:o,onUpdate:s}){let c=new Set(t.map(e=>e.deviceId));return n?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading devices…`]}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[c.size,` of `,e.length,` registered device`,e.length===1?``:`s`,` linked to this workspace.`]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:i,disabled:n,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),e.length===0?(0,$.jsxs)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:[`No devices registered. Devices register themselves on first connection via `,(0,$.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]}):(0,$.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,$.jsx)(oI,{device:e,linked:c.has(e.deviceId),busy:r===e.deviceId,onLink:()=>a(e.deviceId),onUnlink:()=>o(e.deviceId),onUpdate:t=>s(e.deviceId,t)},e.deviceId))})]})}function cI({label:e,value:t,mono:n=!1}){return(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-2 border-b last:border-0`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:e}),(0,$.jsx)(`span`,{className:`text-xs text-right ${n?`font-mono`:``}`,children:t??`—`})]})}function lI({workspaceName:e,current:t,weights:n,floorMode:r,relativeMargin:i,onDone:a}){let[o,s]=(0,Q.useState)(t==null?``:String(t)),[c,l]=(0,Q.useState)(r??`relative`),[u,d]=(0,Q.useState)(i==null?`0.035`:String(i)),[f,p]=(0,Q.useState)(n?.fts==null?`2`:String(n.fts)),[m,h]=(0,Q.useState)(n?.dense==null?`1`:String(n.dense)),[g,_]=(0,Q.useState)(n?.image==null?`2`:String(n.image)),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(ZE);return(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`How photo relevance is decided`}),(0,$.jsxs)(`select`,{value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-input bg-transparent px-2 text-xs`,children:[(0,$.jsx)(`option`,{value:`relative`,children:`Relative to the best match (recommended)`}),(0,$.jsx)(`option`,{value:`absolute`,children:`Absolute distance cutoff`})]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Photo-vs-text distances shift with every query and every model, so one fixed cutoff travels badly: a value tuned for one model keeps everything (or nothing) on the next. Relative anchors on the best match for THIS query and survives a re-embed.`})]}),c===`relative`&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Window width (distance from the best match)`}),(0,$.jsx)(Y,{value:u,onChange:e=>d(e.target.value),placeholder:`0.035`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Wider keeps photos that match your query only partly, which is what a photo matching TWO things (a snowy window) looks like, since it sits further from each one than a pure example does. Too wide and everything gets in.`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:c===`relative`?`Hard ceiling (cosine distance, 0–2; blank = off)`:`Image relevance floor (cosine distance, 0–2; blank = off)`}),(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`0.95`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:c===`relative`?`Nothing beyond this counts as a match however close it is to the best one. This is what lets a search of something you have no photos of come back empty. Without it, a relative window always returns its nearest photo.`:`Lower = stricter (fewer, more-relevant photos); raise if relevant photos are missing.`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Hybrid fusion weights (0 disables a signal)`}),(0,$.jsx)(`div`,{className:`flex flex-wrap items-end gap-x-3 gap-y-2`,children:[[`lexical`,f,p],[`text semantic`,m,h],[`image`,g,_]].map(([e,t,n])=>(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:e}),(0,$.jsx)(Y,{value:t,onChange:e=>n(e.target.value),className:`h-8 w-16 font-mono text-xs`,inputMode:`decimal`})]},e))}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Ranking mix: lexical (filenames/content) · text semantics · photo matches. Equal lexical/image ranks a matching photo like a matching document.`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:async()=>{y(!0),x(null);try{let t=o.trim(),n=t===``?null:Number(t);if(n!==null&&!Number.isFinite(n)){x(`Enter a number (e.g. 0.95) or leave empty`);return}let r={fts:Number(f),dense:Number(m),image:Number(g)};if(Object.values(r).some(e=>!Number.isFinite(e)||e<0)){x(`Weights must be numbers ≥ 0`);return}let i=Number(u.trim());if(c===`relative`&&(!Number.isFinite(i)||i<=0)){x(`Window width must be a positive number (e.g. 0.035)`);return}await Xa(e,{imageMaxDistance:n,imageFloorMode:c,...c===`relative`?{imageRelativeMargin:i}:{},searchWeights:r}),x(`Saved`),a()}catch(e){x(e instanceof Error?e.message:`Failed to save`)}finally{y(!1)}},disabled:v,children:v?`Saving…`:`Save`}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:b})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>{QE(e.target.checked),C(e.target.checked)}}),(0,$.jsx)(`span`,{children:`Debug query`})]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Attaches the raw (unfloored) image distances to each search and shows them above the document list: the numbers this floor should be picked from. Local to this browser; costs a little extra work per query, so leave it off day to day.`})]})]})}function uI({stats:e,isLoading:t,onRefresh:n,workspaceName:r}){return t?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading stats…`]}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Live snapshot from synapsd. Click refresh for updated counts.`}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:n,disabled:t,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),(0,$.jsx)(mI,{workspaceName:r,vectorSpaces:Object.keys(e?.semantic?.vectorSpaces||{}),onDone:n}),e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(er,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Core Index`})]}),(0,$.jsx)(cI,{label:`Backend`,value:e.dbBackend,mono:!0}),(0,$.jsx)(cI,{label:`Status`,value:e.status}),(0,$.jsx)(cI,{label:`Path`,value:e.dbPath,mono:!0}),(0,$.jsx)(cI,{label:`Documents`,value:e.documentCount?.toLocaleString()}),(0,$.jsx)(cI,{label:`Metadata entries`,value:e.metadataCount?.toLocaleString()}),(0,$.jsx)(cI,{label:`Checksum index`,value:e.checksumIndexSize?.toLocaleString()}),(0,$.jsx)(cI,{label:`Bitmap store`,value:e.bitmapStoreSize?.toLocaleString()}),(0,$.jsx)(cI,{label:`Bitmap cache`,value:e.bitmapCacheSize?.toLocaleString()}),(0,$.jsx)(cI,{label:`Deleted (pending GC)`,value:e.deletedDocumentsCount?.toLocaleString()})]}),e.fts&&(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(Gt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Full-Text Search (LanceDB)`})]}),`ready`in e.fts&&(0,$.jsx)(cI,{label:`Ready`,value:String(e.fts.ready)}),e.fts.rowCount!==void 0&&(0,$.jsx)(cI,{label:`Row count`,value:e.fts.rowCount?.toLocaleString()}),e.fts.error&&(0,$.jsx)(cI,{label:`Error`,value:(0,$.jsx)(`span`,{className:`text-destructive`,children:e.fts.error})})]}),e.semantic&&(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(Gt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Semantic / Vector Search`})]}),(0,$.jsx)(cI,{label:`Enabled`,value:String(e.semantic.enabled)}),e.semantic.enabled&&(0,$.jsxs)($.Fragment,{children:[e.inferd?.routing?Object.entries(e.inferd.routing).map(([e,t])=>(0,$.jsx)(cI,{label:`Embeds → ${e}`,value:(0,$.jsx)(`span`,{className:`font-mono text-[11px]`,children:t.join(`, `)})},`route-${e}`)):(0,$.jsx)(cI,{label:`Text-embeddable (gap default)`,value:e.semantic.embeddableSchemas?.join(`, `)}),e.semantic.vectorSpaces&&Object.entries(e.semantic.vectorSpaces).map(([e,t])=>(0,$.jsx)(cI,{label:`Space: ${e} (${t.dim??`?`}-d)`,value:t.error?(0,$.jsx)(`span`,{className:`text-destructive`,children:t.error}):`${(t.embeddedDocs??0).toLocaleString()} docs · ${(t.chunkRows??0).toLocaleString()} vectors`},e)),(0,$.jsx)(cI,{label:`Photo relevance`,value:e.semantic.imageFloorMode===`absolute`?`absolute cutoff`:`relative ±${e.semantic.imageRelativeMargin??.035}`,mono:!0}),(0,$.jsx)(cI,{label:e.semantic.imageFloorMode===`absolute`?`Image relevance floor`:`Hard ceiling`,value:e.semantic.imageMaxDistance==null?`off`:e.semantic.imageMaxDistance,mono:!0}),(0,$.jsx)(cI,{label:`Fusion weights (lexical · text · image)`,value:`${e.semantic.searchWeights?.fts??2} · ${e.semantic.searchWeights?.dense??1} · ${e.semantic.searchWeights?.image??2}`,mono:!0}),(0,$.jsx)(lI,{workspaceName:r,current:e.semantic.imageMaxDistance,weights:e.semantic.searchWeights,floorMode:e.semantic.imageFloorMode,relativeMargin:e.semantic.imageRelativeMargin,onDone:n})]})]})]}):(0,$.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No stats available.`})]})}function dI(){let{workspaceName:e}=bl();return(0,$.jsx)(fI,{},e)}function fI(){let{workspaceName:e,tab:t}=bl(),[n,r]=zu(),i=n.get(`section`),a=[`pending`,`rules`,`hooks`,`scripts`,`runs`].find(e=>e===i),o=n.get(`handler`)||void 0,s=n.get(`run`)||void 0,c=n.get(`addRuleKind`),l=n.get(`addRulePath`),u=n.get(`addRuleTarget`),d=n.get(`addRuleStoreTo`),p=n.get(`addRuleStoreFolder`),m=(0,Q.useMemo)(()=>c===`store`||c===`download`?!l&&!d&&!p?null:{kind:c,path:l||``,storeTo:d||``,storeFolder:p||``}:l?{kind:`mirror`,path:l,target:u||`dir:/`}:null,[c,l,u,d,p]),h=(0,Q.useCallback)(()=>{r(e=>{for(let t of[`addRuleKind`,`addRulePath`,`addRuleTarget`,`addRuleStoreTo`,`addRuleStoreFolder`])e.delete(t);return e},{replace:!0})},[r]),g=gl(),{showToast:_,showProgress:v}=Vr(),y=l_(),{goBack:b}=PT(),x=BO(t);(0,Q.useEffect)(()=>{t!==x&&g(`/workspaces/${e}/settings/${x}`,{replace:!0})},[t,x,e,g]);let[S,C]=(0,Q.useState)(null),w=Op(S),[T,E]=(0,Q.useState)(0),[D,O]=(0,Q.useState)(!0),[k,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(``),[L,R]=(0,Q.useState)(``),[z,ee]=(0,Q.useState)(`#FFFFFF`),[ne,B]=(0,Q.useState)(null),[re,ie]=(0,Q.useState)(null),[ae,oe]=(0,Q.useState)([]),[V,H]=(0,Q.useState)(null),[U,se]=(0,Q.useState)([]),[W,ce]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(null),[de,fe]=(0,Q.useState)(!1),[pe,me]=(0,Q.useState)([]),[G,he]=(0,Q.useState)([]),[ge,_e]=(0,Q.useState)(!1),[ve,K]=(0,Q.useState)(null),q=e||S?.id||``,ye=(0,Q.useRef)(q);(0,Q.useEffect)(()=>{ye.current=q});let be=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t)try{let e=await za(t);oe(e.publicCanvasShares)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load shares`,variant:`destructive`})}},[_]),xe=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t){fe(!0);try{let e=await xa(t);ue(e)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load DB stats`,variant:`destructive`})}finally{fe(!1)}}},[_]),Se=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t){_e(!0);try{let[e,n]=await Promise.all([AO(),NO(t)]);me(e),he(n)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{_e(!1)}}},[_]),Ce=async e=>{K(e);try{await PO(q,e),await Se(),_({title:`Linked`,description:`Device linked to workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to link device`,variant:`destructive`})}finally{K(null)}},we=async e=>{K(e);try{await FO(q,e),he(t=>t.filter(t=>t.deviceId!==e)),_({title:`Unlinked`,description:`Device removed from workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to unlink device`,variant:`destructive`})}finally{K(null)}},Te=async(e,t)=>{K(`edit:${e}`);try{let n=await jO(e,t);me(t=>t.map(t=>t.deviceId===e?{...t,...n}:t)),_({title:`Saved`,description:`Device updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{K(null)}},Ee=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(!t)return;let[n,r]=await Promise.all([Za(t).catch(()=>null),pa(t).catch(()=>[])]);H(n),se(r.filter(e=>e.kind===`storage`))},[]),De=U.some(e=>e.resyncing);(0,Q.useEffect)(()=>{if(!w||!De||!q)return;let e=setInterval(()=>{Ee()},4e3);return()=>clearInterval(e)},[w,De,q,Ee]),(0,Q.useEffect)(()=>{let t=!1;async function n(){try{let n=await Ni();if(t)return;let r=n.find(t=>t.id===e)??n.find(t=>t.name===e);if(C(r??null),r){if(!Op(r))return;I(r.label||``),R(r.description||``),ee(r.color||`#FFFFFF`),B(r.icon??null),r.status===`active`&&await Promise.all([be(e||r.id),Ee(e||r.id)])}}catch{t||_({title:`Error`,description:`Failed to load workspace`,variant:`destructive`})}finally{t||O(!1)}}return n(),()=>{t=!0}},[e,be,Ee,_,T]),(0,Q.useEffect)(()=>{let e=()=>E(e=>e+1);return window.addEventListener(`workspaces:refresh`,e),()=>window.removeEventListener(`workspaces:refresh`,e)},[]);let Oe=(0,Q.useRef)(!1),ke=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{Oe.current=!!le||de,ke.current=ge||pe.length>0}),(0,Q.useEffect)(()=>{w&&(S?.status===`active`&&x===`db`&&q&&!Oe.current&&xe(),S?.status===`active`&&x===`devices`&&q&&!ke.current&&Se())},[w,x,q,S?.status,xe,Se]);let Ae=async e=>{if(e.preventDefault(),S){j(!0);try{await Eo(q,{label:F.trim(),description:L.trim(),color:z,icon:ne}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Saved`,description:`Workspace settings updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{j(!1)}}},je=async()=>{if(S&&window.confirm(`Destroy workspace "${S.label||S.name}"? This cannot be undone.`)){N(!0);try{await no(q),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Destroyed`,description:`${S.label||S.name} has been removed`}),g(`/workspaces`)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Destroy failed`,variant:`destructive`})}finally{N(!1)}}},Me=()=>{for(let t of[e,S?.name,S?.id])t&&Da(t,`backends`);window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:q}}))},Ne=async e=>{if(e.config?.supported!==!1){ce(`backend:${e.address}`);try{await _o(q,e.driver,e.address,{enabled:!e.enabled}),await Ee(),Me(),_({title:`Saved`,description:`${e.address} ${e.enabled?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{ce(null)}}},Pe=async(e,t,n)=>{ce(`${n}:${e.address}`);try{await _o(q,e.driver,e.address,t),await Ee()}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{ce(null)}},Fe=async e=>{let t=typeof e.config?.label==`string`&&e.config.label||e.address;if(window.confirm(`Remove backend "${t}"? No files are deleted; indexed entries remain until purged from the backends tree.`)){ce(`remove:${e.address}`);try{await Ki(q,e.driver,e.address),await Ee(),Me(),_({title:`Removed`,description:`${t} unmounted`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to remove backend`,variant:`destructive`})}finally{ce(null)}}},Ie=async e=>{ce(`resync:${e.address}`);try{await Eb(v,q,e.driver,e.address,e=>{se(t=>t.map(t=>t.driver===e.driver&&t.address===e.address?e:t))}),await Ee()}catch{}finally{ce(null)}},Le=async e=>{ce(`test:${e.address}`);try{await $a(q,e.driver,e.address),_({title:`Connected`,description:`${e.address}: credentials and root folder verified`})}catch(e){_({title:`Connection failed`,description:e instanceof Error?e.message:`Test failed`,variant:`destructive`})}finally{ce(null)}},Re=async e=>{ce(`stopsync:${e.address}`);try{await Qa(q,e.driver,e.address),await Ee(),_({title:`Sync stopped`,description:`${e.address}: indexed files are kept; Re-sync resumes where it left off`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to stop sync`,variant:`destructive`})}finally{ce(null)}},ze=async(e,t)=>{ce(`service:${e}`);try{t?await Pa(q,e):await bi(q,e),await Ee(),_({title:t?`Disabled`:`Enabled`,description:`${e} ${t?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle service`,variant:`destructive`})}finally{ce(null)}},Be=async e=>{let t=`${window.location.origin}${e.url}`;await navigator.clipboard?.writeText(t),_({title:`Copied`,description:t})},Ve=async e=>{if(S&&window.confirm(`Revoke public share for "${e.path}"?`)){ce(`share:${e.code}`);try{await qa(q,e.code),await be(q),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:q}})),_({title:`Revoked`,description:`Public canvas link no longer works`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke share`,variant:`destructive`})}finally{ce(null)}}},He=RO.find(e=>e.id===x);return D?(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`}):S?w?(0,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,$.jsx)(qw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${He.label} - ${S.label||S.name}`,description:`This workspace · ${He.description}`,backTo:`/workspaces/${e}`,onBack:y?b:void 0}),S.status!==`active`&&x!==`general`&&x!==`backups`&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to access these settings. General settings and protection remain available while stopped.`}),x===`backups`&&(0,$.jsx)(rP,{workspaceId:q,onRestored:()=>E(e=>e+1)}),x===`general`&&(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`form`,{onSubmit:Ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-id`,className:`text-sm font-medium`,children:`Workspace ID`}),(0,$.jsx)(Y,{id:`ws-id`,value:S.id,readOnly:!0,className:`font-mono text-sm`,onFocus:e=>e.currentTarget.select()})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-label`,className:`text-sm font-medium`,children:`Label`}),(0,$.jsx)(Y,{id:`ws-label`,value:F,onChange:e=>I(e.target.value),placeholder:`Workspace Label`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`ws-description`,value:L,onChange:e=>R(e.target.value),placeholder:`Description (optional)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Icon & color`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>ie({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:ne||`ph:stack-fill`,width:22,height:22,color:Nm(z)})}),(0,$.jsx)(Y,{id:`ws-color`,type:`color`,value:z,onChange:e=>ee(e.target.value),className:`h-10 w-16 p-1`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ee(Am()),children:`Randomize`})]})]}),(0,$.jsx)(Z,{type:`submit`,disabled:k||!F.trim(),children:k?`Saving...`:`Save Changes`})]}),re&&(0,$.jsx)(Zw,{x:re.x,y:re.y,current:{icon:ne??void 0,color:z},onChange:e=>{`icon`in e&&B(e.icon??null),`color`in e&&e.color&&ee(e.color)},onClose:()=>ie(null)}),(0,$.jsx)(hP,{currentMode:S.protection?.mode,workspaceId:q,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),S.status===`active`&&(0,$.jsx)(pI,{workspaceName:e}),S.status===`active`&&(0,$.jsx)(iI,{workspaceId:q}),(0,$.jsx)(XF,{workspaceId:q,workspaceName:S.label||S.name,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),(0,$.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,$.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,$.jsxs)(Z,{variant:`destructive`,disabled:M,onClick:je,children:[(0,$.jsx)(nt,{className:`mr-2 h-4 w-4`}),M?`Destroying...`:`Destroy Workspace`]})]})]}),S.status===`active`&&x===`shares`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Members`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Share this workspace with teammates by e-mail or with a whole directory group. It shows up in their workspace list on this server.`})]}),(0,$.jsx)(YF,{workspaceId:q})]}),(0,$.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Public Canvas Shares`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Active public canvas links for this workspace.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>be(),children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),ae.length===0?(0,$.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No public canvas shares. Good.`}):ae.map(e=>{let t=`${window.location.origin}${e.url}`;return(0,$.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate font-mono text-sm`,children:e.path}),(0,$.jsxs)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[e.treeName,` / `,e.treeType,` - created `,new Date(e.createdAt).toLocaleString()]}),e.lockedBy?.length>0&&(0,$.jsxs)(`div`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`locks: `,e.lockedBy.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>Be(e),children:(0,$.jsx)(A,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>window.open(t,`_blank`,`noreferrer`),children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`share:${e.code}`,onClick:()=>Ve(e),className:`text-destructive hover:text-destructive`,children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})})]})]}),(0,$.jsx)(`div`,{className:`mt-2 truncate rounded bg-muted/40 px-2 py-1 font-mono text-xs text-muted-foreground`,children:t})]},e.code)})]}),(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workspace ACL Tokens`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Generate token-based workspace access for devices, scripts, and other users.`})]}),(0,$.jsx)(GF,{workspaceId:q})]})]}),S.status===`active`&&x===`data`&&(0,$.jsxs)(`div`,{className:`space-y-3`,children:[U.map(e=>{let t=e.config||{},n=e.address,r=t.device||null,i=e.driver===`gdrive`,a=e.driver===`s3`,o=(e.driver===`file`||i||a)&&t.managed!==!0&&!ZF[n],s=ZF[n]||{title:typeof t.label==`string`&&t.label||n,description:a?`S3 bucket ${t.bucket||``}${t.prefix?`/${t.prefix}`:``}${t.endpoint?` at ${t.endpoint}`:``}. Filing copies only.`:i?`Google Drive${typeof t.account==`string`&&t.account&&t.account!==t.label?` (${t.account})`:``}, folder ${typeof t.folderId==`string`&&t.folderId?t.folderId:`root`}${e.treePath?`, mirrored at ${e.treePath}`:``}.`:o?`Local folder${r?.name?` on ${r.name}`:``}, indexed in place${e.treePath?` and mirrored at ${e.treePath}`:``}.`:`Workspace data backend.`},c=t.supported!==!1,l=n===`workspace:data`,u=c&&!l,d=u&&t.managed!==!0,p=Cm(e);return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(f,{icon:p.icon,width:16,height:16,color:p.color,className:`shrink-0`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:s.title}),!c&&(0,$.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,children:`unsupported`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s.description}),typeof t.root==`string`&&t.root&&(0,$.jsx)(`p`,{className:`mt-2 truncate font-mono text-xs text-muted-foreground`,children:t.root}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[`status: `,e.status]}),e.resyncing&&(0,$.jsxs)(`span`,{className:`flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 font-medium text-primary`,children:[(0,$.jsx)(P,{className:`h-3 w-3 animate-spin`}),`indexing`,e.progress?` ${e.progress.scanned}${e.progress.total==null?``:` / ${e.progress.total}`}`:``]}),r?.name&&(0,$.jsxs)(`span`,{title:r.id,children:[`device: `,r.name]}),t.readOnly===!0&&(0,$.jsx)(`span`,{className:`rounded bg-warning/15 px-1.5 py-0.5 font-medium text-warning`,children:`read-only`}),e.lastSyncAt&&(0,$.jsxs)(`span`,{children:[`last scan: `,new Date(e.lastSyncAt).toLocaleString()]})]}),e.lastError&&(0,$.jsx)(`p`,{className:`mt-2 text-xs text-destructive`,children:e.lastError}),t.readOnly===!0&&(0,$.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`Read-only: the web UI / REST API never deletes bytes on this backend. Destroy degrades to a reference drop. Recommended when the folder is exported elsewhere (e.g. via Samba).`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-3`,children:[e.capabilities?.sync&&c&&(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,title:`Scan this backend in the background whenever the workspace starts. Manual scans remain available when off.`,children:[`Scan on start`,(0,$.jsx)($F,{checked:t.scanOnStart===!0,disabled:W===`startup:${n}`,onClick:()=>Pe(e,{scanOnStart:t.scanOnStart!==!0},`startup`)})]}),(e.driver===`file`||i||a)&&u&&(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:i?`Poll the Drive changes feed so edits made in Drive show up without a manual re-sync.`:void 0,children:[`Watch for changes`,(0,$.jsx)($F,{checked:!!t.watch,disabled:!e.enabled||W===`watch:${n}`,onClick:()=>Pe(e,{watch:!t.watch},`watch`)})]}),d&&(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:`Read-only: Destroy never deletes bytes on this backend (references are dropped instead). Important when the folder is exported via Samba or shared otherwise.`,children:[`read-only`,(0,$.jsx)($F,{checked:t.readOnly===!0,disabled:W===`readonly:${n}`,onClick:()=>Pe(e,{readOnly:t.readOnly!==!0},`readonly`)})]}),(e.driver===`file`||e.driver===`cacache`)&&c&&(0,$.jsx)(nI,{workspaceId:q,backend:e}),e.capabilities?.test&&(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`test:${n}`,onClick:()=>Le(e),title:`Verify credentials and root folder`,children:[(0,$.jsx)(Gt,{className:`mr-2 h-3.5 w-3.5`}),W===`test:${n}`?`Testing…`:`Test`]}),e.capabilities?.sync&&(e.resyncing?(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`stopsync:${n}`,onClick:()=>Re(e),title:`Stop the running scan. Files indexed so far are kept; Re-sync later resumes where it left off (unchanged files are skipped).`,children:[(0,$.jsx)(zn,{className:`mr-2 h-3.5 w-3.5 fill-current`}),W===`stopsync:${n}`?`Stopping…`:`Stop sync`]}):(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`resync:${n}`,onClick:()=>Ie(e),children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${W===`resync:${n}`?`animate-spin`:``}`}),`Re-sync`]})),l?(0,$.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,title:`Structural workspace store; cannot be disabled`,children:`always on`}):(0,$.jsx)($F,{checked:!!e.enabled,disabled:!u||W===`backend:${n}`,onClick:()=>Ne(e)}),o&&(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:W===`remove:${n}`,title:`Unmount this folder (no files are deleted)`,onClick:()=>Fe(e),children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})]}),c&&(0,$.jsx)(lE,{value:t.removalPolicy,backends:U,source:n,destination:t.propagatedRemovalSupported===!0,onSave:async t=>{await _o(q,e.driver,e.address,{removalPolicy:t}),await Ee()}}),a&&(0,$.jsx)(mP,{workspaceId:q,backend:e,onSaved:async()=>{await Ee(),Me()}}),e.driver===`file`&&c&&!l&&(0,$.jsx)(aI,{backend:e,busy:W===`exclude:${n}`,onSave:t=>Pe(e,{exclude:t},`exclude`)})]},n)}),(0,$.jsx)(pP,{workspaceId:q,children:(0,$.jsx)(rI,{workspaceId:q})},q),(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start`,children:[(0,$.jsx)(eI,{workspaceId:q,onAdded:async()=>{await Ee(),Me()}}),(0,$.jsx)(tI,{workspaceId:q,onAdded:async()=>{await Ee(),Me()}}),(0,$.jsx)(mP,{workspaceId:q,onSaved:async()=>{await Ee(),Me()}})]}),e&&(0,$.jsx)(`section`,{className:`border-t pt-4`,children:(0,$.jsx)(dE,{workspaceName:e})})]}),S.status===`active`&&x===`db`&&(0,$.jsxs)(`div`,{className:`space-y-8`,children:[q&&(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Embeddings`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Which model turns this workspace's content into vectors, and where those vectors live.`})]}),(0,$.jsx)(EP,{workspaceId:q,workspaceName:e})]}),(0,$.jsx)(uI,{stats:le,isLoading:de,onRefresh:()=>xe(),workspaceName:e})]}),S.status===`active`&&x===`devices`&&(0,$.jsx)(sI,{allDevices:pe,linkedDevices:G,isLoading:ge,deviceBusy:ve,onRefresh:()=>Se(),onLink:Ce,onUnlink:we,onUpdate:Te}),S.status===`active`&&x===`sync`&&(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(NF,{workspaceId:q,workspaceUuid:S?.id})}),S.status===`active`&&x===`services`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[q&&(0,$.jsx)(BF,{workspaceId:q}),(0,$.jsx)(`div`,{className:`space-y-3`,children:QF.map(e=>{let t=V?.[e.id]||V?.[e.id===`git`?`dotfiles`:e.id===`webdav`?`home`:`imap`],n=!!t?.enabled;return(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Jt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:e.title})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:e.description}),(0,$.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[`initialized: `,t?.initialized?`true`:`false`]})]}),(0,$.jsx)($F,{checked:n,disabled:W===`service:${e.id}`,onClick:()=>ze(e.id,n)})]})},e.id)})}),(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(WF,{workspaceId:q,enabled:!!(V?.imap?.enabled||V?.imapSync?.enabled)})})]}),S.status===`active`&&x===`policies`&&(0,$.jsx)(yF,{workspaceId:q}),S.status===`active`&&x===`hooks`&&(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(BP,{workspaceId:q,prefillRule:m,onPrefillConsumed:h,initialSection:a,initialRunsHandler:o,initialRunId:s})})]})}):(0,$.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,$.jsx)(`h1`,{className:`font-semibold`,children:S.label||S.name}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Workspace settings are available to owners and admins.`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>g(`/workspaces/${e}`),children:`Back to workspace`})]}):(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Workspace not found`})}function pI({workspaceName:e}){let{selected:t,setSelected:n,tree:r,setTree:i,toggle:a}=BT(),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(null);return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Default folders`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Create a set of common folders with matching icons and colors.`}),(0,$.jsx)(`div`,{className:`mt-3`,children:(0,$.jsx)(VT,{selected:t,onToggle:a,tree:r,onTreeChange:i,disabled:o,idPrefix:`settings-default-folders`})}),(0,$.jsxs)(`div`,{className:`mt-3 flex items-center gap-3`,children:[(0,$.jsx)(Z,{type:`button`,size:`sm`,disabled:o||t.size===0,onClick:async()=>{s(!0),l(null);let{ok:i,failed:a}=await zT(e,Array.from(t),r);s(!1),l(a?`${i} created, ${a} failed`:`${i} folder(s) created`),n(new Set)},children:o?`Creating…`:`Create ${t.size||``} folder(s)`}),c&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:c})]})]})}function mI({workspaceName:e,vectorSpaces:t,onDone:n}){let[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),s=async(e,t,r)=>{if(!(r&&!window.confirm(r))){i(e),o(null);try{let e=await t();o(e.message),n()}catch(e){o(e instanceof Error?e.message:`Reindex failed`)}finally{i(null)}}},c=[{title:`Bitmaps`,ops:[{key:`timelines`,label:`Reindex timelines`,description:`Rebuild the created/updated timelines from document data.`,fn:()=>LM(e)},{key:`mime`,label:`Reindex MIME types`,description:`Rebuild the per-MIME-type presence bitmaps (data/mime/*) from stored docs. Backfills blobs indexed before mime bitmaps existed.`,fn:()=>BM(e)}]},{title:`Full-text (BM25)`,ops:[{key:`fts`,label:`Backfill`,description:`Index documents missing from the full-text table. Fast, skips already-indexed.`,fn:()=>RM(e)},{key:`fts-rebuild`,label:`Rebuild`,description:`Wipe the full-text table and rebuild from scratch. Use when counts drift.`,confirm:`Wipe the FTS index and rebuild it from scratch?`,fn:()=>RM(e,!0)},{key:`fts-optimize`,label:`Optimize`,description:`Compact fragments + prune old versions of the full-text table.`,fn:()=>zM(e,`fts`)}]},...t.length>0?[{title:`Vector tables (LanceDB)`,ops:t.map(t=>({key:`${t}-optimize`,label:`Optimize ${t}`,description:`Compact fragments + prune old versions of the '${t}' vector table and rebuild its ANN index.`,fn:()=>zM(e,t)}))}]:[]];return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,$.jsx)(P,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Index maintenance`})]}),(0,$.jsx)(`p`,{className:`mb-3 text-xs text-muted-foreground`,children:`Runs against this workspace. Reindex operations are idempotent.`}),(0,$.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e.title}),(0,$.jsx)(`div`,{className:`space-y-2`,children:e.ops.map(e=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,className:`w-44 justify-start`,disabled:r!==null,onClick:()=>s(e.key,e.fn,e.confirm),children:[r===e.key&&(0,$.jsx)(P,{className:`mr-2 h-3 w-3 animate-spin`}),e.label]}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 basis-52 text-xs text-muted-foreground`,children:e.description})]},e.key))})]},e.title))}),a&&(0,$.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:a})]})}var hI=[{value:`documentRead`,label:`Read`},{value:`documentWrite`,label:`Write`},{value:`documentReadWrite`,label:`Read & write`}];function gI(){let{contextId:e,tab:t}=bl(),[n]=zu(),r=n.get(`ownerId`)||void 0,i=gl(),{showToast:a}=Vr(),{selectEntity:o,goBack:s,closeM2:c}=PT(),l=l_(),u=HO(t),d=r?`?ownerId=${encodeURIComponent(r)}`:``;(0,Q.useEffect)(()=>{t!==u&&e&&i(`/contexts/${e}/settings/${u}${d}`,{replace:!0})},[t,u,e,d,i]);let[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(!0),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(``),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(),[M,N]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(``),[z,ee]=(0,Q.useState)(hI[0].value),[ne,B]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return Cs(e,r).then(e=>{t||(p(e),o(e.id),x(e.name||``),C(e.description||``),T(typeof e.metadata?.ui?.color==`string`?e.metadata.ui.color:null),D(e.url||``),k(e.baseUrl||``))}).catch(()=>{t||a({title:`Error`,description:`Failed to load context`,variant:`destructive`})}).finally(()=>{t||h(!1)}),()=>{t=!0}},[e,r,o,a]);let re=(t=e)=>{t&&(I(!0),Ls(t).then(N).catch(()=>N([])).finally(()=>I(!1)))};(0,Q.useEffect)(()=>{if(u!==`shares`||!e)return;let t=!1;return Ls(e).then(e=>{t||N(e)}).catch(()=>{t||N([])}),()=>{t=!0}},[u,e]);let ie=async t=>{if(t.preventDefault(),e){_(!0);try{let t=await ns(e,{name:b.trim(),description:S.trim(),metadata:{...f?.metadata,ui:{...f?.metadata?.ui,color:w}}},r);p(t),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},ae=async t=>{if(t.preventDefault(),e){_(!0);try{await Promise.all([is(e,E.trim(),r,A),ls(e,{baseUrl:O.trim()||null},r)]),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context URL updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},oe=async()=>{if(e&&window.confirm(`Delete context "${e}"? This cannot be undone.`)){y(!0);try{await As(e,r),c(),o(null),a({title:`Deleted`,description:`Context "${e}" removed`}),i(`/contexts`,{replace:!0})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{y(!1)}}},V=async t=>{if(t.preventDefault(),!(!e||!L.trim())){B(`grant`);try{await Fs(e,L.trim(),z),R(``),re(),a({title:`Shared`,description:`Access granted to ${L.trim()}`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{B(null)}}},H=async t=>{if(e&&window.confirm(`Revoke ${t.userEmail}'s access to "${e}"?`)){B(t.userEmail);try{await $o(e,t.userEmail),re(),a({title:`Revoked`,description:`${t.userEmail} no longer has access`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke access`,variant:`destructive`})}finally{B(null)}}};if(m)return(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!f)return(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Context not found`});let U=VO.find(e=>e.id===u),se=`/contexts/${e}${d}`;return(0,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,$.jsx)(qw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${U.label} - ${f.name||f.id}`,description:U.description,backTo:se,onBack:l?s:void 0}),u===`general`&&(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`form`,{onSubmit:ie,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Context ID`}),(0,$.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:f.id})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-name`,className:`text-sm font-medium`,children:`Name`}),(0,$.jsx)(Y,{id:`ctx-name`,value:b,onChange:e=>x(e.target.value),placeholder:`My Context`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`ctx-description`,value:S,onChange:e=>C(e.target.value),placeholder:`Optional description`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-color`,className:`text-sm font-medium`,children:`Color`}),(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-2`,children:[(0,$.jsx)(Y,{id:`ctx-color`,type:`color`,value:/^#[0-9a-f]{6}$/i.test(w||f.color||``)?w||f.color:`#808080`,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`,disabled:g}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:g||w===null,onClick:()=>T(null),children:`Use inherited color`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:w===null?`Using the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Workspace`}),(0,$.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 text-sm text-muted-foreground`,children:f.workspaceName||f.workspaceId||f.workspace})]}),(0,$.jsx)(Z,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),(0,$.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,$.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,$.jsxs)(Z,{variant:`destructive`,disabled:v,onClick:oe,children:[(0,$.jsx)(nt,{className:`mr-2 h-4 w-4`}),v?`Deleting...`:`Delete Context`]})]})]}),u===`location`&&(0,$.jsxs)(`form`,{onSubmit:ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-url`,className:`text-sm font-medium`,children:`URL`}),(0,$.jsx)(ah,{id:`ctx-url`,value:E,onChange:D,fixedWorkspaceName:f.workspaceName,pickerTitle:`Switch context to…`,placeholder:`workspace://path`,onPickTarget:(e,t)=>{D(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),j(t.treeName)}}),A&&(0,$.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Destination tree: `,A]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`label`,{htmlFor:`ctx-base-url`,className:`text-sm font-medium`,children:[`Base URL `,(0,$.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,$.jsx)(ah,{id:`ctx-base-url`,value:O,onChange:k,fixedWorkspaceName:f.workspaceName,placeholder:`workspace://base/path`,pickerTitle:`Pick a base path…`})]}),(0,$.jsx)(Z,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),u===`shares`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`People with access`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Only the context owner can see and change this list.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>re(),disabled:F,children:[(0,$.jsx)(P,{className:J(`mr-2 h-3.5 w-3.5`,F&&`animate-spin`)}),`Refresh`]})]}),M.length===0?(0,$.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):M.map(e=>(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.userEmail}),(0,$.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[hI.find(t=>t.value===e.accessLevel)?.label||e.accessLevel||`unknown access`,e.sharedAt&&` - since ${new Date(e.sharedAt).toLocaleDateString()}`]})]}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:ne===e.userEmail,onClick:()=>H(e),children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})})]},e.userEmail))]}),(0,$.jsxs)(`form`,{onSubmit:V,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Grant access`}),(0,$.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`share-email`,className:`text-sm font-medium`,children:`User email`}),(0,$.jsx)(Y,{id:`share-email`,type:`email`,value:L,onChange:e=>R(e.target.value),placeholder:`person@example.com`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`The user must already have an account on this server.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`share-level`,className:`text-sm font-medium`,children:`Access level`}),(0,$.jsx)(`select`,{id:`share-level`,value:z,onChange:e=>ee(e.target.value),className:`mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:hI.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),(0,$.jsx)(Z,{type:`submit`,disabled:ne===`grant`||!L.trim(),children:ne===`grant`?`Sharing...`:`Share context`})]})]})]})})}function _I({status:e}){let t={running:{icon:De,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:S,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:N,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:N,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:z,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:Gt,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:Gt,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:S,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,$.jsx)(r,{className:`w-3 h-3`}),n.label]})}function vI(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null);Fp(()=>s(null),o!==null);let[c,l]=tT(),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(!1),{showToast:S}=Vr(),C=bd(),w=(0,Q.useCallback)(async()=>{try{r(!0);let e=await XM.listRoles({type:`workspace`,userId:C?.id});t(e),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch roles`;a(t)}finally{r(!1)}},[C?.id]);(0,Q.useEffect)(()=>{let e=()=>w();e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[w]),(0,Q.useEffect)(()=>{c&&(XM.listTemplates().then(e=>{let t=e.filter(e=>e.type===`workspace`);d(t),h(e=>e||t[0]?.id||``)}).catch(()=>d([])),Ni().then(e=>{p(e),y(t=>t||e[0]?.id||``)}).catch(()=>p([])))},[c]);let T=async e=>{if(e.preventDefault(),!(!m||!g.trim()||!v)){x(!0);try{let e=await XM.createRole({template:m,name:g.trim(),type:`workspace`,userId:C?.id,workspaceId:v});_(``),l(!1),await w(),S({title:`Created`,description:`Role "${e.name}" created`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to create role`,variant:`destructive`})}finally{x(!1)}}},E=async e=>{try{await XM.startRole(e.id),S({title:`Success`,description:`Role "${e.name}" started successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to start role`;S({title:`Error`,description:t,variant:`destructive`})}},D=async e=>{try{await XM.stopRole(e.id),S({title:`Success`,description:`Role "${e.name}" stopped successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to stop role`;S({title:`Error`,description:t,variant:`destructive`})}},O=async e=>{try{await XM.restartRole(e.id),S({title:`Success`,description:`Role "${e.name}" restarted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to restart role`;S({title:`Error`,description:t,variant:`destructive`})}},k=async e=>{try{let t=await XM.getRoleLogs(e.id,100);s({role:e,logs:t})}catch(e){let t=e instanceof Error?e.message:`Failed to fetch logs`;S({title:`Error`,description:t,variant:`destructive`})}};return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`My Roles`,description:`Manage your workspace roles and services`,actions:(0,$.jsxs)($.Fragment,{children:[!c&&(0,$.jsxs)(Z,{onClick:()=>l(!0),children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),`Create Role`]}),(0,$.jsxs)(Z,{onClick:w,variant:`outline`,children:[(0,$.jsx)(j,{className:`mr-2 h-4 w-4`}),`Refresh`]})]})}),c&&(0,$.jsx)($w,{title:`Create New Role`,onClose:()=>l(!1),children:(0,$.jsxs)(`form`,{onSubmit:T,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-template`,className:`mb-1 block text-sm font-medium`,children:`Template`}),(0,$.jsxs)(`select`,{id:`role-template`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:m,onChange:e=>h(e.target.value),disabled:b||u.length===0,children:[u.length===0&&(0,$.jsx)(`option`,{value:``,children:`No workspace templates available`}),u.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-name`,className:`mb-1 block text-sm font-medium`,children:`Role Name`}),(0,$.jsx)(Y,{id:`role-name`,value:g,onChange:e=>_(e.target.value),placeholder:`e.g., canvas-sshd`,disabled:b})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-workspace`,className:`mb-1 block text-sm font-medium`,children:`Workspace`}),(0,$.jsxs)(`select`,{id:`role-workspace`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:v,onChange:e=>y(e.target.value),disabled:b||f.length===0,children:[f.length===0&&(0,$.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),f.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label||e.name},e.id))]})]}),(0,$.jsxs)(Z,{type:`submit`,disabled:b||!m||!g.trim()||!v,children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),b?`Creating…`:`Create Role`]})]})}),n?(0,$.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):i?(0,$.jsx)(`div`,{className:`text-center py-8 text-destructive`,children:i}):e.length===0?(0,$.jsxs)(`div`,{className:`text-center py-12 border rounded-lg`,children:[(0,$.jsx)(Jt,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`You don't have any workspace roles yet`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Contact your administrator to set up roles for your workspaces`})]}):(0,$.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`border rounded-lg p-6 space-y-4 hover:shadow-elevation-2 transition-shadow`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,$.jsxs)(`div`,{className:`flex-1`,children:[(0,$.jsx)(`h3`,{className:`font-semibold text-lg`,children:e.name}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.template})]}),(0,$.jsx)(_I,{status:e.status})]}),e.container&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(Jt,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:e.container.name})]})}),(0,$.jsxs)(`div`,{className:`flex gap-2 pt-2`,children:[e.status===`stopped`||e.status===`created`?(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>E(e),className:`flex-1`,children:[(0,$.jsx)(xe,{className:`w-4 h-4 mr-2`}),`Start`]}):e.status===`running`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>D(e),className:`flex-1`,children:[(0,$.jsx)(zn,{className:`w-4 h-4 mr-2`}),`Stop`]}),(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>O(e),className:`flex-1`,children:[(0,$.jsx)(j,{className:`w-4 h-4 mr-2`}),`Restart`]})]}):(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,disabled:!0,className:`flex-1`,children:[(0,$.jsx)(N,{className:`w-4 h-4 mr-2`}),e.status]}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:()=>k(e),title:`View Logs`,children:(0,$.jsx)(nn,{className:`w-4 h-4`})})]})]},e.id))}),(0,$.jsxs)(`div`,{className:`border-t pt-6`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold mb-4`,children:`Global Services`}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground space-y-2`,children:[(0,$.jsx)(`p`,{children:`Global roles are server-wide services managed by your administrator. These include services like SSH access, storage, and other shared infrastructure.`}),(0,$.jsx)(`p`,{children:`To check the status of global services, contact your system administrator.`})]})]}),o&&(0,$.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,$.jsxs)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-4xl w-full mx-4 max-h-viewport-modal flex flex-col`,children:[(0,$.jsxs)(`div`,{className:`p-6 border-b`,children:[(0,$.jsxs)(`h2`,{className:`text-xl font-bold`,children:[o.role.name,` - Logs`]}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.role.template})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,$.jsx)(`div`,{"data-scheme":`dark`,className:`bg-background text-success p-4 rounded font-mono text-xs overflow-x-auto`,children:o.logs.length===0?(0,$.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,$.jsx)(`pre`,{children:o.logs.join(`
50
+ `)})]})]})}function oI({device:e,linked:t,busy:n,onLink:r,onUnlink:i,onUpdate:a}){let[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(e.name),[u,d]=(0,Q.useState)(e.description??``),f=()=>{c.trim()&&(c!==e.name||u!==(e.description??``))&&a({name:c.trim(),description:u.trim()||void 0}),s(!1)},p=()=>{l(e.name),d(e.description??``),s(!1)};return(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,$.jsx)(Fn,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[o?(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(Y,{value:c,onChange:e=>l(e.target.value),className:`h-7 text-sm`,placeholder:`Device name`,autoFocus:!0,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}}),(0,$.jsx)(Y,{value:u,onChange:e=>d(e.target.value),className:`h-7 text-xs`,placeholder:`Description (optional)`,onKeyDown:e=>{e.key===`Enter`&&f(),e.key===`Escape`&&p()}})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,$.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground font-mono`,children:[(0,$.jsx)(`span`,{children:e.deviceId}),e.platform&&(0,$.jsx)(`span`,{children:e.platform}),e.arch&&(0,$.jsx)(`span`,{children:e.arch}),e.type&&(0,$.jsx)(`span`,{children:e.type})]})]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:f,disabled:!c.trim(),children:(0,$.jsx)(oe,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:p,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]}):(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>s(!0),title:`Edit name/description`,children:(0,$.jsx)(_e,{className:`h-3.5 w-3.5`})}),t?(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:i,className:`text-destructive hover:text-destructive`,title:`Remove from workspace`,children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})}):(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:r,title:`Link to workspace`,children:(0,$.jsx)(Zt,{className:`h-3.5 w-3.5`})}),t&&(0,$.jsx)(`span`,{className:`rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary`,children:`linked`})]})]})})}function sI({allDevices:e,linkedDevices:t,isLoading:n,deviceBusy:r,onRefresh:i,onLink:a,onUnlink:o,onUpdate:s}){let c=new Set(t.map(e=>e.deviceId));return n?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading devices…`]}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[c.size,` of `,e.length,` registered device`,e.length===1?``:`s`,` linked to this workspace.`]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:i,disabled:n,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),e.length===0?(0,$.jsxs)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:[`No devices registered. Devices register themselves on first connection via `,(0,$.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]}):(0,$.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,$.jsx)(oI,{device:e,linked:c.has(e.deviceId),busy:r===e.deviceId,onLink:()=>a(e.deviceId),onUnlink:()=>o(e.deviceId),onUpdate:t=>s(e.deviceId,t)},e.deviceId))})]})}function cI({label:e,value:t,mono:n=!1}){return(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-2 border-b last:border-0`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:e}),(0,$.jsx)(`span`,{className:`text-xs text-right ${n?`font-mono`:``}`,children:t??`—`})]})}function lI({workspaceName:e,current:t,weights:n,floorMode:r,relativeMargin:i,onDone:a}){let[o,s]=(0,Q.useState)(t==null?``:String(t)),[c,l]=(0,Q.useState)(r??`relative`),[u,d]=(0,Q.useState)(i==null?`0.035`:String(i)),[f,p]=(0,Q.useState)(n?.fts==null?`2`:String(n.fts)),[m,h]=(0,Q.useState)(n?.dense==null?`1`:String(n.dense)),[g,_]=(0,Q.useState)(n?.image==null?`2`:String(n.image)),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(ZE);return(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`How photo relevance is decided`}),(0,$.jsxs)(`select`,{value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-input bg-transparent px-2 text-xs`,children:[(0,$.jsx)(`option`,{value:`relative`,children:`Relative to the best match (recommended)`}),(0,$.jsx)(`option`,{value:`absolute`,children:`Absolute distance cutoff`})]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Photo-vs-text distances shift with every query and every model, so one fixed cutoff travels badly: a value tuned for one model keeps everything (or nothing) on the next. Relative anchors on the best match for THIS query and survives a re-embed.`})]}),c===`relative`&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Window width (distance from the best match)`}),(0,$.jsx)(Y,{value:u,onChange:e=>d(e.target.value),placeholder:`0.035`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Wider keeps photos that match your query only partly, which is what a photo matching TWO things (a snowy window) looks like, since it sits further from each one than a pure example does. Too wide and everything gets in.`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:c===`relative`?`Hard ceiling (cosine distance, 0–2; blank = off)`:`Image relevance floor (cosine distance, 0–2; blank = off)`}),(0,$.jsx)(Y,{value:o,onChange:e=>s(e.target.value),placeholder:`0.95`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:c===`relative`?`Nothing beyond this counts as a match however close it is to the best one. This is what lets a search of something you have no photos of come back empty. Without it, a relative window always returns its nearest photo.`:`Lower = stricter (fewer, more-relevant photos); raise if relevant photos are missing.`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Hybrid fusion weights (0 disables a signal)`}),(0,$.jsx)(`div`,{className:`flex flex-wrap items-end gap-x-3 gap-y-2`,children:[[`lexical`,f,p],[`text semantic`,m,h],[`image`,g,_]].map(([e,t,n])=>(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:e}),(0,$.jsx)(Y,{value:t,onChange:e=>n(e.target.value),className:`h-8 w-16 font-mono text-xs`,inputMode:`decimal`})]},e))}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Ranking mix: lexical (filenames/content) · text semantics · photo matches. Equal lexical/image ranks a matching photo like a matching document.`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:async()=>{y(!0),x(null);try{let t=o.trim(),n=t===``?null:Number(t);if(n!==null&&!Number.isFinite(n)){x(`Enter a number (e.g. 0.95) or leave empty`);return}let r={fts:Number(f),dense:Number(m),image:Number(g)};if(Object.values(r).some(e=>!Number.isFinite(e)||e<0)){x(`Weights must be numbers ≥ 0`);return}let i=Number(u.trim());if(c===`relative`&&(!Number.isFinite(i)||i<=0)){x(`Window width must be a positive number (e.g. 0.035)`);return}await Xa(e,{imageMaxDistance:n,imageFloorMode:c,...c===`relative`?{imageRelativeMargin:i}:{},searchWeights:r}),x(`Saved`),a()}catch(e){x(e instanceof Error?e.message:`Failed to save`)}finally{y(!1)}},disabled:v,children:v?`Saving…`:`Save`}),b&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:b})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>{QE(e.target.checked),C(e.target.checked)}}),(0,$.jsx)(`span`,{children:`Debug query`})]}),(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Attaches the raw (unfloored) image distances to each search and shows them above the document list: the numbers this floor should be picked from. Local to this browser; costs a little extra work per query, so leave it off day to day.`})]})]})}function uI({stats:e,isLoading:t,onRefresh:n,workspaceName:r}){return t?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,$.jsx)(P,{className:`h-4 w-4 animate-spin`}),`Loading stats…`]}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Live snapshot from synapsd. Click refresh for updated counts.`}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:n,disabled:t,children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),(0,$.jsx)(mI,{workspaceName:r,vectorSpaces:Object.keys(e?.semantic?.vectorSpaces||{}),onDone:n}),e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(er,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Core Index`})]}),(0,$.jsx)(cI,{label:`Backend`,value:e.dbBackend,mono:!0}),(0,$.jsx)(cI,{label:`Status`,value:e.status}),(0,$.jsx)(cI,{label:`Path`,value:e.dbPath,mono:!0}),(0,$.jsx)(cI,{label:`Documents`,value:e.documentCount?.toLocaleString()}),(0,$.jsx)(cI,{label:`Metadata entries`,value:e.metadataCount?.toLocaleString()}),(0,$.jsx)(cI,{label:`Checksum index`,value:e.checksumIndexSize?.toLocaleString()}),(0,$.jsx)(cI,{label:`Bitmap store`,value:e.bitmapStoreSize?.toLocaleString()}),(0,$.jsx)(cI,{label:`Bitmap cache`,value:e.bitmapCacheSize?.toLocaleString()}),(0,$.jsx)(cI,{label:`Deleted (pending GC)`,value:e.deletedDocumentsCount?.toLocaleString()})]}),e.fts&&(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(Gt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Full-Text Search (LanceDB)`})]}),`ready`in e.fts&&(0,$.jsx)(cI,{label:`Ready`,value:String(e.fts.ready)}),e.fts.rowCount!==void 0&&(0,$.jsx)(cI,{label:`Row count`,value:e.fts.rowCount?.toLocaleString()}),e.fts.error&&(0,$.jsx)(cI,{label:`Error`,value:(0,$.jsx)(`span`,{className:`text-destructive`,children:e.fts.error})})]}),e.semantic&&(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(Gt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Semantic / Vector Search`})]}),(0,$.jsx)(cI,{label:`Enabled`,value:String(e.semantic.enabled)}),e.semantic.enabled&&(0,$.jsxs)($.Fragment,{children:[e.inferd?.routing?Object.entries(e.inferd.routing).map(([e,t])=>(0,$.jsx)(cI,{label:`Embeds → ${e}`,value:(0,$.jsx)(`span`,{className:`font-mono text-[11px]`,children:t.join(`, `)})},`route-${e}`)):(0,$.jsx)(cI,{label:`Text-embeddable (gap default)`,value:e.semantic.embeddableSchemas?.join(`, `)}),e.semantic.vectorSpaces&&Object.entries(e.semantic.vectorSpaces).map(([e,t])=>(0,$.jsx)(cI,{label:`Space: ${e} (${t.dim??`?`}-d)`,value:t.error?(0,$.jsx)(`span`,{className:`text-destructive`,children:t.error}):`${(t.embeddedDocs??0).toLocaleString()} docs · ${(t.chunkRows??0).toLocaleString()} vectors`},e)),(0,$.jsx)(cI,{label:`Photo relevance`,value:e.semantic.imageFloorMode===`absolute`?`absolute cutoff`:`relative ±${e.semantic.imageRelativeMargin??.035}`,mono:!0}),(0,$.jsx)(cI,{label:e.semantic.imageFloorMode===`absolute`?`Image relevance floor`:`Hard ceiling`,value:e.semantic.imageMaxDistance==null?`off`:e.semantic.imageMaxDistance,mono:!0}),(0,$.jsx)(cI,{label:`Fusion weights (lexical · text · image)`,value:`${e.semantic.searchWeights?.fts??2} · ${e.semantic.searchWeights?.dense??1} · ${e.semantic.searchWeights?.image??2}`,mono:!0}),(0,$.jsx)(lI,{workspaceName:r,current:e.semantic.imageMaxDistance,weights:e.semantic.searchWeights,floorMode:e.semantic.imageFloorMode,relativeMargin:e.semantic.imageRelativeMargin,onDone:n})]})]})]}):(0,$.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No stats available.`})]})}function dI(){let{workspaceName:e}=bl();return(0,$.jsx)(fI,{},e)}function fI(){let{workspaceName:e,tab:t}=bl(),[n,r]=zu(),i=n.get(`section`),a=[`pending`,`rules`,`hooks`,`scripts`,`runs`].find(e=>e===i),o=n.get(`handler`)||void 0,s=n.get(`run`)||void 0,c=n.get(`addRuleKind`),l=n.get(`addRulePath`),u=n.get(`addRuleTarget`),d=n.get(`addRuleStoreTo`),p=n.get(`addRuleStoreFolder`),m=(0,Q.useMemo)(()=>c===`store`||c===`download`?!l&&!d&&!p?null:{kind:c,path:l||``,storeTo:d||``,storeFolder:p||``}:l?{kind:`mirror`,path:l,target:u||`dir:/`}:null,[c,l,u,d,p]),h=(0,Q.useCallback)(()=>{r(e=>{for(let t of[`addRuleKind`,`addRulePath`,`addRuleTarget`,`addRuleStoreTo`,`addRuleStoreFolder`])e.delete(t);return e},{replace:!0})},[r]),g=gl(),{showToast:_,showProgress:v}=Vr(),y=l_(),{goBack:b}=PT(),x=BO(t);(0,Q.useEffect)(()=>{t!==x&&g(`/workspaces/${e}/settings/${x}`,{replace:!0})},[t,x,e,g]);let[S,C]=(0,Q.useState)(null),w=Op(S),[T,E]=(0,Q.useState)(0),[D,O]=(0,Q.useState)(!0),[k,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(``),[L,R]=(0,Q.useState)(``),[z,ee]=(0,Q.useState)(`#FFFFFF`),[ne,B]=(0,Q.useState)(null),[re,ie]=(0,Q.useState)(null),[ae,oe]=(0,Q.useState)([]),[V,H]=(0,Q.useState)(null),[U,se]=(0,Q.useState)([]),[W,ce]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(null),[de,fe]=(0,Q.useState)(!1),[pe,me]=(0,Q.useState)([]),[G,he]=(0,Q.useState)([]),[ge,_e]=(0,Q.useState)(!1),[ve,K]=(0,Q.useState)(null),q=e||S?.id||``,ye=(0,Q.useRef)(q);(0,Q.useEffect)(()=>{ye.current=q});let be=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t)try{let e=await za(t);oe(e.publicCanvasShares)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load shares`,variant:`destructive`})}},[_]),xe=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t){fe(!0);try{let e=await xa(t);ue(e)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load DB stats`,variant:`destructive`})}finally{fe(!1)}}},[_]),Se=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(t){_e(!0);try{let[e,n]=await Promise.all([AO(),NO(t)]);me(e),he(n)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load devices`,variant:`destructive`})}finally{_e(!1)}}},[_]),Ce=async e=>{K(e);try{let t=pe.find(t=>t.deviceId===e);if(!t)throw Error(`Device not found in your account`);await PO(q,t),await Se(),_({title:`Linked`,description:`Device linked to workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to link device`,variant:`destructive`})}finally{K(null)}},we=async e=>{K(e);try{await FO(q,e),he(t=>t.filter(t=>t.deviceId!==e)),_({title:`Unlinked`,description:`Device removed from workspace`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to unlink device`,variant:`destructive`})}finally{K(null)}},Te=async(e,t)=>{K(`edit:${e}`);try{let n=await jO(e,t);me(t=>t.map(t=>t.deviceId===e?{...t,...n}:t)),_({title:`Saved`,description:`Device updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update device`,variant:`destructive`})}finally{K(null)}},Ee=(0,Q.useCallback)(async e=>{let t=e??ye.current;if(!t)return;let[n,r]=await Promise.all([Za(t).catch(()=>null),pa(t).catch(()=>[])]);H(n),se(r.filter(e=>e.kind===`storage`))},[]),De=U.some(e=>e.resyncing);(0,Q.useEffect)(()=>{if(!w||!De||!q)return;let e=setInterval(()=>{Ee()},4e3);return()=>clearInterval(e)},[w,De,q,Ee]),(0,Q.useEffect)(()=>{let t=!1;async function n(){try{let n=await Ni();if(t)return;let r=n.find(t=>t.id===e)??n.find(t=>t.name===e);if(C(r??null),r){if(!Op(r))return;I(r.label||``),R(r.description||``),ee(r.color||`#FFFFFF`),B(r.icon??null),r.status===`active`&&await Promise.all([be(e||r.id),Ee(e||r.id)])}}catch{t||_({title:`Error`,description:`Failed to load workspace`,variant:`destructive`})}finally{t||O(!1)}}return n(),()=>{t=!0}},[e,be,Ee,_,T]),(0,Q.useEffect)(()=>{let e=()=>E(e=>e+1);return window.addEventListener(`workspaces:refresh`,e),()=>window.removeEventListener(`workspaces:refresh`,e)},[]);let Oe=(0,Q.useRef)(!1),ke=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{Oe.current=!!le||de,ke.current=ge||pe.length>0}),(0,Q.useEffect)(()=>{w&&(S?.status===`active`&&x===`db`&&q&&!Oe.current&&xe(),S?.status===`active`&&x===`devices`&&q&&!ke.current&&Se())},[w,x,q,S?.status,xe,Se]);let Ae=async e=>{if(e.preventDefault(),S){j(!0);try{await Eo(q,{label:F.trim(),description:L.trim(),color:z,icon:ne}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Saved`,description:`Workspace settings updated`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{j(!1)}}},je=async()=>{if(S&&window.confirm(`Destroy workspace "${S.label||S.name}"? This cannot be undone.`)){N(!0);try{await no(q),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Destroyed`,description:`${S.label||S.name} has been removed`}),g(`/workspaces`)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Destroy failed`,variant:`destructive`})}finally{N(!1)}}},Me=()=>{for(let t of[e,S?.name,S?.id])t&&Da(t,`backends`);window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:q}}))},Ne=async e=>{if(e.config?.supported!==!1){ce(`backend:${e.address}`);try{await _o(q,e.driver,e.address,{enabled:!e.enabled}),await Ee(),Me(),_({title:`Saved`,description:`${e.address} ${e.enabled?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{ce(null)}}},Pe=async(e,t,n)=>{ce(`${n}:${e.address}`);try{await _o(q,e.driver,e.address,t),await Ee()}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{ce(null)}},Fe=async e=>{let t=typeof e.config?.label==`string`&&e.config.label||e.address;if(window.confirm(`Remove backend "${t}"? No files are deleted; indexed entries remain until purged from the backends tree.`)){ce(`remove:${e.address}`);try{await Ki(q,e.driver,e.address),await Ee(),Me(),_({title:`Removed`,description:`${t} unmounted`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to remove backend`,variant:`destructive`})}finally{ce(null)}}},Ie=async e=>{ce(`resync:${e.address}`);try{await Eb(v,q,e.driver,e.address,e=>{se(t=>t.map(t=>t.driver===e.driver&&t.address===e.address?e:t))}),await Ee()}catch{}finally{ce(null)}},Le=async e=>{ce(`test:${e.address}`);try{await $a(q,e.driver,e.address),_({title:`Connected`,description:`${e.address}: credentials and root folder verified`})}catch(e){_({title:`Connection failed`,description:e instanceof Error?e.message:`Test failed`,variant:`destructive`})}finally{ce(null)}},Re=async e=>{ce(`stopsync:${e.address}`);try{await Qa(q,e.driver,e.address),await Ee(),_({title:`Sync stopped`,description:`${e.address}: indexed files are kept; Re-sync resumes where it left off`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to stop sync`,variant:`destructive`})}finally{ce(null)}},ze=async(e,t)=>{ce(`service:${e}`);try{t?await Pa(q,e):await bi(q,e),await Ee(),_({title:t?`Disabled`:`Enabled`,description:`${e} ${t?`disabled`:`enabled`}`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to toggle service`,variant:`destructive`})}finally{ce(null)}},Be=async e=>{let t=`${window.location.origin}${e.url}`;await navigator.clipboard?.writeText(t),_({title:`Copied`,description:t})},Ve=async e=>{if(S&&window.confirm(`Revoke public share for "${e.path}"?`)){ce(`share:${e.code}`);try{await qa(q,e.code),await be(q),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:q}})),_({title:`Revoked`,description:`Public canvas link no longer works`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke share`,variant:`destructive`})}finally{ce(null)}}},He=RO.find(e=>e.id===x);return D?(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`}):S?w?(0,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,$.jsx)(qw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${He.label} - ${S.label||S.name}`,description:`This workspace · ${He.description}`,backTo:`/workspaces/${e}`,onBack:y?b:void 0}),S.status!==`active`&&x!==`general`&&x!==`backups`&&(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to access these settings. General settings and protection remain available while stopped.`}),x===`backups`&&(0,$.jsx)(rP,{workspaceId:q,onRestored:()=>E(e=>e+1)}),x===`general`&&(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`form`,{onSubmit:Ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-id`,className:`text-sm font-medium`,children:`Workspace ID`}),(0,$.jsx)(Y,{id:`ws-id`,value:S.id,readOnly:!0,className:`font-mono text-sm`,onFocus:e=>e.currentTarget.select()})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-label`,className:`text-sm font-medium`,children:`Label`}),(0,$.jsx)(Y,{id:`ws-label`,value:F,onChange:e=>I(e.target.value),placeholder:`Workspace Label`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ws-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`ws-description`,value:L,onChange:e=>R(e.target.value),placeholder:`Description (optional)`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Icon & color`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>ie({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,$.jsx)(f,{icon:ne||`ph:stack-fill`,width:22,height:22,color:Nm(z)})}),(0,$.jsx)(Y,{id:`ws-color`,type:`color`,value:z,onChange:e=>ee(e.target.value),className:`h-10 w-16 p-1`}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ee(Am()),children:`Randomize`})]})]}),(0,$.jsx)(Z,{type:`submit`,disabled:k||!F.trim(),children:k?`Saving...`:`Save Changes`})]}),re&&(0,$.jsx)(Zw,{x:re.x,y:re.y,current:{icon:ne??void 0,color:z},onChange:e=>{`icon`in e&&B(e.icon??null),`color`in e&&e.color&&ee(e.color)},onClose:()=>ie(null)}),(0,$.jsx)(hP,{currentMode:S.protection?.mode,workspaceId:q,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),S.status===`active`&&(0,$.jsx)(pI,{workspaceName:e}),S.status===`active`&&(0,$.jsx)(iI,{workspaceId:q}),(0,$.jsx)(XF,{workspaceId:q,workspaceName:S.label||S.name,isActive:S.status===`active`,onChanged:()=>E(e=>e+1)}),(0,$.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,$.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,$.jsxs)(Z,{variant:`destructive`,disabled:M,onClick:je,children:[(0,$.jsx)(nt,{className:`mr-2 h-4 w-4`}),M?`Destroying...`:`Destroy Workspace`]})]})]}),S.status===`active`&&x===`shares`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Members`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Share this workspace with teammates by e-mail or with a whole directory group. It shows up in their workspace list on this server.`})]}),(0,$.jsx)(YF,{workspaceId:q})]}),(0,$.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Public Canvas Shares`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Active public canvas links for this workspace.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>be(),children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),ae.length===0?(0,$.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No public canvas shares. Good.`}):ae.map(e=>{let t=`${window.location.origin}${e.url}`;return(0,$.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate font-mono text-sm`,children:e.path}),(0,$.jsxs)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:[e.treeName,` / `,e.treeType,` - created `,new Date(e.createdAt).toLocaleString()]}),e.lockedBy?.length>0&&(0,$.jsxs)(`div`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`locks: `,e.lockedBy.join(`, `)]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>Be(e),children:(0,$.jsx)(A,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>window.open(t,`_blank`,`noreferrer`),children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`share:${e.code}`,onClick:()=>Ve(e),className:`text-destructive hover:text-destructive`,children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})})]})]}),(0,$.jsx)(`div`,{className:`mt-2 truncate rounded bg-muted/40 px-2 py-1 font-mono text-xs text-muted-foreground`,children:t})]},e.code)})]}),(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-3`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workspace ACL Tokens`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Generate token-based workspace access for devices, scripts, and other users.`})]}),(0,$.jsx)(GF,{workspaceId:q})]})]}),S.status===`active`&&x===`data`&&(0,$.jsxs)(`div`,{className:`space-y-3`,children:[U.map(e=>{let t=e.config||{},n=e.address,r=t.device||null,i=e.driver===`gdrive`,a=e.driver===`s3`,o=(e.driver===`file`||i||a)&&t.managed!==!0&&!ZF[n],s=ZF[n]||{title:typeof t.label==`string`&&t.label||n,description:a?`S3 bucket ${t.bucket||``}${t.prefix?`/${t.prefix}`:``}${t.endpoint?` at ${t.endpoint}`:``}. Filing copies only.`:i?`Google Drive${typeof t.account==`string`&&t.account&&t.account!==t.label?` (${t.account})`:``}, folder ${typeof t.folderId==`string`&&t.folderId?t.folderId:`root`}${e.treePath?`, mirrored at ${e.treePath}`:``}.`:o?`Local folder${r?.name?` on ${r.name}`:``}, indexed in place${e.treePath?` and mirrored at ${e.treePath}`:``}.`:`Workspace data backend.`},c=t.supported!==!1,l=n===`workspace:data`,u=c&&!l,d=u&&t.managed!==!0,p=Cm(e);return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(f,{icon:p.icon,width:16,height:16,color:p.color,className:`shrink-0`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:s.title}),!c&&(0,$.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,children:`unsupported`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s.description}),typeof t.root==`string`&&t.root&&(0,$.jsx)(`p`,{className:`mt-2 truncate font-mono text-xs text-muted-foreground`,children:t.root}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,$.jsxs)(`span`,{children:[`status: `,e.status]}),e.resyncing&&(0,$.jsxs)(`span`,{className:`flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 font-medium text-primary`,children:[(0,$.jsx)(P,{className:`h-3 w-3 animate-spin`}),`indexing`,e.progress?` ${e.progress.scanned}${e.progress.total==null?``:` / ${e.progress.total}`}`:``]}),r?.name&&(0,$.jsxs)(`span`,{title:r.id,children:[`device: `,r.name]}),t.readOnly===!0&&(0,$.jsx)(`span`,{className:`rounded bg-warning/15 px-1.5 py-0.5 font-medium text-warning`,children:`read-only`}),e.lastSyncAt&&(0,$.jsxs)(`span`,{children:[`last scan: `,new Date(e.lastSyncAt).toLocaleString()]})]}),e.lastError&&(0,$.jsx)(`p`,{className:`mt-2 text-xs text-destructive`,children:e.lastError}),t.readOnly===!0&&(0,$.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`Read-only: the web UI / REST API never deletes bytes on this backend. Destroy degrades to a reference drop. Recommended when the folder is exported elsewhere (e.g. via Samba).`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-3`,children:[e.capabilities?.sync&&c&&(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,title:`Scan this backend in the background whenever the workspace starts. Manual scans remain available when off.`,children:[`Scan on start`,(0,$.jsx)($F,{checked:t.scanOnStart===!0,disabled:W===`startup:${n}`,onClick:()=>Pe(e,{scanOnStart:t.scanOnStart!==!0},`startup`)})]}),(e.driver===`file`||i||a)&&u&&(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:i?`Poll the Drive changes feed so edits made in Drive show up without a manual re-sync.`:void 0,children:[`Watch for changes`,(0,$.jsx)($F,{checked:!!t.watch,disabled:!e.enabled||W===`watch:${n}`,onClick:()=>Pe(e,{watch:!t.watch},`watch`)})]}),d&&(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[11px] text-muted-foreground`,title:`Read-only: Destroy never deletes bytes on this backend (references are dropped instead). Important when the folder is exported via Samba or shared otherwise.`,children:[`read-only`,(0,$.jsx)($F,{checked:t.readOnly===!0,disabled:W===`readonly:${n}`,onClick:()=>Pe(e,{readOnly:t.readOnly!==!0},`readonly`)})]}),(e.driver===`file`||e.driver===`cacache`)&&c&&(0,$.jsx)(nI,{workspaceId:q,backend:e}),e.capabilities?.test&&(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`test:${n}`,onClick:()=>Le(e),title:`Verify credentials and root folder`,children:[(0,$.jsx)(Gt,{className:`mr-2 h-3.5 w-3.5`}),W===`test:${n}`?`Testing…`:`Test`]}),e.capabilities?.sync&&(e.resyncing?(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`stopsync:${n}`,onClick:()=>Re(e),title:`Stop the running scan. Files indexed so far are kept; Re-sync later resumes where it left off (unchanged files are skipped).`,children:[(0,$.jsx)(zn,{className:`mr-2 h-3.5 w-3.5 fill-current`}),W===`stopsync:${n}`?`Stopping…`:`Stop sync`]}):(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:W===`resync:${n}`,onClick:()=>Ie(e),children:[(0,$.jsx)(P,{className:`mr-2 h-3.5 w-3.5 ${W===`resync:${n}`?`animate-spin`:``}`}),`Re-sync`]})),l?(0,$.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,title:`Structural workspace store; cannot be disabled`,children:`always on`}):(0,$.jsx)($F,{checked:!!e.enabled,disabled:!u||W===`backend:${n}`,onClick:()=>Ne(e)}),o&&(0,$.jsx)(Z,{type:`button`,variant:`ghost`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:W===`remove:${n}`,title:`Unmount this folder (no files are deleted)`,onClick:()=>Fe(e),children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})]}),c&&(0,$.jsx)(lE,{value:t.removalPolicy,backends:U,source:n,destination:t.propagatedRemovalSupported===!0,onSave:async t=>{await _o(q,e.driver,e.address,{removalPolicy:t}),await Ee()}}),a&&(0,$.jsx)(mP,{workspaceId:q,backend:e,onSaved:async()=>{await Ee(),Me()}}),e.driver===`file`&&c&&!l&&(0,$.jsx)(aI,{backend:e,busy:W===`exclude:${n}`,onSave:t=>Pe(e,{exclude:t},`exclude`)})]},n)}),(0,$.jsx)(pP,{workspaceId:q,children:(0,$.jsx)(rI,{workspaceId:q})},q),(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start`,children:[(0,$.jsx)(eI,{workspaceId:q,onAdded:async()=>{await Ee(),Me()}}),(0,$.jsx)(tI,{workspaceId:q,onAdded:async()=>{await Ee(),Me()}}),(0,$.jsx)(mP,{workspaceId:q,onSaved:async()=>{await Ee(),Me()}})]}),e&&(0,$.jsx)(`section`,{className:`border-t pt-4`,children:(0,$.jsx)(dE,{workspaceName:e})})]}),S.status===`active`&&x===`db`&&(0,$.jsxs)(`div`,{className:`space-y-8`,children:[q&&(0,$.jsxs)(`section`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Embeddings`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Which model turns this workspace's content into vectors, and where those vectors live.`})]}),(0,$.jsx)(EP,{workspaceId:q,workspaceName:e})]}),(0,$.jsx)(uI,{stats:le,isLoading:de,onRefresh:()=>xe(),workspaceName:e})]}),S.status===`active`&&x===`devices`&&(0,$.jsx)(sI,{allDevices:pe,linkedDevices:G,isLoading:ge,deviceBusy:ve,onRefresh:()=>Se(),onLink:Ce,onUnlink:we,onUpdate:Te}),S.status===`active`&&x===`sync`&&(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(NF,{workspaceId:q,workspaceUuid:S?.id})}),S.status===`active`&&x===`services`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[q&&(0,$.jsx)(BF,{workspaceId:q}),(0,$.jsx)(`div`,{className:`space-y-3`,children:QF.map(e=>{let t=V?.[e.id]||V?.[e.id===`git`?`dotfiles`:e.id===`webdav`?`home`:`imap`],n=!!t?.enabled;return(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Jt,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:e.title})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:e.description}),(0,$.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[`initialized: `,t?.initialized?`true`:`false`]})]}),(0,$.jsx)($F,{checked:n,disabled:W===`service:${e.id}`,onClick:()=>ze(e.id,n)})]})},e.id)})}),(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(WF,{workspaceId:q,enabled:!!(V?.imap?.enabled||V?.imapSync?.enabled)})})]}),S.status===`active`&&x===`policies`&&(0,$.jsx)(yF,{workspaceId:q}),S.status===`active`&&x===`hooks`&&(0,$.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,$.jsx)(BP,{workspaceId:q,prefillRule:m,onPrefillConsumed:h,initialSection:a,initialRunsHandler:o,initialRunId:s})})]})}):(0,$.jsxs)(`div`,{className:`space-y-3 p-6`,children:[(0,$.jsx)(`h1`,{className:`font-semibold`,children:S.label||S.name}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Workspace settings are available to owners and admins.`}),(0,$.jsx)(Z,{variant:`outline`,onClick:()=>g(`/workspaces/${e}`),children:`Back to workspace`})]}):(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Workspace not found`})}function pI({workspaceName:e}){let{selected:t,setSelected:n,tree:r,setTree:i,toggle:a}=BT(),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(null);return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Default folders`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Create a set of common folders with matching icons and colors.`}),(0,$.jsx)(`div`,{className:`mt-3`,children:(0,$.jsx)(VT,{selected:t,onToggle:a,tree:r,onTreeChange:i,disabled:o,idPrefix:`settings-default-folders`})}),(0,$.jsxs)(`div`,{className:`mt-3 flex items-center gap-3`,children:[(0,$.jsx)(Z,{type:`button`,size:`sm`,disabled:o||t.size===0,onClick:async()=>{s(!0),l(null);let{ok:i,failed:a}=await zT(e,Array.from(t),r);s(!1),l(a?`${i} created, ${a} failed`:`${i} folder(s) created`),n(new Set)},children:o?`Creating…`:`Create ${t.size||``} folder(s)`}),c&&(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:c})]})]})}function mI({workspaceName:e,vectorSpaces:t,onDone:n}){let[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),s=async(e,t,r)=>{if(!(r&&!window.confirm(r))){i(e),o(null);try{let e=await t();o(e.message),n()}catch(e){o(e instanceof Error?e.message:`Reindex failed`)}finally{i(null)}}},c=[{title:`Bitmaps`,ops:[{key:`timelines`,label:`Reindex timelines`,description:`Rebuild the created/updated timelines from document data.`,fn:()=>LM(e)},{key:`mime`,label:`Reindex MIME types`,description:`Rebuild the per-MIME-type presence bitmaps (data/mime/*) from stored docs. Backfills blobs indexed before mime bitmaps existed.`,fn:()=>BM(e)}]},{title:`Full-text (BM25)`,ops:[{key:`fts`,label:`Backfill`,description:`Index documents missing from the full-text table. Fast, skips already-indexed.`,fn:()=>RM(e)},{key:`fts-rebuild`,label:`Rebuild`,description:`Wipe the full-text table and rebuild from scratch. Use when counts drift.`,confirm:`Wipe the FTS index and rebuild it from scratch?`,fn:()=>RM(e,!0)},{key:`fts-optimize`,label:`Optimize`,description:`Compact fragments + prune old versions of the full-text table.`,fn:()=>zM(e,`fts`)}]},...t.length>0?[{title:`Vector tables (LanceDB)`,ops:t.map(t=>({key:`${t}-optimize`,label:`Optimize ${t}`,description:`Compact fragments + prune old versions of the '${t}' vector table and rebuild its ANN index.`,fn:()=>zM(e,t)}))}]:[]];return(0,$.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,$.jsx)(P,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Index maintenance`})]}),(0,$.jsx)(`p`,{className:`mb-3 text-xs text-muted-foreground`,children:`Runs against this workspace. Reindex operations are idempotent.`}),(0,$.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e.title}),(0,$.jsx)(`div`,{className:`space-y-2`,children:e.ops.map(e=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,className:`w-44 justify-start`,disabled:r!==null,onClick:()=>s(e.key,e.fn,e.confirm),children:[r===e.key&&(0,$.jsx)(P,{className:`mr-2 h-3 w-3 animate-spin`}),e.label]}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 basis-52 text-xs text-muted-foreground`,children:e.description})]},e.key))})]},e.title))}),a&&(0,$.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:a})]})}var hI=[{value:`documentRead`,label:`Read`},{value:`documentWrite`,label:`Write`},{value:`documentReadWrite`,label:`Read & write`}];function gI(){let{contextId:e,tab:t}=bl(),[n]=zu(),r=n.get(`ownerId`)||void 0,i=gl(),{showToast:a}=Vr(),{selectEntity:o,goBack:s,closeM2:c}=PT(),l=l_(),u=HO(t),d=r?`?ownerId=${encodeURIComponent(r)}`:``;(0,Q.useEffect)(()=>{t!==u&&e&&i(`/contexts/${e}/settings/${u}${d}`,{replace:!0})},[t,u,e,d,i]);let[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(!0),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(``),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(),[M,N]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(``),[z,ee]=(0,Q.useState)(hI[0].value),[ne,B]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return Cs(e,r).then(e=>{t||(p(e),o(e.id),x(e.name||``),C(e.description||``),T(typeof e.metadata?.ui?.color==`string`?e.metadata.ui.color:null),D(e.url||``),k(e.baseUrl||``))}).catch(()=>{t||a({title:`Error`,description:`Failed to load context`,variant:`destructive`})}).finally(()=>{t||h(!1)}),()=>{t=!0}},[e,r,o,a]);let re=(t=e)=>{t&&(I(!0),Ls(t).then(N).catch(()=>N([])).finally(()=>I(!1)))};(0,Q.useEffect)(()=>{if(u!==`shares`||!e)return;let t=!1;return Ls(e).then(e=>{t||N(e)}).catch(()=>{t||N([])}),()=>{t=!0}},[u,e]);let ie=async t=>{if(t.preventDefault(),e){_(!0);try{let t=await ns(e,{name:b.trim(),description:S.trim(),metadata:{...f?.metadata,ui:{...f?.metadata?.ui,color:w}}},r);p(t),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},ae=async t=>{if(t.preventDefault(),e){_(!0);try{await Promise.all([is(e,E.trim(),r,A),ls(e,{baseUrl:O.trim()||null},r)]),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),a({title:`Saved`,description:`Context URL updated`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{_(!1)}}},oe=async()=>{if(e&&window.confirm(`Delete context "${e}"? This cannot be undone.`)){y(!0);try{await As(e,r),c(),o(null),a({title:`Deleted`,description:`Context "${e}" removed`}),i(`/contexts`,{replace:!0})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Delete failed`,variant:`destructive`})}finally{y(!1)}}},V=async t=>{if(t.preventDefault(),!(!e||!L.trim())){B(`grant`);try{await Fs(e,L.trim(),z),R(``),re(),a({title:`Shared`,description:`Access granted to ${L.trim()}`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{B(null)}}},H=async t=>{if(e&&window.confirm(`Revoke ${t.userEmail}'s access to "${e}"?`)){B(t.userEmail);try{await $o(e,t.userEmail),re(),a({title:`Revoked`,description:`${t.userEmail} no longer has access`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to revoke access`,variant:`destructive`})}finally{B(null)}}};if(m)return(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!f)return(0,$.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Context not found`});let U=VO.find(e=>e.id===u),se=`/contexts/${e}${d}`;return(0,$.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,$.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,$.jsx)(qw,{compact:!0,className:`mb-6 border-b pb-4`,title:`${U.label} - ${f.name||f.id}`,description:U.description,backTo:se,onBack:l?s:void 0}),u===`general`&&(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`form`,{onSubmit:ie,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Context ID`}),(0,$.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:f.id})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-name`,className:`text-sm font-medium`,children:`Name`}),(0,$.jsx)(Y,{id:`ctx-name`,value:b,onChange:e=>x(e.target.value),placeholder:`My Context`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-description`,className:`text-sm font-medium`,children:`Description`}),(0,$.jsx)(Y,{id:`ctx-description`,value:S,onChange:e=>C(e.target.value),placeholder:`Optional description`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-color`,className:`text-sm font-medium`,children:`Color`}),(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-2`,children:[(0,$.jsx)(Y,{id:`ctx-color`,type:`color`,value:/^#[0-9a-f]{6}$/i.test(w||f.color||``)?w||f.color:`#808080`,onChange:e=>T(e.target.value),className:`h-10 w-16 p-1`,disabled:g}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,disabled:g||w===null,onClick:()=>T(null),children:`Use inherited color`})]}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:w===null?`Using the tree folder or workspace color.`:`Applies only to this context.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-sm font-medium`,children:`Workspace`}),(0,$.jsx)(`div`,{className:`mt-1 flex h-10 items-center rounded-md bg-muted px-3 text-sm text-muted-foreground`,children:f.workspaceName||f.workspaceId||f.workspace})]}),(0,$.jsx)(Z,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),(0,$.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,$.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,$.jsxs)(Z,{variant:`destructive`,disabled:v,onClick:oe,children:[(0,$.jsx)(nt,{className:`mr-2 h-4 w-4`}),v?`Deleting...`:`Delete Context`]})]})]}),u===`location`&&(0,$.jsxs)(`form`,{onSubmit:ae,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`ctx-url`,className:`text-sm font-medium`,children:`URL`}),(0,$.jsx)(ah,{id:`ctx-url`,value:E,onChange:D,fixedWorkspaceName:f.workspaceName,pickerTitle:`Switch context to…`,placeholder:`workspace://path`,onPickTarget:(e,t)=>{D(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),j(t.treeName)}}),A&&(0,$.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Destination tree: `,A]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`label`,{htmlFor:`ctx-base-url`,className:`text-sm font-medium`,children:[`Base URL `,(0,$.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,$.jsx)(ah,{id:`ctx-base-url`,value:O,onChange:k,fixedWorkspaceName:f.workspaceName,placeholder:`workspace://base/path`,pickerTitle:`Pick a base path…`})]}),(0,$.jsx)(Z,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),u===`shares`&&(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`People with access`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Only the context owner can see and change this list.`})]}),(0,$.jsxs)(Z,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>re(),disabled:F,children:[(0,$.jsx)(P,{className:J(`mr-2 h-3.5 w-3.5`,F&&`animate-spin`)}),`Refresh`]})]}),M.length===0?(0,$.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):M.map(e=>(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.userEmail}),(0,$.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[hI.find(t=>t.value===e.accessLevel)?.label||e.accessLevel||`unknown access`,e.sharedAt&&` - since ${new Date(e.sharedAt).toLocaleDateString()}`]})]}),(0,$.jsx)(Z,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:ne===e.userEmail,onClick:()=>H(e),children:(0,$.jsx)(te,{className:`h-3.5 w-3.5`})})]},e.userEmail))]}),(0,$.jsxs)(`form`,{onSubmit:V,className:`space-y-4 rounded-lg border p-4`,children:[(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Grant access`}),(0,$.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`share-email`,className:`text-sm font-medium`,children:`User email`}),(0,$.jsx)(Y,{id:`share-email`,type:`email`,value:L,onChange:e=>R(e.target.value),placeholder:`person@example.com`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`The user must already have an account on this server.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`share-level`,className:`text-sm font-medium`,children:`Access level`}),(0,$.jsx)(`select`,{id:`share-level`,value:z,onChange:e=>ee(e.target.value),className:`mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`,children:hI.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),(0,$.jsx)(Z,{type:`submit`,disabled:ne===`grant`||!L.trim(),children:ne===`grant`?`Sharing...`:`Share context`})]})]})]})})}function _I({status:e}){let t={running:{icon:De,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:S,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:N,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:N,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:z,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:Gt,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:Gt,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:S,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,$.jsx)(r,{className:`w-3 h-3`}),n.label]})}function vI(){let[e,t]=(0,Q.useState)([]),[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null);Fp(()=>s(null),o!==null);let[c,l]=tT(),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(!1),{showToast:S}=Vr(),C=bd(),w=(0,Q.useCallback)(async()=>{try{r(!0);let e=await XM.listRoles({type:`workspace`,userId:C?.id});t(e),a(null)}catch(e){let t=e instanceof Error?e.message:`Failed to fetch roles`;a(t)}finally{r(!1)}},[C?.id]);(0,Q.useEffect)(()=>{let e=()=>w();e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[w]),(0,Q.useEffect)(()=>{c&&(XM.listTemplates().then(e=>{let t=e.filter(e=>e.type===`workspace`);d(t),h(e=>e||t[0]?.id||``)}).catch(()=>d([])),Ni().then(e=>{p(e),y(t=>t||e[0]?.id||``)}).catch(()=>p([])))},[c]);let T=async e=>{if(e.preventDefault(),!(!m||!g.trim()||!v)){x(!0);try{let e=await XM.createRole({template:m,name:g.trim(),type:`workspace`,userId:C?.id,workspaceId:v});_(``),l(!1),await w(),S({title:`Created`,description:`Role "${e.name}" created`})}catch(e){S({title:`Error`,description:e instanceof Error?e.message:`Failed to create role`,variant:`destructive`})}finally{x(!1)}}},E=async e=>{try{await XM.startRole(e.id),S({title:`Success`,description:`Role "${e.name}" started successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to start role`;S({title:`Error`,description:t,variant:`destructive`})}},D=async e=>{try{await XM.stopRole(e.id),S({title:`Success`,description:`Role "${e.name}" stopped successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to stop role`;S({title:`Error`,description:t,variant:`destructive`})}},O=async e=>{try{await XM.restartRole(e.id),S({title:`Success`,description:`Role "${e.name}" restarted successfully`}),w()}catch(e){let t=e instanceof Error?e.message:`Failed to restart role`;S({title:`Error`,description:t,variant:`destructive`})}},k=async e=>{try{let t=await XM.getRoleLogs(e.id,100);s({role:e,logs:t})}catch(e){let t=e instanceof Error?e.message:`Failed to fetch logs`;S({title:`Error`,description:t,variant:`destructive`})}};return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`My Roles`,description:`Manage your workspace roles and services`,actions:(0,$.jsxs)($.Fragment,{children:[!c&&(0,$.jsxs)(Z,{onClick:()=>l(!0),children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),`Create Role`]}),(0,$.jsxs)(Z,{onClick:w,variant:`outline`,children:[(0,$.jsx)(j,{className:`mr-2 h-4 w-4`}),`Refresh`]})]})}),c&&(0,$.jsx)($w,{title:`Create New Role`,onClose:()=>l(!1),children:(0,$.jsxs)(`form`,{onSubmit:T,className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-template`,className:`mb-1 block text-sm font-medium`,children:`Template`}),(0,$.jsxs)(`select`,{id:`role-template`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:m,onChange:e=>h(e.target.value),disabled:b||u.length===0,children:[u.length===0&&(0,$.jsx)(`option`,{value:``,children:`No workspace templates available`}),u.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-name`,className:`mb-1 block text-sm font-medium`,children:`Role Name`}),(0,$.jsx)(Y,{id:`role-name`,value:g,onChange:e=>_(e.target.value),placeholder:`e.g., canvas-sshd`,disabled:b})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`role-workspace`,className:`mb-1 block text-sm font-medium`,children:`Workspace`}),(0,$.jsxs)(`select`,{id:`role-workspace`,className:`w-full rounded-md border border-border bg-background px-3 py-2`,value:v,onChange:e=>y(e.target.value),disabled:b||f.length===0,children:[f.length===0&&(0,$.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),f.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label||e.name},e.id))]})]}),(0,$.jsxs)(Z,{type:`submit`,disabled:b||!m||!g.trim()||!v,children:[(0,$.jsx)(sn,{className:`mr-2 h-4 w-4`}),b?`Creating…`:`Create Role`]})]})}),n?(0,$.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):i?(0,$.jsx)(`div`,{className:`text-center py-8 text-destructive`,children:i}):e.length===0?(0,$.jsxs)(`div`,{className:`text-center py-12 border rounded-lg`,children:[(0,$.jsx)(Jt,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,$.jsx)(`p`,{className:`text-muted-foreground`,children:`You don't have any workspace roles yet`}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Contact your administrator to set up roles for your workspaces`})]}):(0,$.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`border rounded-lg p-6 space-y-4 hover:shadow-elevation-2 transition-shadow`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,$.jsxs)(`div`,{className:`flex-1`,children:[(0,$.jsx)(`h3`,{className:`font-semibold text-lg`,children:e.name}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.template})]}),(0,$.jsx)(_I,{status:e.status})]}),e.container&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(Jt,{className:`w-3 h-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:e.container.name})]})}),(0,$.jsxs)(`div`,{className:`flex gap-2 pt-2`,children:[e.status===`stopped`||e.status===`created`?(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>E(e),className:`flex-1`,children:[(0,$.jsx)(xe,{className:`w-4 h-4 mr-2`}),`Start`]}):e.status===`running`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>D(e),className:`flex-1`,children:[(0,$.jsx)(zn,{className:`w-4 h-4 mr-2`}),`Stop`]}),(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,onClick:()=>O(e),className:`flex-1`,children:[(0,$.jsx)(j,{className:`w-4 h-4 mr-2`}),`Restart`]})]}):(0,$.jsxs)(Z,{size:`sm`,variant:`outline`,disabled:!0,className:`flex-1`,children:[(0,$.jsx)(N,{className:`w-4 h-4 mr-2`}),e.status]}),(0,$.jsx)(Z,{size:`sm`,variant:`outline`,onClick:()=>k(e),title:`View Logs`,children:(0,$.jsx)(nn,{className:`w-4 h-4`})})]})]},e.id))}),(0,$.jsxs)(`div`,{className:`border-t pt-6`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold mb-4`,children:`Global Services`}),(0,$.jsxs)(`div`,{className:`text-sm text-muted-foreground space-y-2`,children:[(0,$.jsx)(`p`,{children:`Global roles are server-wide services managed by your administrator. These include services like SSH access, storage, and other shared infrastructure.`}),(0,$.jsx)(`p`,{children:`To check the status of global services, contact your system administrator.`})]})]}),o&&(0,$.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,$.jsxs)(`div`,{className:`bg-background rounded-lg shadow-elevation-3 max-w-4xl w-full mx-4 max-h-viewport-modal flex flex-col`,children:[(0,$.jsxs)(`div`,{className:`p-6 border-b`,children:[(0,$.jsxs)(`h2`,{className:`text-xl font-bold`,children:[o.role.name,` - Logs`]}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.role.template})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,$.jsx)(`div`,{"data-scheme":`dark`,className:`bg-background text-success p-4 rounded font-mono text-xs overflow-x-auto`,children:o.logs.length===0?(0,$.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,$.jsx)(`pre`,{children:o.logs.join(`
51
51
  `)})})}),(0,$.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,$.jsx)(Z,{onClick:()=>s(null),children:`Close`})})]})})]})}function yI(){return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsx)(qw,{title:`Remotes`,description:`Connect to remote Canvas instances`}),(0,$.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,$.jsxs)(`div`,{className:`text-center`,children:[(0,$.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,$.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Remote connection management is currently under development. Check back later for updates.`})]})})]})}var bI=[`note`,`todo`,`link`,`file`,`photo`];function xI(){let{kind:e}=bl(),t=gl();return e===`sketch`?(0,$.jsx)(Hl,{to:`/apps/sketch?add=1`,replace:!0}):!e||!bI.includes(e)?(0,$.jsx)(Hl,{to:`/home`,replace:!0}):(0,$.jsx)(aO,{initialKind:e,onInitialCardClose:()=>t(`/home`)})}var SI=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Wl,{index:!0,element:(0,$.jsx)(hO,{})},`r1`),(0,$.jsx)(Wl,{path:`home`,element:(0,$.jsx)(mO,{})},`r2`),(0,$.jsx)(Wl,{path:`share-target`,element:(0,$.jsx)(SO,{})},`r3`),(0,$.jsx)(Wl,{path:`apps/add/:kind`,element:(0,$.jsx)(xI,{})},`r4`),(0,$.jsx)(Wl,{path:`workspaces`,element:(0,$.jsx)(QT,{})},`r5`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName`,element:(0,$.jsx)(cD,{})},`r6`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/documents/by-id/:documentId`,element:(0,$.jsx)(pD,{})},`workspace-document-by-id`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/documents/:documentId`,element:(0,$.jsx)(pD,{})},`workspace-document`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/documents/by-hash/:algo/:checksum`,element:(0,$.jsx)(pD,{})},`workspace-document-by-hash`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/documents/by-checksum/:algo/:checksum`,element:(0,$.jsx)(pD,{})},`workspace-document-by-checksum`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/settings`,element:(0,$.jsx)(dI,{})},`r7`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/settings/:tab`,element:(0,$.jsx)(dI,{})},`r8`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/path/*`,element:(0,$.jsx)(cD,{})},`r9`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/trees/:treeName`,element:(0,$.jsx)(cD,{})},`r10`),(0,$.jsx)(Wl,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:(0,$.jsx)(cD,{})},`r11`),(0,$.jsx)(Wl,{path:`contexts`,element:(0,$.jsx)(TO,{})},`r12`),(0,$.jsx)(Wl,{path:`contexts/:contextId`,element:(0,$.jsx)(DO,{})},`r13`),(0,$.jsx)(Wl,{path:`contexts/:contextId/settings`,element:(0,$.jsx)(gI,{})},`r14`),(0,$.jsx)(Wl,{path:`contexts/:contextId/settings/:tab`,element:(0,$.jsx)(gI,{})},`r15`),(0,$.jsx)(Wl,{path:`agents`,element:(0,$.jsx)(wN,{})},`r16`),(0,$.jsx)(Wl,{path:`agents/:agentId`,element:(0,$.jsx)(BN,{})},`r17`),(0,$.jsx)(Wl,{path:`agents/:agentId/:sessionId`,element:(0,$.jsx)(BN,{})},`r18`),(0,$.jsx)(Wl,{path:`agents/:agentId/settings`,element:(0,$.jsx)(JN,{})},`r19`),(0,$.jsx)(Wl,{path:`agents/:agentId/settings/:tab`,element:(0,$.jsx)(JN,{})},`r20`),(0,$.jsx)(Wl,{path:`roles`,element:(0,$.jsx)(vI,{})},`r21`),(0,$.jsx)(Wl,{path:`remotes`,element:(0,$.jsx)(yI,{})},`r22`),(0,$.jsx)(Wl,{path:`settings`,element:(0,$.jsx)(jk,{})},`settings`),(0,$.jsx)(Wl,{path:`appearance`,element:(0,$.jsx)(ZA,{})},`r23`),(0,$.jsx)(Wl,{path:`key-bindings`,element:(0,$.jsx)(oj,{})},`key-bindings`),(0,$.jsx)(Wl,{path:`offline`,element:(0,$.jsx)(Gj,{})},`r24`),(0,$.jsx)(Wl,{path:`about`,element:(0,$.jsx)(Jj,{})},`r25`),(0,$.jsx)(Wl,{path:`api-tokens`,element:(0,$.jsx)(kO,{})},`r26`),(0,$.jsx)(Wl,{path:`devices`,element:(0,$.jsx)(LO,{})},`r27`),(0,$.jsx)(Wl,{path:`embedding`,element:(0,$.jsx)(kM,{})},`r28`),(0,$.jsx)(Wl,{path:`shared`,element:(0,$.jsx)(AM,{})},`r29`),(0,$.jsx)(Wl,{path:`admin/users`,element:(0,$.jsx)(eN,{})},`r30`),(0,$.jsx)(Wl,{path:`admin/contexts`,element:(0,$.jsx)(WM,{})},`r31`),(0,$.jsx)(Wl,{path:`admin/workspaces`,element:(0,$.jsx)(UM,{})},`r32`),(0,$.jsx)(Wl,{path:`admin/agents`,element:(0,$.jsx)(GM,{})},`r33`),(0,$.jsx)(Wl,{path:`admin/logs`,element:(0,$.jsx)(YM,{})},`r34`),(0,$.jsx)(Wl,{path:`admin/roles`,element:(0,$.jsx)($M,{})},`r35`),(0,$.jsx)(Wl,{path:`admin/embedding`,element:(0,$.jsx)(tN,{})},`r36`),(0,$.jsx)(Wl,{path:`admin/auth`,element:(0,$.jsx)(SN,{})},`r37`)]});function CI(e){if(typeof e!=`string`||!e.startsWith(`/`)||e.startsWith(`//`)||/[\\\u0000-\u0020]/.test(e))return null;let t=new URL(e,`https://canvas.invalid`);return t.origin!==`https://canvas.invalid`||/^\/(?:login|register|pub|share-target|apps|next)(?:\/|$)/.test(t.pathname)||t.pathname===`/`||[...t.searchParams.keys()].some(e=>/token|password|secret|code/i.test(e))?null:t.pathname+t.search+t.hash}function wI(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var TI=ql(SI),EI=e=>{let t=CI(e);return t&&sc(TI,t)?t:null};function DI(){let e=pl(),[t]=(0,Q.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:EI(localStorage.getItem(wI(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,Q.useEffect)(()=>{if(n)return;let t=EI(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(wI(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,$.jsx)(Hl,{to:t.path,replace:!0}):null}var OI={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function kI(e,t){switch(t.type){case`RESTORE_MENU`:return{...e,...t.menu,user:e.user};case`SET_SECTION`:return{...e,activeSection:t.section,m1Open:t.section!==null,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_SECTION`:return e.activeSection===t.section&&e.m1Open?{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`TOGGLE_M0`:return e.m0Open?{...e,m0Open:!1,activeSection:null,m1Open:!1,m2Open:!1,m2View:null}:{...e,m0Open:!0};case`CLOSE_M0`:return{...e,m0Open:!1};case`CLOSE_M1`:return{...e,activeSection:null,m1Open:!1,m2Open:!1,m2View:null};case`OPEN_M2`:return{...e,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId===void 0?e.selectedEntityId:t.entityId};case`OPEN_M2_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!0,m2View:t.view,selectedEntityId:t.entityId};case`OPEN_M1_DRAWER`:return{...e,m0Open:!0,activeSection:t.section,m1Open:!0,m2Open:!1,m2View:null,selectedEntityId:null};case`CLOSE_M2`:return{...e,m2Open:!1,m2View:null};case`SELECT_ENTITY`:return{...e,selectedEntityId:t.entityId};case`SYNC_FROM_URL`:{let n=!t.mobile&&!e.m2Open&&e.m2View===null&&t.section===e.activeSection&&t.entityId===e.selectedEntityId;return t.section===e.activeSection&&t.entityId===e.selectedEntityId&&t.m2View===e.m2View&&!(t.mobile&&(e.m1Open||e.m0Open))?e:{...e,activeSection:t.section,m0Open:!t.mobile&&e.m0Open,m1Open:!t.mobile&&t.section!==null,selectedEntityId:t.entityId,m2Open:!n&&t.m2View!==null,m2View:n?null:t.m2View}}case`SET_USER`:return{...e,user:t.user};default:return e}}function AI({children:e}){let[t,n]=(0,Q.useReducer)(kI,OI),r=pl(),i=gl(),a=(0,Q.useRef)(t);(0,Q.useLayoutEffect)(()=>{a.current=t},[t]),IT(t,n);let o=(0,Q.useCallback)((e,t=!1,o=!1)=>{let s=kI(a.current,e);if(a.current=s,n(e),!MT())return;let{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p}=s;i({pathname:r.pathname,search:r.search,hash:r.hash},{replace:t,state:{...r.state,canvasMenu:{activeSection:c,m0Open:l,m1Open:u,m2Open:d,m2View:f,selectedEntityId:p},canvasMenuBack:o}})},[r,i]),s=(0,Q.useCallback)(e=>{if(MT()&&a.current.m1Open){let{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l}=a.current;i(e,{replace:!0,state:{...r.state,canvasMenu:{activeSection:t,m0Open:n,m1Open:o,m2Open:s,m2View:c,selectedEntityId:l},canvasMenuBack:!1}})}i(e)},[r.state,i]),c=(0,Q.useCallback)(()=>{if(window.history.state?.idx>0){i(-1);return}let e=a.current;if(e.m1Open&&e.m2Open)o({type:`CLOSE_M2`},!0,!0);else if(e.m1Open)o({type:`CLOSE_M1`},!0,!0);else if(e.m0Open)o({type:`CLOSE_M0`},!0,!0);else{let{section:e,entityId:t,m2View:n}=FT(r.pathname);if(!MT()){i(e?`/${e}`:`/`);return}o(e&&t?{type:`OPEN_M2_DRAWER`,section:e,view:n,entityId:t}:{type:`TOGGLE_M0`},!0,!0)}},[o,r.pathname,i]);(0,Q.useEffect)(()=>{let e=bd();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return xd().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let l={state:t,dispatch:n,setSection:(0,Q.useCallback)(e=>{o({type:`SET_SECTION`,section:e})},[o]),toggleSection:(0,Q.useCallback)(e=>{o({type:`TOGGLE_SECTION`,section:e})},[o]),toggleM0:(0,Q.useCallback)(()=>{o({type:`TOGGLE_M0`},a.current.m0Open)},[o]),closeM0:(0,Q.useCallback)(()=>{o({type:`CLOSE_M0`},!0)},[o]),closeM1:(0,Q.useCallback)(()=>{o({type:`CLOSE_M1`},!0)},[o]),openM2:(0,Q.useCallback)((e,t)=>{o({type:`OPEN_M2`,view:e,entityId:t})},[o]),openM2Drawer:(0,Q.useCallback)((e,t,n)=>{o({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:n})},[o]),openM1Drawer:(0,Q.useCallback)(e=>{o({type:`OPEN_M1_DRAWER`,section:e})},[o]),closeM2:(0,Q.useCallback)(()=>{MT()&&a.current.m1Open&&a.current.m2Open?c():n({type:`CLOSE_M2`})},[c]),selectEntity:(0,Q.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[]),goBack:c,navigateFromMenu:s};return(0,$.jsx)(NT.Provider,{value:l,children:e})}function jI(){return(0,Q.useSyncExternalStore)(Nr,Tr,()=>!1)}function MI(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&Tr()&&(i=setTimeout(()=>{s()},3e4))}function s(s=!1){if(n)return n;if(r)return Promise.resolve(!1);clearTimeout(i),a=new AbortController;let c=setTimeout(()=>a?.abort(),5e3);return n=(async()=>{try{let n=await fetch(e,{cache:`no-store`,credentials:`omit`,signal:a.signal});if(!n.ok||n.headers.get(`x-canvas-offline`)===`fallback`)throw Error(`Unavailable`);if((await n.json()).status!==`success`)throw Error(`Not a Canvas response`);if(r)return!1;let i=Tr();return Dr(),(i||s)&&t(),!0}catch{return r||Ar(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=Nr(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var NI;function PI(){NI=MI(`${Lr}/ping`,()=>hd.retryNow());let e=()=>{NI?.retry()},t=hd.on(`connect_error`,e),n=hd.on(`disconnect`,e);return()=>{t(),n(),NI?.stop(),NI=void 0}}function FI(){return NI?.retry(!0)??Promise.resolve(!1)}function II(){let e=jI(),[t,n]=(0,Q.useState)(!1);return e?(0,$.jsxs)(`details`,{className:`relative`,children:[(0,$.jsx)(`summary`,{"aria-label":`Offline — connection options`,title:`Offline — cached content available`,className:`flex h-10 w-10 cursor-pointer list-none items-center justify-center rounded-lg text-amber-600 hover:bg-accent/50 [&::-webkit-details-marker]:hidden`,children:(0,$.jsx)(w,{className:`h-5 w-5`})}),(0,$.jsxs)(`div`,{className:`absolute bottom-0 left-full z-50 ml-2 w-60 max-w-[calc(100vw-5rem)] rounded-lg border bg-popover p-3 text-popover-foreground shadow-lg`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`You can browse cached documents. We’ll reconnect automatically when the server is available.`}),(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await FI()}finally{n(!1)}},className:`mt-3 rounded-md bg-secondary px-3 py-2 text-xs font-medium hover:bg-accent disabled:opacity-50`,children:t?`Checking…`:`Retry now`})]})]}):null}var LI=Le,RI=O,zI=nr,BI=Q.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,$.jsx)(ar,{children:(0,$.jsx)(Ct,{ref:r,sideOffset:t,className:J(`z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in duration-fast fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]`,e),...n})}));BI.displayName=Ct.displayName;var VI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(mt,{ref:n,className:J(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));VI.displayName=mt.displayName;var HI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(lr,{ref:n,className:J(`aspect-square h-full w-full`,e),...t}));HI.displayName=lr.displayName;var UI=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(Qn,{ref:n,className:J(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));UI.displayName=Qn.displayName;function WI({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=PT(),o=i.activeSection===e;return(0,$.jsxs)(RI,{children:[(0,$.jsx)(zI,{asChild:!0,children:(0,$.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:J(`relative flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,o?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`,r&&`opacity-30 cursor-not-allowed`),children:[o&&(0,$.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,$.jsx)(BI,{side:`right`,sideOffset:8,children:n})]})}function GI({path:e,icon:t,label:n,section:r=`settings`}){let i=gl(),{setSection:a}=PT();return(0,$.jsxs)(RI,{children:[(0,$.jsx)(zI,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,"aria-label":n,onClick:()=>{a(r),i(e)},className:`flex items-center justify-center w-10 h-10 rounded-lg text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors`,children:t})}),(0,$.jsx)(BI,{side:`right`,sideOffset:8,children:n})]})}function KI(){let{state:e,toggleM0:t}=PT(),n=jI();return(0,$.jsxs)(`button`,{type:`button`,onClick:t,"aria-label":`${e.m0Open?`Close menu`:`Open menu`}${n?` — offline, connection options in menu`:``}`,"data-shell":`rail`,className:`fixed bottom-rail-inset left-2 z-nav flex h-rail w-rail items-center justify-center rounded-full bg-foreground text-background shadow-elevation-4 md:hidden`,children:[e.m0Open?(0,$.jsx)(G,{className:`h-5 w-5`}):(0,$.jsx)(Wn,{className:`h-5 w-5`}),n&&(0,$.jsx)(`span`,{"aria-hidden":!0,className:`absolute right-0 top-0 h-3 w-3 rounded-full border-2 border-background bg-amber-500`})]})}function qI(){let{state:e,closeM0:t,closeM1:n}=PT(),{state:r,setView:i,closeT1:a}=zs(),o=gl(),{showToast:s}=Vr(),c=e.user?.userType===`admin`,l=Gw(),u=()=>{r.t1Open?a():i(`tools`),n(),t()},d=(0,Q.useCallback)(async()=>{try{await X.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,$.jsxs)(LI,{delayDuration:200,children:[e.m0Open&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,$.jsxs)(`div`,{"data-shell":`rail`,className:J(`flex flex-col items-center w-rail h-full rounded-(--panel-radius) bg-transparent shrink-0`,e.m0Open?`max-md:fixed max-md:left-2 max-md:top-2 max-md:bottom-rail-stack max-md:z-rail max-md:h-auto max-md:bg-card max-md:surface-glass max-md:shadow-elevation-5`:`max-md:hidden`),children:[(0,$.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,$.jsx)(`button`,{type:`button`,"aria-label":`Canvas home`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,$.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,$.jsxs)(`nav`,{className:`flex flex-col items-center gap-1 py-2 flex-1 min-h-0 overflow-y-auto`,children:[(!l.local||l.workspace!==!1)&&(0,$.jsx)(WI,{section:`contexts`,icon:(0,$.jsx)(ur,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,$.jsx)(WI,{section:`workspaces`,icon:(0,$.jsx)($n,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,$.jsx)(WI,{section:`agents`,icon:(0,$.jsx)(ct,{className:`w-5 h-5`}),label:`Agents`}),(!l.local||l.workspace!==!1)&&(0,$.jsx)(GI,{path:`/roles`,section:null,icon:(0,$.jsx)(mn,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,$.jsx)(GI,{path:`/admin/users`,icon:(0,$.jsx)(ie,{className:`w-5 h-5`}),label:`All Users`}),(0,$.jsx)(GI,{path:`/admin/logs`,icon:(0,$.jsx)(nn,{className:`w-5 h-5`}),label:`Server Logs`}),(0,$.jsx)(GI,{path:`/admin/workspaces`,icon:(0,$.jsx)(rt,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,$.jsx)(GI,{path:`/admin/agents`,icon:(0,$.jsx)(ct,{className:`w-5 h-5`}),label:`All Agents`}),(0,$.jsx)(GI,{path:`/admin/roles`,icon:(0,$.jsx)(mn,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,$.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,$.jsx)(II,{}),(0,$.jsxs)(RI,{children:[(0,$.jsx)(zI,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,onClick:u,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:J(`flex items-center justify-center w-10 h-10 rounded-lg transition-colors`,r.t1Open?`bg-accent text-foreground`:`text-muted-foreground hover:text-foreground hover:bg-accent/50`),children:(0,$.jsx)(Ne,{className:`w-5 h-5`})})}),(0,$.jsx)(BI,{side:`right`,sideOffset:8,children:`Toolbox`})]}),!l.local&&(0,$.jsx)(GI,{path:`/settings`,section:`settings`,icon:(0,$.jsx)(yn,{className:`w-5 h-5`}),label:`Settings`}),(0,$.jsxs)(RI,{children:[(0,$.jsx)(zI,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,"aria-label":e.user?.email?`Profile: ${e.user.email}`:`Profile`,onClick:()=>o(`/home`),className:`flex items-center justify-center w-10 h-10 rounded-lg hover:bg-accent/50 transition-colors`,children:(0,$.jsx)(VI,{className:`h-7 w-7 touch-target`,children:(0,$.jsx)(UI,{className:`text-[10px] bg-muted`,children:e.user?.email?(e=>e.split(`@`)[0].split(`.`).map(e=>e.charAt(0).toUpperCase()).join(``).slice(0,2))(e.user.email):`U`})})})}),(0,$.jsx)(BI,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,$.jsxs)(RI,{children:[(0,$.jsx)(zI,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,"aria-label":`Log out`,onClick:d,className:`flex items-center justify-center w-10 h-10 rounded-lg text-destructive hover:bg-destructive/10 transition-colors`,children:(0,$.jsx)(Tn,{className:`w-5 h-5`})})}),(0,$.jsx)(BI,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}function JI(e,t,n,r=!0){let i=l_(),a=pl(),o=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{let s=window.history.state?.idx??0,c=o.current,l=a.state?.canvasMenuBack||!!c&&(s<c.index||s===c.index&&c.backwards);if(o.current={active:t,viewKey:n,index:s,backwards:l},!r||!i||!t||!c||c.active&&c.viewKey===n)return;let u=e.current;if(!u||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;let d=Number.parseFloat(getComputedStyle(u).getPropertyValue(`--motion-scale`)),f=Number.isFinite(d)?Math.max(0,d):1,p=u.animate([{transform:`translateX(${l?`-100%`:`100%`})`},{transform:`translateX(0)`}],{duration:70*f,easing:`cubic-bezier(0.2, 0, 0, 1)`});return()=>p.cancel()},[r,i,t,n,a.key,a.state,e])}function YI(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ps();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useRef)(s);(0,Q.useEffect)(()=>{c.current=s});let l=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>hd.emit(`subscribe`,{channel:`context`}),r=()=>hd.emit(`unsubscribe`,{channel:`context`}),i=hd.on(`connect`,()=>{t(),s()});t();let o=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.some(e=>e.id===t.id&&e.userId===t.userId)?e:[...e,t])},l=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},u=e=>{let t=e,r=t?.contextId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},d=e=>{let t=e;!t?.id||!t?.userId||n(e=>e.map(e=>e.id===t.id&&e.userId===t.userId?{...e,...t}:e))},f=()=>{a.current=!1,c.current()},p=[[`context:created`,o],[`context.created`,o],[`context:updated`,l],[`context.updated`,l],[`context:deleted`,u],[`context.deleted`,u],[`context:url:changed`,d],[`context.url.set`,d],[`context:url:set`,d],[`workspace:status:changed`,f],[`workspace.status.changed`,f]];return p.forEach(([e,t])=>hd.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>hd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!ss(e,t)))};return window.addEventListener(os,e),()=>window.removeEventListener(os,e)},[]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,Q.useMemo)(()=>JT(t),[t]),isLoading:r,refresh:l}}function XI(){let{goBack:e}=PT();return(0,$.jsx)(`button`,{type:`button`,onClick:e,"aria-label":`Back to previous view`,title:`Back to previous view`,className:`-ml-2 mr-1 flex h-11 w-11 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent md:hidden`,children:(0,$.jsx)(Jn,{className:`h-5 w-5`})})}function ZI(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=PT(),i=l_(),{contexts:a,isLoading:o}=YI(e.activeSection===`contexts`),{showToast:s}=Vr(),c=gl(),[l,u]=(0,Q.useState)(null),d=l&&l.base===a?l.order:a,p=e=>e.isShared===!0||e.type===`shared`,{rowProps:m,handleProps:h,draggingIndex:g,insertLineClass:_}=ZT((e,t)=>{let n=YT(d,e,t);u({base:a,order:n}),XT(n,(e,t)=>p(e)?Promise.resolve():ls(e.id,{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`contexts:refresh`)),e&&s({title:`Partial reorder`,description:`${e} context(s) could not be reordered`,variant:`destructive`})})}),v=e=>{t(e.id),c(`/contexts/${e.id}`)};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(XI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{r(),c(`/contexts?create=1`)},title:`Create context`,"aria-label":`Create context`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,$.jsx)(`div`,{className:`space-y-1.5 px-2`,children:d.map((r,a)=>{let o=e.selectedEntityId===r.id,s=p(r),l=r.workspaceActive!==!1,u=Nm(r.color);return(0,$.jsxs)(`div`,{...m(a),"data-active":o||void 0,className:J(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,l?`cursor-pointer hover:shadow `+(o?`bg-accent shadow`:`bg-card hover:bg-accent/50`):`cursor-not-allowed opacity-50 bg-card`,_(a,d.length),g===a&&`opacity-60`),onClick:()=>l&&v(r),title:l?void 0:`Workspace "${r.workspaceName}" is not active`,children:[s?(0,$.jsx)(`div`,{className:J(`absolute inset-y-0 right-0 w-4 rounded-r-(--card-radius)`,!u&&`bg-muted`),style:u?{backgroundColor:u}:void 0}):(0,$.jsx)(`button`,{type:`button`,...h(a),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:J(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!u&&`bg-muted`),style:u?{backgroundColor:u}:void 0,children:(0,$.jsx)(T,{className:J(`h-3.5 w-3.5`,Pm(u))})}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(f,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:u,className:J(`mt-0.5 shrink-0`,!u&&`text-muted-foreground`)}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),s&&(0,$.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),l&&(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),n(`detail`,r.id)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Switch context URL`,children:(0,$.jsx)(Zt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),i?n(`settings`,r.id):c(`/contexts/${r.id}/settings/general`)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Settings`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function QI({title:e,onBack:t,action:n,className:r,icon:i,accentColor:a}){let{closeM1:o}=PT(),s=Nm(a);return(0,$.jsxs)(`div`,{className:J(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{borderBottomWidth:4,...s?{borderBottomColor:s}:{}},children:[(0,$.jsxs)(`button`,{type:`button`,onClick:t,className:`flex items-center gap-0.5 h-8 rounded px-1 hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors flex-1 min-w-0`,title:`Back`,"aria-label":`Back to previous view`,children:[(0,$.jsx)(E,{className:`w-4 h-4 shrink-0`}),i&&(0,$.jsx)(f,{icon:i,width:16,height:16,color:s,className:J(`mr-1 shrink-0`,!s&&`text-muted-foreground`)}),(0,$.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,$.jsx)(`div`,{className:`shrink-0`,children:n}),(0,$.jsx)(`button`,{type:`button`,onClick:o,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Close menu`,"aria-label":`Close menu`,children:(0,$.jsx)(G,{className:`w-4 h-4`})})]})}var $I=22,eL=44,tL=4;function nL(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?null:n[0]===`workspace`&&n.length>=2?{address:`workspace:${n[1]}`,key:n.slice(2).join(`/`)}:n[0]===`device`&&n.length>=3?{address:n[2],key:n.slice(3).join(`/`)}:n[0]===`file`&&n.length>=2?{address:n[1],key:n.slice(2).join(`/`)}:null}function rL(e,t){return!t||ho(e)!==null}var iL=e=>Array.from(e.dataTransfer.types).includes(`application/json`);function aL(e,t){if(!t)return null;let n=String(e||``).split(`/`).filter(Boolean);return n[0]===`workspace`&&n[1]===`git`?n[2]||null:n[0]===`workspace`&&n.length>=2?`workspace:${n[1]}`:n[0]===`device`?n.length>=3?n[2]:null:n.length>=2?n[1]:null}function oL({x:e,y:t,node:n,path:r,isBackendsTree:i,isDirectoryTree:a,backends:o,onClose:s,onShowContent:c,onOpenToSide:l,sourceLayer:u,targetLayers:d,clipboard:f,onStartInlineCreate:p,onChangeIcon:m,onNewCanvas:h,onShareCanvas:g,onRemove:_,onRename:v,onExportSubtree:y,onImportSubtree:b,onLock:x,onUnlock:S,onDestroy:C,onMerge:w,onSubtract:T,onMergeDown:E,onSubtractDown:D,onResyncBackend:O,onAddRule:k,onAddStoreRule:j,onStoragePolicy:M,onRenameBackendFolder:N,onDeleteBackendFolder:F,onRestoreTrash:I,onDiscardTrash:L,onCopy:R,onCut:z,onPaste:te,pastedDocumentIds:B,onPasteDocuments:re,isPinned:ie,onTogglePin:ae}){let oe=u&&d.size>0&&u.path===r,H=!i&&(E||D)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,U=u&&d.size>0&&(u.path===r||d.has(r)),se=async e=>{s();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},W=(e,t,n,r=!1)=>(0,$.jsxs)(`button`,{type:`button`,className:J(`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,r&&`text-destructive hover:bg-destructive/10`),onClick:()=>se(n),children:[e,t]});return i&&n.metadata?.backendTrash?(0,$.jsxs)(em,{x:e,y:t,onClose:s,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&W((0,$.jsx)(nt,{className:`h-3 w-3`}),`Open Trash`,async()=>c(r)),r!==`/Trash`&&I&&W((0,$.jsx)(ir,{className:`h-3 w-3`}),`Restore original paths`,()=>I(r)),r!==`/Trash`&&L&&W((0,$.jsx)(nt,{className:`h-3 w-3`}),`Empty Trash`,()=>L(r),!0)]}):(0,$.jsxs)(em,{x:e,y:t,onClose:s,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[c&&W((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Show layer content`,async()=>{c(r,n.id||void 0)}),l&&W((0,$.jsx)(Xn,{className:`w-3 h-3`}),`Open to the side`,async()=>{l(r)}),(c||l)&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&g&&W((0,$.jsx)(jn,{className:`w-3 h-3`}),`Share canvas`,async()=>{await g(r)}),n.type===`canvas`&&g&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),O&&aL(r,i)&&(0,$.jsxs)($.Fragment,{children:[W((0,$.jsx)(P,{className:`w-3 h-3`}),`Resync backend (${aL(r,i)})`,async()=>{await O(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&aL(r,i)&&(k||j)&&(0,$.jsxs)($.Fragment,{children:[k&&W((0,$.jsx)(Nn,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{k(r)}),j&&nL(r,i)&&W((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{j(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(j||M)&&r!==`/`&&(0,$.jsxs)($.Fragment,{children:[j&&W((0,$.jsx)(Pe,{className:`w-3 h-3`}),`Create rule…`,async()=>{j(r)}),j&&W((0,$.jsx)(qt,{className:`w-3 h-3`}),`Create download rule…`,async()=>{j(r,`download`)}),M&&n.type!==`canvas`&&W((0,$.jsx)(fe,{className:`w-3 h-3`}),`Storage policy…`,async()=>{M(r)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||nL(r,i))&&(0,$.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{p(r),s()},children:[(0,$.jsx)(sn,{className:`w-3 h-3`}),`New folder here`]}),N&&nL(r,i)?.key&&W((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await N(r,t)}),F&&i&&po(r,o)&&W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await F(r)},!0),h&&!i&&(0,$.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{h(r),s()},children:[(0,$.jsx)(gt,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&ae&&W(ie?(0,$.jsx)(ee,{className:`w-3 h-3`}):(0,$.jsx)(Oe,{className:`w-3 h-3`}),ie?`Unpin`:`Pin`,async()=>{await ae()}),r!==`/`&&m&&(0,$.jsxs)(`button`,{type:`button`,className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent rounded-sm text-left`,onClick:()=>{m(),s()},children:[(0,$.jsx)(V,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&v&&!i&&W((0,$.jsx)(Ie,{className:`w-3 h-3`}),`Rename`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New name:`,e);!t||t===e||await v(r,t)}),(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),W((0,$.jsx)(A,{className:`w-3 h-3`}),`Copy`,async()=>R(r)),!i&&W((0,$.jsx)(Et,{className:`w-3 h-3`}),`Cut`,async()=>z(r)),f&&!i&&W((0,$.jsx)(Ce,{className:`w-3 h-3`}),`Paste (${f.mode})`,async()=>te(r)),B&&B.length>0&&re&&rL(r,i)&&W((0,$.jsx)(Ce,{className:`w-3 h-3`}),i?`Move ${B.length} message(s) here`:`Paste ${B.length} document(s)`,async()=>{await re(r,B)}),(y||b)&&(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),y&&n.type!==`canvas`&&W((0,$.jsx)(qt,{className:`w-3 h-3`}),`Export subtree…`,()=>y(r)),b&&!i&&n.type!==`canvas`&&W((0,$.jsx)(ne,{className:`w-3 h-3`}),`Import subtree here…`,()=>b(r)),!i&&r!==`/`&&!n.locked&&_&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"${a?` and all children`:``}?`)&&await _(r,a)},!0),!a&&W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await _(r,!0)},!0)]}),!i&&(x||S||C)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?S&&W((0,$.jsx)(Ot,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await S(n.id)}):x&&W((0,$.jsx)(Vn,{className:`w-3 h-3`}),`Lock layer`,async()=>{await x(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`px-3 pt-1 pb-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Locked by`}),n.lockedBy.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,$.jsx)(`span`,{className:`truncate`,title:e,children:e}),S&&(0,$.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>se(async()=>{await S(n.id,e)}),children:(0,$.jsx)(Ot,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&C&&W((0,$.jsx)(nt,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await C(n.id)},!0)]}),H&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),E&&W((0,$.jsx)(kn,{className:`w-3 h-3`}),`Merge down (into ancestors)`,async()=>{confirm(`Merge "${n.label||n.name}" into every layer above it on\n${r}\n\nAfter this, ${r} lists its documents.`)&&await E(r)}),D&&W((0,$.jsx)(Bn,{className:`w-3 h-3`}),`Subtract from ancestors`,async()=>{confirm(`Remove "${n.label||n.name}"'s documents from every layer above it on\n${r}\n\nUndo of "Merge down". Documents an ancestor holds for other reasons are removed from it too.`)&&await D(r)})]}),oe&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),w&&W((0,$.jsx)(ur,{className:`w-3 h-3`}),`Merge this layer into ${d.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(d.keys()).join(`
52
52
  `)}\n\nThe selected layers gain this layer's documents. This layer is unchanged.`)&&await w(n.id,Array.from(d.values()))}),T&&W((0,$.jsx)(ur,{className:`w-3 h-3`}),`Subtract this layer from ${d.size} selected`,async()=>{confirm(`Subtract "${r}" (source) FROM:\n${Array.from(d.keys()).join(`
53
- `)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await T(n.id,Array.from(d.values()))})]}),U&&!oe&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,$.jsxs)(`div`,{className:`px-3 py-1.5 text-[10px] text-muted-foreground italic`,children:[`This is a target. Right-click the source (`,u?.path,`) to merge/subtract`]})]})]})}function sL({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,$.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 bg-card ring-1 ring-primary/50 shadow-elevation-3 text-sm font-medium`,children:[(0,$.jsx)(hr,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,$.jsx)(`input`,{ref:r,className:`flex-1 bg-transparent outline-none min-w-0 text-sm font-medium placeholder:font-normal placeholder:text-muted-foreground`,placeholder:n,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),i()),e.key===`Escape`&&t()},onBlur:i})]})}function cL(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function lL(e,t,n){let r=cL(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>lL(e,r,n))??!1}function uL({node:e,parentPath:t,depth:n,isLast:r,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:c,targetLayers:l,clipboard:u,searchQuery:d,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,policyBadgeFor:M,removingPaths:N,accordion:F=!1,trail:I=[]}){let L=Ep(),R=cL(t,e.name),z=M?.(R)??null,ee=S.get(R)??wm(e),[te,ne]=(0,Q.useState)(()=>i!==`/`&&(i===R||i.startsWith(R+`/`))),[B,re]=(0,Q.useState)(i);if(B!==i&&(re(i),i!==`/`&&i.startsWith(R+`/`)&&ne(!0)),d&&!lL(e,t,d))return null;let ie=te||p===R||d.length>0,ae=e.children&&e.children.length>0,oe=i===R,V=a===R,H=c?.path===R,U=l.has(R),se=e.type===`canvas`,W=t=>{if(t.ctrlKey||t.metaKey){_(R,e.id);return}if(t.shiftKey&&h){h(R);return}m(R)},ce=e=>{!ae||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button, input, textarea, select, a, [contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),ne(e=>!e))},le=[...I].reverse().find(Boolean)??null,ue=ee.color||le,de=F?[...I,ue]:I,pe=i!==`/`&&i.startsWith(R+`/`),me=!H&&!U,G=me&&oe,he=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,ge=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,_e=Math.min(n,5),ve=ie&&!!ae,K=n>0&&le?le:ue,q=me&&!G&&!e.locked&&ve,ye=K?Math.min(12+_e*5+(pe?6:0),34):Math.min(_e*7+(pe?5:0)+(V?3:0),30),be=G?`var(--primary)`:H?he(`var(--info)`,22):U?he(`var(--warning)`,22):e.locked?he(`var(--warning)`,20+_e*4):q?ue?he(ue,84):he(`var(--foreground)`,38):he(K||`var(--foreground)`,ye),xe=G?`text-primary-foreground`:q&&ue?Fm(ue):`text-foreground`,Se=F&&ie&&ae&&n<tL,Ce=(0,$.jsxs)(`div`,{"data-active":oe||void 0,className:J(`group relative flex cursor-pointer select-none items-stretch overflow-hidden text-sm`,`after:pointer-events-none after:absolute after:inset-0 after:bg-foreground/0 after:transition-colors hover:after:bg-foreground/[0.07]`,xe,H&&`ring-1 ring-inset ring-info/40`,U&&!H&&`ring-1 ring-inset ring-warning/40`,C===R&&!s&&!w&&`ring-2 ring-inset ring-info`,C===R&&!s&&w&&`ring-2 ring-inset ring-success`),style:{height:eL,background:be,borderBottom:`1px solid ${ge(14)}`,...Se?{position:`sticky`,top:n*eL,zIndex:20-n}:{}},draggable:!s&&!e.metadata?.backendTrash,onClick:W,onDoubleClick:ce,...s?{}:L,onContextMenu:t=>{s||(t.preventDefault(),v(t,R,e))},onDragStart:e=>{s||T(R,e)},onDragEnter:e=>{s||E(R,e)},onDragOver:e=>{s||D(R,e)},onDragLeave:e=>O(R,e),onDragEnd:()=>k(),onDrop:e=>{s||A(R,e)},children:[I.length>0&&(0,$.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:I.map((e,t)=>(0,$.jsx)(`span`,{className:`w-[3px]`,style:{background:e||ge(28)}},t))}),(()=>{let t=ee.color?{background:ee.color}:le?{background:`color-mix(in oklab, ${le} 45%, transparent)`}:{background:ge(10)},n=(0,$.jsx)(f,{icon:ee.icon||(se?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:J(`shrink-0`,ee.color?Pm(ee.color):G?`text-primary-foreground`:q?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return x?(0,$.jsx)(`button`,{type:`button`,className:r,style:t,title:`Change icon`,onClick:t=>{br()||(t.stopPropagation(),x(t,R,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,R,e)},children:n}):(0,$.jsx)(`span`,{className:r,style:t,children:n})})(),(0,$.jsx)(`span`,{className:J(`min-w-0 flex-1 self-center truncate px-2.5`,oe||pe||ve?`font-semibold`:`font-medium`),title:e.description||void 0,children:e.label||e.name}),N.has(R)&&(0,$.jsx)(P,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":N.get(R)}),j?.has(R)&&(0,$.jsx)(P,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),z&&(0,$.jsx)(fe,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":z,children:(0,$.jsx)(`title`,{children:z})}),!s&&(0,$.jsx)(`button`,{type:`button`,className:`reveal-on-hover shrink-0 self-center rounded p-1 hover:bg-foreground/10`,onClick:t=>{t.stopPropagation(),v(t,R,e)},children:(0,$.jsx)(vn,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{type:`button`,className:J(`relative z-[1] flex w-12 shrink-0 cursor-pointer items-center justify-center transition-colors`,`bg-[color-mix(in_oklab,currentColor_9%,transparent)] hover:bg-[color-mix(in_oklab,currentColor_24%,transparent)] active:bg-[color-mix(in_oklab,currentColor_32%,transparent)]`,!ae&&p!==R&&`invisible`),style:{borderLeft:`1px solid ${ge(16)}`},"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,title:ie?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,$.jsx)(Xe,{className:`h-5 w-5`,strokeWidth:2.25}):(0,$.jsx)(hr,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,$.jsxs)(`div`,{className:`relative`,children:[F?Ce:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${$I/2}px`,...r?{height:`1.375rem`}:{bottom:0}}}),(0,$.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${$I/2}px`,width:`${$I/2}px`}}),(0,$.jsxs)(`div`,{"data-active":oe||void 0,className:J(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none overflow-hidden`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,H&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,U&&!H&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!H&&!U&&oe&&!e.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!H&&!U&&oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!H&&!U&&!oe&&V&&`bg-primary/[0.03] before:bg-transparent`,!H&&!U&&!oe&&!V&&!e.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!H&&!U&&!oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,C===R&&!s&&!w&&`ring-2 ring-info bg-info-subtle/50`,C===R&&!s&&w&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:ee.color?`4px solid ${ee.color}`:`4px solid transparent`},draggable:!s&&!e.metadata?.backendTrash,onClick:W,onDoubleClick:ce,...s?{}:L,onContextMenu:t=>{s||(t.preventDefault(),v(t,R,e))},onDragStart:e=>{s||T(R,e)},onDragEnter:e=>{s||E(R,e)},onDragOver:e=>{s||D(R,e)},onDragLeave:e=>O(R,e),onDragEnd:()=>k(),onDrop:e=>{s||A(R,e)},children:[(0,$.jsx)(`button`,{type:`button`,className:J(`shrink-0 text-muted-foreground hover:text-foreground`,!ae&&p!==R&&`invisible`),"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,$.jsx)(Xe,{className:`w-4 h-4`}):(0,$.jsx)(hr,{className:`w-4 h-4`})}),(()=>{let t=(0,$.jsx)(f,{icon:ee.icon||(se?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:ee.color||void 0,className:J(`shrink-0`,!ee.color&&(se?`text-primary`:`text-muted-foreground`))});return x?(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 rounded p-0.5 -m-0.5 hover:bg-muted-foreground/10 touch-target`,title:`Change icon`,onClick:t=>{br()||(t.stopPropagation(),x(t,R,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,R,e)},children:t}):t})(),(0,$.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name}),N.has(R)&&(0,$.jsx)(P,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":N.get(R)}),j?.has(R)&&(0,$.jsx)(P,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),z&&(0,$.jsx)(fe,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":z,children:(0,$.jsx)(`title`,{children:z})}),!s&&(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:t=>{t.stopPropagation(),v(t,R,e)},children:(0,$.jsx)(vn,{className:`w-4 h-4`})})]})]}),ie&&(ae||p===R)&&(0,$.jsxs)(`div`,{className:F?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[p===R&&(0,$.jsx)(sL,{onConfirm:e=>y(R,e),onCancel:b}),e.children?.map((t,r)=>(0,$.jsx)(uL,{node:t,parentPath:R,depth:n+1,isLast:r===(e.children?.length??0)-1,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:c,targetLayers:l,clipboard:u,searchQuery:d,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,policyBadgeFor:M,removingPaths:N,accordion:F,trail:de},t.id||t.name))]})]})}function dL({root:e,workspaceId:t,treeName:n=`context`,isBackendsTree:r=!1,onRestoreTrash:i,onDiscardTrash:a,selectedPath:o,pendingPath:s,onSelect:c,isLoading:l=!1,readOnly:u=!1,onAddRule:d,onAddStoreRule:f,onStoragePolicy:p,policyBadgeFor:m,rootLabel:h,contentPath:g,onShowContent:_,onOpenToSide:v,onShiftSelect:y,onInsertPath:b,onNewCanvas:x,onShareCanvas:S,onRemovePath:C,onRenamePath:w,onMovePath:T,onCopyPath:E,onExportSubtree:D,onImportSubtree:O,pastedDocumentIds:k,onPasteDocuments:A,onLockLayer:j,onUnlockLayer:M,onDestroyLayer:N,onMergeLayer:F,onSubtractLayer:I,onMergeDown:L,onSubtractDown:R,onResyncBackend:z,onCreateBackendFolder:ee,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onUpdateNode:B,isPathPinned:re,onTogglePin:ie,searchQuery:ae=``,resyncingPaths:oe,backends:V}){let H=_A(),[U,se]=(0,Q.useState)(null),[W,ce]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(new Map),[de,fe]=(0,Q.useState)(null),[pe,me]=(0,Q.useState)(new Map),G=(0,Q.useRef)(new Set),he=(0,Q.useCallback)(async(e,t=!1,i=!1,a=!1)=>{if(!(r?ne:C)||[...G.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;G.current.add(e);let o=r?`Deleting from backend…`:a?`Removing documents and backend files…`:i?`Removing and purging documents…`:`Removing folder…`;me(t=>new Map(t).set(e,o));try{return r?await ne(e):await C(e,n===`directory`||t,i,a)}finally{G.current.delete(e),me(t=>{let n=new Map(t);return n.delete(e),n})}},[C,ne,r,n]),[ge,_e]=(0,Q.useState)(null),[ve,K]=(0,Q.useState)(new Map),[q,ye]=(0,Q.useState)(e),be=(0,Q.useRef)(new Map),xe=(0,Q.useRef)(null),[Se,Ce]=(0,Q.useState)(null);if(e!==q){ye(e);let t=Se;K(t?new Map([[t.path,t.style]]):new Map)}let[we,Te]=(0,Q.useState)(null),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)(!1),[Ae,je]=(0,Q.useState)(!1),[Me,Ne]=(0,Q.useState)(!1),Pe=(0,Q.useRef)(!1),Fe=(0,Q.useRef)(null),Ie=(0,Q.useRef)(n),Le=(0,Q.useRef)(!1),Re=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=e=>{se(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||Re.current;Le.current=t,ke(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let ze=(0,Q.useCallback)((e,t,r)=>{if(pb(Ie.current,e)||pb(n,t))return!1;if(Ie.current!==n)return!0;let i=e.endsWith(`/`)?e.slice(0,-1):e,a=t.endsWith(`/`)?t.slice(0,-1):t,o=i.substring(0,i.lastIndexOf(`/`))||`/`;return!(a.startsWith(i+`/`)||i===a||!r&&a===o)},[n]),Be=(0,Q.useCallback)((e,t)=>{if(pb(n,e)){t.preventDefault();return}Fe.current=e,Ie.current=n,t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:n})),t.dataTransfer.effectAllowed=`copyMove`},[n]),Ve=e=>e.ctrlKey||e.altKey||Re.current,He=(0,Q.useCallback)((e,t)=>{if(pb(n,e))return;let i=Fe.current,a=Ve(t);if(a!==Le.current&&(Le.current=a,ke(a)),i){if(!ze(i,e,a))return}else if(iL(t)&&!rL(e,r))return;t.preventDefault(),De(e)},[ze,n,r]),Ue=(0,Q.useCallback)((e,t)=>{if(pb(n,e)){t.dataTransfer.dropEffect=`none`;return}let i=Ve(t);i!==Le.current&&(Le.current=i,ke(i));let a=Fe.current;if(a){if(!ze(a,e,i)){t.dataTransfer.dropEffect=`none`;return}}else if(iL(t)&&!rL(e,r)){t.dataTransfer.dropEffect=`none`;return}t.preventDefault(),t.dataTransfer.dropEffect=i&&!r?`copy`:`move`},[ze,n,r]),We=(0,Q.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||De(t=>t===e?null:t)},[]),Ge=(0,Q.useCallback)(()=>{Fe.current=null,Ie.current=n,Le.current=!1,ke(!1),De(null)},[n]),Ke=(0,Q.useCallback)(async(e,i)=>{if(i.preventDefault(),i.stopPropagation(),pb(n,e))return;let a=(()=>{try{return JSON.parse(i.dataTransfer.getData(`application/json`))}catch{return null}})();if(a?.type===`document`&&Array.isArray(a.documentIds)&&a.documentIds.length){if(Fe.current=null,Le.current=!1,ke(!1),De(null),_g(a,t,n,e))return;if(A&&rL(e,r))try{await A(e,a.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let o=(()=>{try{return JSON.parse(i.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),s=o?.path||i.dataTransfer.getData(`text/plain`),c=o?.treeName||Ie.current||n;if(pb(c,s))return;let l=Ve(i)||Le.current;if(Fe.current=null,Ie.current=n,Le.current=!1,ke(!1),De(null),!s)return;let u=i.shiftKey,d=c!==n;if(!(!d&&s===e)&&!(!d&&!ze(s,e,l)))try{if(l&&E)await E(s,e,u,c,n);else if(!l&&T){let t=Pe.current&&!r&&!!L;await T(s,e,u,c,n,t?{mergeDown:t}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[ze,E,T,A,t,n,r,L]),qe=ae.toLowerCase().trim(),Je=(0,Q.useCallback)((e,t,n)=>{e.stopPropagation(),fe({x:e.clientX,y:e.clientY,path:t,node:n})},[]),Ye=(0,Q.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(xe.current=null,Ce(null),_e({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),Ze=(0,Q.useCallback)(e=>{if(!ge||!B)return;let t=ge.path,n={...ve.get(t)??(xe.current?.path===t?xe.current.style:wm(ge.node)),...e};xe.current={path:t,style:n},Ce({path:t,style:n}),K(e=>new Map(e).set(t,n));let r=Em(ge.node.metadata,n),i=be.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),B(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[ge,B,ve]),Qe=(0,Q.useCallback)((e,t)=>{W?e===W.path?(ce(null),ue(new Map)):ue(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(ce({path:e,id:t}),ue(new Map))},[W]),$e=(0,Q.useCallback)(async e=>{!U||!T||!E||U.treeName===n&&(e===U.path||e.startsWith(U.path+`/`))||(U.mode===`cut`?(await T(U.path,e,!1,U.treeName,n),se(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))):await E(U.path,e,!0,U.treeName,n))},[U,T,E,n]);(0,Q.useEffect)(()=>{if(u)return;let e=e=>{let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),U?.mode===`cut`){$e(o);return}let r={mode:`cut`,path:o,treeName:n};se(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[U,$e,u,o,n]);let et=(0,Q.useCallback)(async(e,t)=>{Te(null);let n=e===`/`?`/${t}`:`${e}/${t}`;try{nL(e,r)&&ee?await ee(e,t)&&c(n):b&&await b(n,!0)&&c(n)}catch(e){alert(e instanceof Error?e.message:String(e))}},[b,ee,c,r]),tt=(0,Q.useCallback)(()=>{Te(null)},[]),nt=(0,Q.useCallback)((e,t)=>{let r={mode:t,path:e,treeName:n};se(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))},[n]),rt=(0,Q.useCallback)(t=>{if(u||am(t.target)||o&&pb(n,o))return;if(im(t,`Mod+V`)){k?.length&&A&&o&&rL(o,r)?(t.preventDefault(),A(o,k).catch(()=>{})):U&&o&&(t.preventDefault(),$e(o).catch(e=>alert(e instanceof Error?e.message:String(e))));return}if(o&&o!==`/`&&(im(t,`Mod+C`)||!r&&im(t,`Mod+X`))){t.preventDefault(),nt(o,t.key.toLowerCase()===`x`?`cut`:`copy`);return}if((r?!ne||!po(o||``,V):!C)||t.key!==`Delete`&&t.key!==`Backspace`||!o||o===`/`)return;t.preventDefault();let i=di(e,o);if(!r&&i?.locked){alert(`"${o}" is locked`);return}confirm(r?`Delete "${o}" and its contents from this backend?`:`Remove "${o}"${n===`directory`?` and all children`:``}?`)&&he(o,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))},[u,C,ne,he,o,e,k,A,U,$e,r,nt,n,V]),it=(0,Q.useCallback)(()=>{je(e=>{let t=!e;return Re.current=t,Le.current=t,ke(t),t})},[]);if(l)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let at=W||le.size>0,ot={accordion:H,selectedPath:o,pendingPath:s,contentPath:g,readOnly:u,sourceLayer:W,targetLayers:le,clipboard:U,searchQuery:qe,inlineCreateParent:we,onSelect:c,onShiftSelect:y,onShowContent:_,onCtrl:Qe,onCtxMenu:Je,onConfirmCreate:et,onCancelCreate:tt,onOpenPicker:B?Ye:void 0,styleOverrides:ve,dragOverPath:Ee,isCopyDrag:Oe,onDragStart:Be,onDragEnter:He,onDragOver:Ue,onDragLeave:We,onDragEnd:Ge,onDrop:Ke,resyncingPaths:oe,backends:V,policyBadgeFor:r?void 0:m,removingPaths:pe};return(0,$.jsxs)(`div`,{className:`px-3 py-2 space-y-1.5 outline-none`,tabIndex:0,onKeyDown:rt,children:[pe.size>0&&(0,$.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-1 rounded-md border bg-muted/50 p-2 text-xs`,children:[...pe].map(([e,t])=>(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(P,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block`,children:t}),(0,$.jsx)(`span`,{className:`block truncate text-muted-foreground`,title:e,children:e})]})]},e))}),!u&&(0,$.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:it,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:J(`px-2 py-0.5 rounded-full border transition-colors select-none`,Ae?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:Ae?`Drag → Copy`:`Drag → Move`}),L&&!r&&!Ae&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>Ne(e=>(Pe.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:J(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,Me?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:Me?`+ merge down`:`merge down: off`})]}),at&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,$.jsx)(`span`,{children:W?`Source: ${W.path} · ${le.size} target(s)`:`Select source with ⌃-click`}),(0,$.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{ce(null),ue(new Map)},children:`clear`})]}),(0,$.jsxs)(`div`,{"data-active":o===`/`&&!g||void 0,className:J(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,o===`/`&&!g?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,Ee===`/`&&!u&&!Oe&&`ring-2 ring-info bg-info-subtle/50`,Ee===`/`&&!u&&Oe&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>c(`/`),onDragEnter:e=>{u||He(`/`,e)},onDragOver:e=>{u||Ue(`/`,e)},onDragLeave:e=>We(`/`,e),onDrop:e=>{u||Ke(`/`,e)},onContextMenu:e=>{!u&&b&&(e.preventDefault(),fe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,$.jsx)(Xe,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,h&&(0,$.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,h,`]`]})]}),!u&&b&&(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:e=>{e.stopPropagation(),fe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,$.jsx)(vn,{className:`w-4 h-4`})})]}),(0,$.jsxs)(`div`,{className:H?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[we===`/`&&(0,$.jsx)(sL,{onConfirm:e=>et(`/`,e),onCancel:tt}),e.children?.map((t,n)=>(0,$.jsx)(uL,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...ot},t.id||t.name)),!e.children?.length&&we!==`/`&&(0,$.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),de&&(0,$.jsx)(oL,{x:de.x,y:de.y,node:de.node,path:de.path,isBackendsTree:r,backends:V,isDirectoryTree:n===`directory`,onClose:()=>fe(null),onShowContent:de.node.metadata?.backendTrash?c:_,onRestoreTrash:u?void 0:i,onDiscardTrash:u?void 0:a,onOpenToSide:v?e=>v(e,n):void 0,sourceLayer:W,targetLayers:le,clipboard:U,onStartInlineCreate:e=>Te(e),onChangeIcon:B?()=>Ye({clientX:de.x,clientY:de.y,stopPropagation:()=>{}},de.path,de.node):void 0,onNewCanvas:x,onShareCanvas:S,onExportSubtree:D,onImportSubtree:u?void 0:O,onRemove:!u&&C&&![...pe.keys()].some(e=>e===de.path||e.startsWith(de.path+`/`)||de.path.startsWith(e+`/`))?he:void 0,onRename:u?void 0:w,onLock:u?void 0:j,onUnlock:u?void 0:M,onDestroy:u?void 0:N,onMerge:u?void 0:F,onSubtract:u?void 0:I,onMergeDown:u?void 0:L,onSubtractDown:u?void 0:R,onResyncBackend:z,onAddRule:d,onAddStoreRule:f,onStoragePolicy:!u&&!r?p:void 0,onRenameBackendFolder:te,onDeleteBackendFolder:!u&&ne&&![...pe.keys()].some(e=>e===de.path||e.startsWith(de.path+`/`)||de.path.startsWith(e+`/`))?e=>he(e,!0):void 0,onCopy:e=>nt(e,`copy`),onCut:e=>nt(e,`cut`),onPaste:$e,pastedDocumentIds:k,onPasteDocuments:A,isPinned:re?re(de.path):!1,onTogglePin:ie?()=>ie(de.path,de.node):void 0}),ge&&B&&(0,$.jsx)(Zw,{x:ge.x,y:ge.y,current:ve.get(ge.path)??wm(ge.node),onChange:Ze,onClose:()=>_e(null)})]})}function fL(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=PT(),a=l_(),o=gl(),s=e.selectedEntityId,{showToast:c}=Vr(),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(`/`),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(!1),k=(0,Q.useCallback)(async e=>{w(!0);try{let t=await gs(e);f(t),E(null)}catch(e){E(e instanceof Error?e.message:`Failed to load the tree`)}finally{w(!1)}},[]);(0,Q.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await Cs(e);if(t)return;u(n),m(n.url||``),g(void 0),v(``),S(null),b(n.path||`/`),w(!0);try{let n=await gs(e);t||(f(n),E(null))}catch(e){t||E(e instanceof Error?e.message:`Failed to load the tree`)}finally{t||w(!1)}}catch{t||c({title:`Error`,description:`Failed to load context`,variant:`destructive`})}}n();let r=t=>{t.detail?.contextId===e&&n()};return window.addEventListener(`contexts:refresh`,r),()=>{t=!0,window.removeEventListener(`contexts:refresh`,r)}},[s,c]);let A=jb({contextId:s??void 0,onRefresh:()=>{s&&k(s)}}),j=e=>{g(void 0),S(e),m(l?.workspaceName?`${l.workspaceName}://${e.replace(/^\//,``)}`:e)},M=l!=null&&(p.trim()!==(l.url||``)||h!==void 0);return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(QI,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s&&(a?i(`settings`,s):o(`/contexts/${s}/settings/general`))},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Settings`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})}),(0,$.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(ah,{presentation:`breadcrumbs`,value:p,fixedWorkspaceName:l?.workspaceName,pickerTitle:`Switch context to…`,onPickTarget:(e,t)=>{m(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),g(t.treeName),S(null)},onChange:e=>{m(e),S(h?null:`/`+e.replace(/^.*?:\/\//,``).replace(/^\/+/,``))},disabled:D,className:`min-w-0 flex-1`,inputClassName:J(`text-xs transition-colors`,M&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,$.jsx)(Z,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;O(!0);try{await is(e,p,void 0,h);let t=await Cs(e);u(t),m(t.url||``),b(t.path||`/`),S(null),g(void 0),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),await k(e),c({title:`Saved`,description:`Context URL updated`}),window.matchMedia(`(max-width: 767px)`).matches&&(n(),r())}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{O(!1)}},disabled:D||!M,children:D?`…`:`Set`})]})]}),h&&(0,$.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,h,` · press Set to apply`]}),(0,$.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,$.jsx)(Y,{type:`search`,name:`context-tree-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search context tree`,placeholder:`Search paths…`,value:_,onChange:e=>v(e.target.value),className:`h-7 text-xs`})}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,$.jsxs)(`div`,{className:`text-[10px] text-muted-foreground px-3 pt-2 pb-1 font-medium uppercase tracking-wide shrink-0`,children:[l?.workspaceName||`Workspace`,` · `,d?.type===`directory`?`directory`:`context`,` tree`]}),T&&!d&&(0,$.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:T}),(0,$.jsx)(dL,{root:d,workspaceId:l?.workspaceName,searchQuery:_,selectedPath:y,pendingPath:x,onSelect:j,isLoading:C,rootLabel:l?.workspaceName,...A})]})]})}function pL({items:e,activeId:t,onSelect:n}){let[r,i]=(0,Q.useState)(``),a=e.filter(e=>dT(r,e.label,e.description||``));return(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,$.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,$.jsx)(Y,{type:`search`,name:`settings-section-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,$.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching settings.`}),a.map(e=>{let r=e.id===t;return(0,$.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:J(`flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left transition-colors`,r?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,$.jsx)(`span`,{className:J(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,$.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,$.jsx)(hr,{className:J(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}function mL(){let{state:e,closeM2:t}=PT(),n=l_(),r=gl(),i=pl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return Cs(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?HO(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,Q.useMemo)(()=>VO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>u&&r(u),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open context`,children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),(0,$.jsx)(pL,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function hL(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Ni();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>hd.emit(`subscribe`,{channel:`workspace`}),r=()=>hd.emit(`unsubscribe`,{channel:`workspace`}),i=hd.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e,r=t?.workspaceId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},o=e=>{let t=e?.workspace??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},c=e=>{let t=e,r=t?.workspaceId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=[[`workspace:status:changed`,a],[`workspace.status.changed`,a],[`workspace:created`,o],[`workspace.created`,o],[`workspace:deleted`,c],[`workspace.deleted`,c]];return l.forEach(([e,t])=>hd.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>hd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,Q.useMemo)(()=>JT(t),[t]),isLoading:r,refresh:c}}function gL({status:e}){return(0,$.jsx)(`span`,{className:J(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function _L(){let e=Gw(),{state:t,selectEntity:n,openM2:r,closeM2:i}=PT(),a=l_(),{workspaces:o,isLoading:s}=hL(t.activeSection===`workspaces`),{showToast:c}=Vr(),l=gl(),[u,d]=(0,Q.useState)(new Set),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(new Map),_=(0,Q.useRef)(new Map),[v,y]=(0,Q.useState)(null),b=v&&v.base===o?v.order:o,{rowProps:x,handleProps:S,draggingIndex:C,insertLineClass:w}=ZT((e,t)=>{let n=YT(b,e,t);y({base:o,order:n}),XT(n,(e,t)=>Eo(Kw(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&c({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),E=e=>h.get(Kw(e))??{icon:e.icon??void 0,color:e.color??void 0},D=(e,t,n)=>{let r={...t,...n};g(t=>new Map(t).set(e,r));let i=_.current,a=i.get(e);a&&clearTimeout(a),i.set(e,setTimeout(()=>{i.delete(e);let t={icon:r.icon??null};r.color&&(t.color=r.color),Eo(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>c({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},O=e=>{n(Kw(e)),r(`detail`,Kw(e)),!a&&sT(Kw(e))&&l(cT(Kw(e)))},k=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(Kw(t)));try{await so(Kw(t)),c({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(Kw(t)),n})}},A=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(Kw(t)));try{await ha(Kw(t)),c({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(Kw(t)),n})}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(XI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`})]}),!e.local&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{i(),l(`/workspaces?create=1`)},title:`Create workspace`,"aria-label":`Create workspace`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,$.jsx)(`div`,{className:`space-y-1.5 px-2`,children:b.map((e,i)=>{let o=t.selectedEntityId===Kw(e),s=Op(e),c=u.has(Kw(e)),d=e.status!==`active`,p=E(e),h=Nm(p.color);return(0,$.jsxs)(`div`,{...x(i),"data-active":o||void 0,className:J(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,o?`bg-accent shadow cursor-pointer hover:shadow`:d?`bg-card opacity-60 cursor-not-allowed`:`bg-card hover:bg-accent/50 cursor-pointer hover:shadow`,w(i,b.length),C===i&&`opacity-60`),onClick:()=>{d||O(e)},children:[(0,$.jsx)(`button`,{type:`button`,...S(i),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:J(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!h&&`bg-muted`),style:h?{backgroundColor:h}:void 0,children:(0,$.jsx)(T,{className:J(`h-3.5 w-3.5`,Pm(h))})}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:s?`Change icon`:`Workspace appearance requires admin access`,onClick:t=>{!s||br()||(t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Kw(e)}))},onContextMenu:t=>{s&&(t.preventDefault(),t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Kw(e)}))},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,$.jsx)(f,{icon:p.icon||`ph:stack-fill`,width:18,height:18,color:h,className:J(!h&&`text-muted-foreground`)})}),(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(gL,{status:e.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,$.jsx)(`button`,{type:`button`,disabled:c,onClick:t=>A(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,$.jsx)(zn,{className:`w-3.5 h-3.5`})}):(0,$.jsx)(`button`,{type:`button`,disabled:c,onClick:t=>k(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,$.jsx)(xe,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(Kw(e)),a?r(`settings`,Kw(e)):l(`/workspaces/${Kw(e)}/settings/general`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,disabled:!s,title:s?`Settings`:`Workspace settings require admin access`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),p&&(()=>{let e=o.find(e=>Kw(e)===p.name);if(!e)return null;let t=E(e);return(0,$.jsx)(Zw,{x:p.x,y:p.y,current:t,onChange:e=>D(p.name,t,e),onClose:()=>m(null)})})()]})}function vL(e,t){let n=(0,Q.useRef)(null),r=(0,Q.useRef)(0);return(0,Q.useEffect)(()=>{if(!e)return;let n=e=>{if(e.defaultPrevented||e.repeat||e.isComposing||e.getModifierState(`AltGraph`))return;let n=e.target;if(n instanceof Element&&n.closest(`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="dialog"], [role="alertdialog"]`)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let r=rj(e);if(!r)return;let i=tj(),a=r===i.previousTree?-1:+(r===i.nextTree);a&&(e.preventDefault(),t(a))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),{onTouchStart(e){r.current=0,n.current=e.touches.length===1?{x:e.touches[0].clientX,y:e.touches[0].clientY}:null},onTouchMove(e){e.touches.length!==1&&(n.current=null)},onTouchCancel(){n.current=null},onTouchEnd(i){if(!n.current||!e)return;let a=i.changedTouches[0],o=aj(a.clientX-n.current.x,a.clientY-n.current.y);n.current=null,o&&(r.current=Date.now()+500,i.stopPropagation(),t(o))},onClickCapture(e){Date.now()<r.current&&(e.preventDefault(),e.stopPropagation(),r.current=0)}}}function yL(e,t,n,r=!1){if(!t.startsWith(`/`)||!n.length)throw Error(`Choose a source folder and at least one destination.`);let i=new Map;for(let e of n){if(![`context`,`directory`].includes(e.tree)||!e.path.startsWith(`/`))throw Error(`Choose a context or directory destination.`);if(e.path.includes(`{{`))throw Error(`Auto-Link destinations cannot contain {{ template markers.`);i.set(`${e.tree}:${e.path}`,e)}return{id:e,enabled:!0,description:`Auto-Link backends:${t} → ${[...i.keys()].join(`, `)}`,cascade:!0,when:{event:[`document.inserted`,`document.updated`,`document.linked`],...r?{path:`backends:${t}`}:{pathExact:`backends:${t}`}},then:[...i.values()].map(e=>({action:`link`,paths:[`${e.tree===`context`?`ctx`:`dir`}:${e.path}`],...r?{recursive:!0}:{}}))}}function bL(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=yL(e,t,n,r);if(i===`forward`)return[c];if(a===`move`&&!s?.trim())throw Error(`Choose the source backend whose copy should be moved.`);if(r&&n.some(e=>e.tree===`context`))throw Error(`Recursive storage requires a directory source. Context paths can store files in a fixed backend folder.`);let l=t.split(`/`).filter(Boolean);if(l.length<2||t.includes(`{{`)||l.some(e=>e===`.`||e===`..`))throw Error(`Choose a backend folder with a valid storage address.`);if(!o)throw Error(`Choose a writable backend folder.`);let u=o.address,d=o.key,f=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],p={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${f.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:f.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:u,folder:d,mode:a,...a===`move`?{from:s.trim()}:{},autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[c,p]:[p]}function xL(e,t){let n=as(e,t);if(t.find(e=>e.driver===n.driver&&e.address===n.address)?.capabilities.paths!==!0)throw Error(`This backend has not reported support for folder paths. Choose a writable storage folder to copy or move files here.`);return n}function SL({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(`forward`),u=c===`forward`||!i.some(e=>e.tree===`context`),[d,f]=(0,Q.useState)(`copy`),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)(!0),[y,b]=(0,Q.useState)(0),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(!0),[T]=(0,Q.useState)(()=>`autolink-${crypto.randomUUID()}`),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(0),[I,L]=(0,Q.useState)(0),[R,z]=(0,Q.useState)(0),[ee]=(0,Q.useState)(pp),[te,ne]=(0,Q.useState)(1),[B,re]=(0,Q.useState)(0),[ie,ae]=(0,Q.useState)(),[oe,V]=(0,Q.useState)(0),H=()=>{O||n()},U=_?`Checking whether this backend can receive files…`:``;if(!_)try{xL(t,h)}catch(e){U=e instanceof Error?e.message:`Choose a writable storage folder.`}let se=e=>{l(e),e!==`forward`&&(w(!1),i.some(e=>e.tree===`context`)&&S(!1))},W=e=>`${e.replace(/\/+$/,``)}/${x?`Subfolder/`:``}example.pdf`;return(0,Q.useEffect)(()=>{let t=!1;return pa(e).then(e=>{t||g(e)}).catch(()=>{t||N(`Could not load storage backends. Reopen Autolink to retry.`)}).finally(()=>{t||v(!1)}),()=>{t=!0}},[e]),(0,$.jsx)(Lp,{label:o?`Choose virtual paths`:`Autolink documents`,onClose:o?()=>s(!1):H,children:o?(0,$.jsx)(ih,{fixedWorkspaceName:e,tabs:c!==`forward`&&x?[`directory`]:[`context`,`directory`],initialTab:c===`forward`?void 0:`directory`,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-full rounded-none border-0 shadow-none`,onClose:()=>s(!1),onConfirm:(e,t)=>{c!==`forward`&&t.treeType===`context`&&S(!1),a(n=>{let r=[...n];for(let n of e)r.some(e=>e.tree===t.treeType&&e.path===n)||r.push({tree:t.treeType,path:n});return r}),s(!1)}}):(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b p-5`,children:[(0,$.jsxs)(`h2`,{className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,$.jsx)(Zt,{className:`h-5 w-5`}),`Autolink documents`]}),(0,$.jsx)(`button`,{type:`button`,onClick:H,disabled:O,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-5`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current backend folder`}),(0,$.jsxs)(`p`,{className:`mt-1 break-words text-sm`,children:[`backends:`,t]})]}),(0,$.jsxs)(`fieldset`,{disabled:O||E,className:`space-y-2 text-sm`,children:[(0,$.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,$.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>se(e.target.value),children:[(0,$.jsx)(`option`,{value:`forward`,children:`Backend → virtual folders (link)`}),(0,$.jsx)(`option`,{value:`reverse`,disabled:!!U,children:`Virtual folders → backend (Copy/Move)`}),(0,$.jsx)(`option`,{value:`both`,disabled:!!U,children:`Both directions`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link documents from this backend folder into the selected virtual folders. Files stay where they are.`:`When a document is added or explicitly linked to a selected virtual folder, ${d} its file to the current backend folder.${c===`both`?` Documents arriving on the backend are also linked into the virtual folders.`:``}`}),U&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:_?U:`Reverse mapping unavailable: ${U}`}),c!==`forward`&&(0,$.jsxs)(`div`,{className:`space-y-2 rounded-lg border p-3`,children:[(0,$.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-operation`,children:`File operation`}),(0,$.jsxs)(`select`,{id:`autolink-operation`,className:`w-full rounded-md border bg-background p-2`,value:d,onChange:e=>f(e.target.value),children:[(0,$.jsx)(`option`,{value:`copy`,children:`Copy files to this backend`}),(0,$.jsx)(`option`,{value:`move`,children:`Move files to this backend`})]}),d===`copy`&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Keep the source file and its virtual-folder links.`}),d===`move`&&(0,$.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,$.jsx)(`label`,{className:`block`,htmlFor:`autolink-source-backend`,children:`Move files from`}),(0,$.jsxs)(`select`,{id:`autolink-source-backend`,className:`w-full rounded-md border bg-background p-2`,value:p,onChange:e=>m(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:`Choose a source backend…`}),h.filter(e=>e.kind===`storage`&&e.enabled&&e.config?.readOnly!==!0).map(e=>(0,$.jsx)(`option`,{value:e.address,children:e.address},e.address))]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Move the file from this source backend after it has been stored at the destination. Virtual-folder links stay in place. Files missing from this source are skipped; multiple source copies require Copy instead.`})]})]})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`h3`,{className:`text-sm font-medium`,children:c===`reverse`?`Watch virtual folders`:`Virtual folders`}),i.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,$.jsx)(`p`,{className:`break-words`,children:e.path})]}),!E&&(0,$.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:O,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(G,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),!E&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,disabled:O,onClick:()=>s(!0),children:[(0,$.jsx)(sn,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Choose the virtual folders where backend documents should appear.`:`Choose a Directory tree folder to watch for newly added documents. Its files will be stored in the current backend folder.`})]}),(0,$.jsxs)(`fieldset`,{disabled:O||E,className:`space-y-3 text-sm`,children:[(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:x,disabled:!u,onChange:e=>S(e.target.checked),className:`mt-1`}),`Include subfolders and recreate their path in the destination`]}),!u&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Context membership has no single folder path. To preserve subfolders on a backend, choose a directory source. Context paths store files directly in the selected backend folder.`}),(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),!!i.length&&(0,$.jsxs)(`div`,{className:`space-y-3 rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`Mapping preview`,children:[(0,$.jsx)(`h3`,{className:`font-medium`,children:`Example result`}),i.map(e=>(0,$.jsxs)(`div`,{className:`space-y-2 break-all text-xs`,children:[c!==`reverse`&&(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Link `}),`backends:`,W(t),(0,$.jsx)(`br`,{}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Into `}),e.tree===`context`?`ctx`:`dir`,`:`,W(e.path)]}),c!==`forward`&&(0,$.jsxs)(`p`,{children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground`,children:[d===`move`?`Move`:`Copy`,` `]}),e.tree===`context`?`ctx`:`dir`,`:`,W(e.path),(0,$.jsx)(`br`,{}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`To `}),`backends:`,W(t)]})]},`preview:${e.tree}:${e.path}`)),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:x?`The selected folders are the roots. Only the subfolder path beneath each root is recreated at its destination.`:`Only direct folder contents are included.`})]}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[C?`Existing matching documents are processed when you enable this rule.`:c===`forward`?`Future backend arrivals and updates are linked automatically.`:`Newly added or explicitly linked virtual-folder documents are processed automatically.`,` `,c===`both`&&`Both directions creates two rules in workspace Rules. `,`Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`]}),O&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:E?`${te>1?`Rule ${Math.min(y+1,te)}/${te}: `:``}Processing ${B}${ie===void 0?``:`/${ie}`} existing documents… ${I} matches applied.`:`Saving Auto-Link…`}),A&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Auto-Link is enabled for future documents.`,C?` ${oe} document${te>1?` checks across ${te} rules`:`s checked`}. ${I} matches applied.`:``]}),R>0&&(0,$.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[R,` document operations failed. Check the rule’s run log in Rules and rerun it after resolving the errors.`]}),M&&(0,$.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[E?`Auto-Link is enabled. `:``,M]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,$.jsx)(Z,{variant:`ghost`,disabled:O,onClick:r,children:`Manage rules`}),A?(0,$.jsx)(Z,{onClick:n,children:`Done`}):(0,$.jsx)(Z,{disabled:O||!i.length||c!==`forward`&&(!!U||d===`move`&&!p),onClick:async()=>{if(!O){k(!0),N(``);try{let n=c===`forward`?void 0:xL(t,await pa(e)),r=bL(T,t,i,x,c,d,n,p);if(ne(r.length),E||(await Sp(e,r),D(!0)),C){for(let t=y;t<r.length;t++){let n=t===y?P:0;re(n),ae(void 0);let i=await gp(e,{ruleId:r[t].id,limit:1,offset:n,dryRun:!0});for(ae(i.total);n!==null;){let i=await gp(e,{ruleId:r[t].id,limit:ee,offset:n});if(L(e=>e+i.matched-i.failed),z(e=>e+i.failed),re(n+i.processed),V(e=>e+i.processed),ae(i.total),i.nextOffset===void 0)throw Error(`The rule is enabled, but applying the full folder needs an updated server. Use Rules to rerun existing documents after updating.`);n=i.nextOffset,n!==null&&F(n)}b(t+1),F(0)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}j(!0)}catch(e){N(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{k(!1)}}},children:O?`Applying…`:E?`Retry existing documents`:`Enable Autolink`})]})]})})}async function CL(){return await X.get(`${Lr}/users/me/config/webui`)??{}}async function wL(e){return await X.put(`${Lr}/users/me/config/webui`,e)??e}var TL=`application/x-canvas-workspace-pin`;function EL({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:i,onShowInTree:a,onUnpin:o,onMove:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),p=n.toLowerCase().trim(),m=p?e.filter(e=>(e.label||e.name||``).toLowerCase().includes(p)||e.path.toLowerCase().includes(p)||(e.description||``).toLowerCase().includes(p)):e,h=()=>{l(null),d(null)},g=async()=>{let t=u,n=c;if(h(),!n||!t||t.id===n)return;let r=t.id;if(t.id&&!t.before&&(r=e[e.findIndex(e=>e.id===t.id)+1]?.id??null),r!==n)try{await s(n,r)}catch(e){alert(e instanceof Error?e.message:String(e))}};return t&&!e.length?(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,$.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{c&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),c&&!u&&d({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=Nm(e.color),s=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===ei(e.tree,e.path),_=u?.id===e.id&&u.before,v=u?.id===e.id&&!u.before;return(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(TL,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,l(e.id)},onDragEnd:h,onDragOver:t=>{if(!c||c===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;d(t=>t?.id===e.id&&t.before===r?t:{id:e.id,before:r})},onDrop:e=>{e.preventDefault(),e.stopPropagation(),g()},onClick:()=>{t||i(e)},onKeyDown:n=>{n.target===n.currentTarget&&(n.key===`Enter`||n.key===` `)&&!t&&(n.preventDefault(),i(e))},title:t?`${e.path} — folder no longer exists`:`Open ${e.tree}:${e.path}`,className:J(`group relative flex items-stretch gap-2.5 rounded-(--card-radius) border bg-card shadow-elevation-1 text-left transition-colors`,t?`opacity-70 cursor-default`:`cursor-pointer hover:bg-accent/40`,m&&`ring-1 ring-primary/60`,c===e.id&&`opacity-40`,_&&`border-t-2 border-t-primary`,v&&`border-b-2 border-b-primary`),style:{borderLeft:`5px solid ${n??`transparent`}`},children:[(0,$.jsx)(`div`,{className:`flex items-center justify-center w-12 shrink-0 rounded-l-[5px] my-0 self-stretch`,style:n?{backgroundColor:`${n}22`}:void 0,children:t?(0,$.jsx)(W,{className:`w-5 h-5 text-warning`}):(0,$.jsx)(f,{icon:s,width:22,height:22,color:n,className:J(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,$.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,$.jsx)(Vn,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,$.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,$.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,$.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:t=>{t.stopPropagation(),a(e)},title:`Show in tree`,"aria-label":`Show in tree`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover focus-visible:opacity-100 hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-default`,children:(0,$.jsx)(ne,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await o(e)}catch(e){alert(e instanceof Error?e.message:String(e))}},title:`Unpin`,"aria-label":`Unpin`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,$.jsx)(ee,{className:`w-3.5 h-3.5`})})]}),!p&&(0,$.jsx)(T,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,$.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,$.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,$.jsx)(`p`,{children:`No pinned folders yet.`}),(0,$.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,$.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var DL=[`pins`,`context`,`layers`,`directory`,`backends`],OL=e=>typeof e==`string`&&DL.includes(e),kL=e=>{let t=Array.isArray(e)?e.filter(OL).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...DL.filter(e=>!t.includes(e))]},AL={pins:(0,$.jsx)(Oe,{className:`w-3.5 h-3.5`}),context:(0,$.jsx)(ae,{className:`w-3.5 h-3.5`}),layers:(0,$.jsx)(ur,{className:`w-3.5 h-3.5`}),directory:(0,$.jsx)(ne,{className:`w-3.5 h-3.5`}),backends:(0,$.jsx)(er,{className:`w-3.5 h-3.5`})},jL={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},ML=e=>e===`directory`||e===`backends`?e:lo,NL=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function PL(){let{state:e}=PT();return e.selectedEntityId?(0,$.jsx)(pE,{workspaceName:e.selectedEntityId,children:(0,$.jsx)(FL,{},e.selectedEntityId)}):null}function FL(){let{state:e,closeM2:t,openM2:n,navigateFromMenu:r}=PT(),i=gy(),a=l_(),o=e.selectedEntityId,s=gl(),c=pl(),{treeName:l,path:u}=Px(c.pathname),d=new URLSearchParams(c.search).get(`layer`)===`1`,f=new URLSearchParams(c.search).get(`layerId`),p=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!f,m=p?NL(l,f):DL[0],[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)({icon:null,color:null}),[C,w]=(0,Q.useState)(m),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)([]),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),[z,ee]=(0,Q.useState)(!1),[te,ne]=(0,Q.useState)(u),[B,re]=(0,Q.useState)([]),[ie,ae]=(0,Q.useState)(new Set),[oe,V]=(0,Q.useState)(d&&u!==`/`?u:null),[H,U]=(0,Q.useState)(``),[se,W]=(0,Q.useState)(null),[ce,le]=(0,Q.useState)(null),[ue,de]=(0,Q.useState)(null),{policies:fe,refresh:pe}=hF(o),me=(0,Q.useCallback)(e=>{if(C!==`context`&&C!==`directory`||!fe.length)return null;let t=tF(fe,C,e);return t.length?`Storage policy targets: ${nF(t)} (see Settings for transfer status)`:null},[C,fe]),[G,he]=(0,Q.useState)([]),[ge,_e]=(0,Q.useState)(!1),[ve,K]=(0,Q.useState)(!1),q=(0,Q.useRef)(null),ye=(0,Q.useRef)(!1),[be,xe]=(0,Q.useState)(!1),[Se,Ce]=(0,Q.useState)(DL),we=!p;(0,Q.useEffect)(()=>{let e=!1;return CL().then(t=>{if(e)return;let n=kL(t?.m2?.tabOrder);Ce(n),we&&w(e=>e===DL[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Te=(0,Q.useCallback)(async e=>{let t=Se;Ce(e);try{let t=await CL();await wL({...t,m2:{...t.m2,tabOrder:e}})}catch{Ce(t)}},[Se]),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)(null),Ae=()=>{De(null),ke(null)},je=()=>{if(Ee&&Oe&&Ee!==Oe.id){let e=Se.filter(e=>e!==Ee),t=e.indexOf(Oe.id);t>=0&&(e.splice(Oe.before?t:t+1,0,Ee),e.some((e,t)=>e!==Se[t])&&Te(e))}Ae()};(0,Q.useEffect)(()=>{let e=e=>W(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[Me,Ne]=(0,Q.useState)(u);u!==Me&&(Ne(u),ne(u));let Pe=(0,Q.useRef)(new Map),Fe=(0,Q.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();Pe.current.set(t,i);let a=()=>Pe.current.get(t)===i,o=t===`context`?P:t===`directory`?I:R,s=t===`context`?E:t===`directory`?O:A;n||o(!0);try{n&&!r&&Da(e,t);let i=await vi(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ie=(0,Q.useCallback)(async(e,t=!1)=>{let n=Symbol();Pe.current.set(`pins`,n);let r=()=>Pe.current.get(`pins`)===n;t||_e(!0);try{let t=await Ai(e);r()&&he(t)}catch{}finally{r()&&_e(!1)}},[]),Le=(0,Q.useCallback)(async(e,t=!1)=>{let n=Symbol();Pe.current.set(`layers`,n);let r=()=>Pe.current.get(`layers`)===n;t||ee(!0);try{let t=await oi(e,`context`);r()&&M(t)}catch{}finally{r()&&ee(!1)}},[]);(0,Q.useEffect)(()=>{if(!o)return;let e=o,t=!1,n=Pe.current;async function r(){qr(e).then(e=>{t||(v(e.label||e.name),g(Op(e)),b(e.id||null),S({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Fe(e,`context`),Fe(e,`directory`),Fe(e,`backends`),Le(e),Ie(e)])}return r(),()=>{t=!0,n.clear()}},[o,Fe,Le,Ie]);let Re=(0,Q.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Fe(e,r,!0,n);(!t||t===`context`)&&Le(e,!0),Ie(e,!0)},[Fe,Le,Ie]),ze=(0,Q.useCallback)(()=>{o&&Re(o)},[o,Re]);(0,Q.useEffect)(()=>{if(!o)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==o||Re(o,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[o,Re]),(0,Q.useEffect)(()=>{if(!o)return;let e=!1,t=()=>pa(o).then(t=>{e||(re(t),ae(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath))))}).catch(()=>{});t();let n=e=>{let n=e.detail;n?.workspaceName&&n.workspaceName!==o||(!n?.treeName||n.treeName===`backends`)&&t()};return window.addEventListener(`workspace:tree:refresh`,n),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,n)}},[o]),(0,Q.useEffect)(()=>{if(!o)return;let e=[`workspace:${o}`,y?`workspace:${y}`:null].filter(Boolean),t=()=>e.forEach(e=>hd.emit(`subscribe`,{channel:e})),n=hd.on(`connect`,t);t();let r=Ab(o,y),i=e=>{if(e?.workspaceId&&y&&e.workspaceId!==y)return;let t=e?.treePath;t&&ae(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};hd.on(`backend.resync.changed`,i);let a=e=>{e?.workspaceId&&y&&e.workspaceId!==y||Ie(o,!0)};return hd.on(`pins.changed`,a),()=>{r(),n?.(),hd.off(`backend.resync.changed`,i),hd.off(`pins.changed`,a)}},[o,y,Ie]);let[Be,Ve]=(0,Q.useState)(null),He=`${c.pathname}|${c.search}`;if(He!==Be){Ve(He);let{treeName:e,path:t}=Px(c.pathname),n=new URLSearchParams(c.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!n;ve?K(!1):w(r||be?r?NL(e,n):C:Se[0]),ne(t),V(t===`/`?null:t)}let{showProgress:Ue}=Vr(),We=jb({workspaceId:o??void 0,treeName:ML(C),onRefresh:ze}),Ge=new Set(G.map(e=>ei(e.tree,e.path))),Ke=ML(C),qe=(0,Q.useCallback)(e=>Ge.has(ei(Ke,e)),[G,Ke]),Je=(0,Q.useCallback)(async e=>{if(!o)return;let t=G.find(t=>ei(t.tree,t.path)===ei(Ke,e));t?await oa(o,t.id):await Yi(o,e,Ke),await Ie(o)},[o,G,Ke,Ie]),Ye=(0,Q.useCallback)(async e=>{if(o){he(t=>t.filter(t=>t.id!==e.id));try{await oa(o,e.id)}finally{await Ie(o)}}},[o,Ie]),Xe=(0,Q.useCallback)(async(e,t)=>{if(!o)return;let n=G.find(t=>t.id===e);if(!n)return;let r=G.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let a=[...r.slice(0,i),n,...r.slice(i)];if(!a.every((e,t)=>e===G[t])){he(a);try{he(await Fi(o,a.map(e=>e.id)))}catch(e){throw await Ie(o),e}}},[o,G,Ie]),Ze=(0,Q.useCallback)(e=>{if(!o)return;K(!0),ne(e.path),V(null);let t=Fx(o,e.path,e.tree);if(i){i.activateRow(`pin:${o}:${e.id}`,e.label||e.name||e.path,t);return}r(t)},[o,r,i]),Qe=(0,Q.useCallback)(e=>{!o||e.resolvable===!1||(K(!1),xe(!0),w(NL(e.tree)),ne(e.path),V(null),U(``),ye.current=!0,i?.setFocus(`main`),r(Fx(o,e.path,e.tree)))},[o,r,i]),$e=C===`context`?T:C===`directory`?D:C===`backends`?k:null,et=C===`context`?N:C===`directory`?F:C===`backends`&&L;(0,Q.useEffect)(()=>{if(!ye.current||et||C===`pins`)return;let e=q.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),ye.current=!1)},[C,te,$e,et]);let tt=(0,Q.useCallback)(e=>{xe(!0),w(e),ne(`/`),V(null),U(``)},[]),nt=(0,Q.useCallback)(e=>{tt(ij(Se,C,e))},[Se,C,tt]),rt=vL(e.m2Open,nt),it=e=>{V(null),ne(e);let t=ML(C);i?.setFocus(`main`),r(Fx(o,e,t))},at=(0,Q.useCallback)((e,t)=>{ne(e),V(e);let n=ML(C),a=new URLSearchParams;a.set(`layer`,`1`),t&&a.set(`layerId`,t),i?.setFocus(`main`),r(`${Fx(o,e,n)}?${a.toString()}`)},[o,C,r,i]),ot=(0,Q.useCallback)((e,t)=>{if(o){if(i){i.openCanvas({kind:`route`,location:Fx(o,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:t,path:e}}))}},[o,i]),st=(0,Q.useCallback)(async e=>{if(!o)return;let t=ML(C),n=await To(o,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[o,C]),ct=H.toLowerCase().trim(),lt=ct?j.filter(e=>e.name.toLowerCase().includes(ct)||(e.label||``).toLowerCase().includes(ct)||(e.description||``).toLowerCase().includes(ct)):j;return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(QI,{title:_||o||`Workspace`,icon:x.icon||`ph:stack-fill`,accentColor:x.color,onBack:t,action:(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>o&&r(cT(o)),className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Open workspace`,children:(0,$.jsx)(Ht,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,disabled:!h,onClick:()=>{a?n(`settings`,o??null):s(`/workspaces/${o}/settings/general`)},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,title:h?`Settings`:`Workspace settings require admin access`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})}),(0,$.jsx)(`div`,{...rt,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:Se.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>tt(e),title:`${jL[e]} — drag to reorder; the first tab opens by default`,"aria-label":jL[e],"aria-pressed":C===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,De(e)},onDragEnd:Ae,onDragOver:t=>{if(!Ee||Ee===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;ke(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),je()},className:J(`relative flex-1 flex items-center justify-center py-2 transition-colors`,C===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,Ee===e&&`opacity-40`,Oe?.id===e&&Oe.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Oe?.id===e&&!Oe.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[AL[e],e===`pins`&&G.length>0&&(0,$.jsx)(`span`,{className:`absolute top-1 right-[calc(50%-14px)] min-w-[14px] h-[14px] px-0.5 rounded-full bg-primary text-primary-foreground text-[9px] leading-[14px] text-center font-medium`,children:G.length})]},e))}),(0,$.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,$.jsx)(tr,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,$.jsx)(`input`,{type:`search`,name:`workspace-tree-filter`,"aria-label":`Search workspace tree`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:C===`layers`?`Search layers…`:C===`pins`?`Search pins…`:`Search paths…`,value:H,onChange:e=>U(e.target.value)})]})}),(0,$.jsx)(`div`,{ref:q,className:`flex-1 overflow-y-auto`,children:C===`pins`?(0,$.jsx)(EL,{pins:G,isLoading:ge,searchQuery:H,activeKey:ei(l,u),onOpen:Ze,onShowInTree:Qe,onUnpin:Ye,onMove:Xe}):C===`layers`?(0,$.jsx)(HL,{layers:lt,isLoading:z,wsName:o??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),r(`${Fx(o,`/`)}?${t.toString()}`)},onLock:async e=>{await ci(o,e.id,o,`context`),Re(o)},onUnlock:async e=>{await Ea(o,e.id,o,`context`),Re(o)},onRename:async(e,t)=>{await ia(o,e.id,t,`context`),Re(o)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await Jr(o,e.id,`context`),Re(o))}}):(0,$.jsx)(dL,{root:$e,workspaceId:o??void 0,treeName:C,isBackendsTree:C===`backends`,onRestoreTrash:o?e=>xb(o,e):void 0,onDiscardTrash:o?e=>Cb(o,e):void 0,onShiftSelect:i?e=>ot(e,ML(C)):void 0,selectedPath:te,contentPath:oe,onSelect:it,onShowContent:C===`context`?at:void 0,onOpenToSide:ot,onShareCanvas:st,onNewCanvas:o&&C!==`backends`?e=>{s(`${Fx(o,e,C)}?createCanvas=1`)}:void 0,isLoading:et,rootLabel:o??void 0,searchQuery:H,backends:B,resyncingPaths:C===`backends`?ie:void 0,onAddRule:o&&C===`backends`?le:void 0,onAddStoreRule:o?(e,t=`store`)=>{let n=C===`backends`?(()=>{let n=ep(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${C===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:np(e)};s(`/workspaces/${o}/settings/hooks?${tp(n).toString()}`)}:void 0,onStoragePolicy:o&&(C===`context`||C===`directory`)?e=>de(KP(C,e)):void 0,policyBadgeFor:me,pastedDocumentIds:se?.documentIds,isPathPinned:qe,onTogglePin:o?Je:void 0,onPasteDocuments:o&&C===`backends`?async(e,t)=>{let n=ho(e);if(!n)return!1;let r=e.split(`/`).filter(Boolean).slice(2).join(`/`),i=Ue({title:`Moving…`,description:`${t.length} message(s) → ${r}`});try{let{moved:a,results:s}=await Li(o,n.address,t,e),c=s.filter(e=>!e.ok);return c.length?i.fail({title:`${c.length} message(s) not moved`,description:c[0].error||`Move failed`,variant:`destructive`}):i.done({title:`Moved`,description:`${a} message(s) → ${r}`}),se&&a&&(W(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:`/imap/${n.address}`,treeName:`backends`}})),a>0}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to move messages`,variant:`destructive`}),!1}}:o?async(e,t)=>{let n=C===`directory`?`directory`:`context`,r=C===`directory`?`directory`:lo,i=Ue({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await Qr(o,e,t,r,n)}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(se&&(W(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:e,treeName:r}}))),a}:void 0,...We})}),ce&&o&&(0,$.jsx)(SL,{workspaceId:o,sourcePath:ce,onClose:()=>le(null),onManageRules:()=>{le(null),s(`/workspaces/${o}/settings/hooks?section=rules`)}}),ue&&o&&(0,$.jsx)(oF,{workspaceId:o,path:ue,onClose:()=>de(null),onSaved:()=>{pe()}})]})}var IL={canvas:{label:`Canvases`,order:0},dataset:{label:`Datasets`,order:1},context:{label:`Context layers`,order:2},workspace:{label:`Workspaces`,order:3},universe:{label:`Universe`,order:4},label:{label:`Labels`,order:5},system:{label:`System`,order:6}},LL=100,RL=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),zL=e=>IL[e]??{label:`${RL(e)} layers`,order:LL};function BL({type:e}){return e===`canvas`?(0,$.jsx)(gt,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,$.jsx)(er,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,$.jsx)(ur,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function VL(e){let t=new Map;for(let n of e){let e=n.type||`context`,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({type:e,items:t,meta:zL(e)})).sort((e,t)=>e.meta.order-t.meta.order||e.meta.label.localeCompare(t.meta.label)).map(({type:e,items:t,meta:n})=>({type:e,label:n.label,items:t}))}function HL({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(null);if((0,Q.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No layers found`});let u=async(e,t)=>{e.stopPropagation();try{await t()}catch(e){alert(e instanceof Error?e.message:String(e))}},d=async(e,t)=>{c(null);let n=t.trim();if(!(!n||n===e.name))try{await a(e,n)}catch(e){alert(e instanceof Error?e.message:String(e))}},f=VL(e);return(0,$.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,$.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,$.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-l-md px-2 py-1.5 text-xs bg-card shadow-elevation-1 cursor-pointer hover:bg-accent/40 transition-colors`,style:{borderRight:e.color?`4px solid ${e.color}`:`4px solid transparent`},onClick:()=>s!==e.id&&n(e),children:[(0,$.jsx)(`div`,{className:J(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,$.jsx)(BL,{type:e.type}),s===e.id?(0,$.jsx)(`input`,{ref:l,defaultValue:e.label||e.name,className:`flex-1 bg-transparent outline-none min-w-0 font-medium border-b border-primary`,onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&d(e,t.target.value),t.key===`Escape`&&c(null)},onBlur:t=>d(e,t.target.value)}):(0,$.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,$.jsx)(Vn,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,$.jsx)(`button`,{type:`button`,title:`Unlock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-warning hover:text-foreground touch-target`,onClick:t=>u(t,()=>i(e)),children:(0,$.jsx)(Ot,{className:`w-3 h-3`})}):(0,$.jsx)(`button`,{type:`button`,title:`Lock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>u(t,()=>r(e)),children:(0,$.jsx)(Vn,{className:`w-3 h-3`})}),!e.locked&&(0,$.jsx)(`button`,{type:`button`,title:`Rename layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>{t.stopPropagation(),c(e.id)},children:(0,$.jsx)(Ie,{className:`w-3 h-3`})}),!e.locked&&(0,$.jsx)(`button`,{type:`button`,title:`Destroy layer`,className:`p-0.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,onClick:t=>u(t,()=>o(e)),children:(0,$.jsx)(nt,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function UL(){let{state:e,closeM2:t}=PT(),n=l_(),r=gl(),i=pl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null),c=o?.address===a?o.workspace:null,l=c?.label||c?.name,u=Op(c);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return qr(a).then(t=>{e||s({address:a,workspace:t})}).catch(()=>{}),()=>{e=!0}},[a]);let d=i.pathname.split(`/`).filter(Boolean),f=d[2]===`settings`?BO(d[3]):null,p=(0,Q.useMemo)(()=>RO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:`Settings: ${l||a||`Workspace`}`,icon:c?.icon||`ph:stack-fill`,accentColor:c?.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>a&&r(`/workspaces/${a}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open workspace`,children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),u?(0,$.jsx)(pL,{items:p,activeId:f,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)}):(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:c?`Workspace settings are available to owners and admins.`:`Loading workspace…`})]})}function WL(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ok();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>hd.emit(`subscribe`,{channel:`agent`}),r=()=>hd.emit(`unsubscribe`,{channel:`agent`}),i=hd.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e?.agent??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},o=e=>{let t=e?.agent??e;t?.id&&n(e=>e.map(e=>e.id===t.id?{...e,...t}:e))},c=e=>{let t=e,r=t?.agentId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=e=>{let t=e,r=t?.agentId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},u=[[`agent:created`,a],[`agent.created`,a],[`agent:updated`,o],[`agent.updated`,o],[`agent:deleted`,c],[`agent.deleted`,c],[`agent:status:changed`,l],[`agent.status.changed`,l]];return u.forEach(([e,t])=>hd.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>hd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`agents:refresh`,e),()=>window.removeEventListener(`agents:refresh`,e)},[s]),{agents:t,isLoading:r,refresh:c}}function GL({status:e}){return(0,$.jsx)(`span`,{className:J(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function KL(){let e=Gw(),{state:t,selectEntity:n,openM2:r,closeM2:i}=PT(),a=l_(),{agents:o,isLoading:s,refresh:c}=WL(t.activeSection===`agents`),{showToast:l}=Vr(),[u,d]=(0,Q.useState)(new Set),f=gl(),p=e=>{n(e.id),r(`detail`,e.id),f(`/agents/${encodeURIComponent(e.name||e.id)}`)},m=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await bk(t.id),c(),l({title:`Success`,description:`${t.label||t.name} started`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}},h=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await xk(t.id),c(),l({title:`Success`,description:`${t.label||t.name} stopped`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(XI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})]}),!e.local&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{i(),f(`/agents?create=1`)},title:`Create agent`,"aria-label":`Create agent`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No agents found`}):(0,$.jsx)(`div`,{className:`space-y-1.5 px-2`,children:o.map(e=>{let i=t.selectedEntityId===e.id,o=u.has(e.id);return(0,$.jsxs)(`div`,{"data-active":i||void 0,className:J(`group relative rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all shadow-elevation-1 hover:shadow`,i?`bg-accent shadow`:`bg-card hover:bg-accent/50`),style:{borderRight:`6px solid ${e.color||`transparent`}`},onClick:()=>p(e),children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(GL,{status:e.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,$.jsx)(`button`,{type:`button`,disabled:o,onClick:t=>h(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,$.jsx)(zn,{className:`w-3.5 h-3.5`})}):(0,$.jsx)(`button`,{type:`button`,disabled:o,onClick:t=>m(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,$.jsx)(xe,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(e.id),a?r(`settings`,e.id):f(`/agents/${encodeURIComponent(e.name||e.id)}/settings/identity`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors`,title:`Settings`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description})]},e.id)})})})]})}function qL(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function JL(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function YL(e){return e.sessions.sessions.find(t=>t.id===e.current.sessionId||t.path===e.current.sessionFile||t.id===e.sessions.currentSessionId||t.path===e.sessions.currentSessionPath||t.isCurrent)||null}function XL(){let{state:e,closeM2:t}=PT(),n=e.selectedEntityId||``,r=gl(),{showToast:i}=Vr(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),{current:h,sessions:g,isLoading:_,error:v,refresh:y,create:b,select:x,rename:S,remove:C}=AN(n);(0,Q.useEffect)(()=>{n&&(sk(n).then(o).catch(()=>{}),y().catch(e=>{i({title:`Error`,description:e instanceof Error?e.message:`Failed to load sessions`,variant:`destructive`})}))},[n,y,i]);let w=(0,Q.useMemo)(()=>g?.sessions?g.currentSessionId?g.sessions.find(e=>e.id===g.currentSessionId)||null:g.currentSessionPath?g.sessions.find(e=>e.path===g.currentSessionPath)||null:g.sessions.find(e=>e.isCurrent)||null:null,[g]),T=a?.name||n,E=e=>e?.slug||e?.id,D=e=>{let t=typeof e==`string`?e:E(e);r(t?`/agents/${encodeURIComponent(T)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(T)}`)},O=async()=>{try{let e=await b({mode:`persistent`,name:l.trim()||void 0});c(!1),u(``),D(YL(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create session`,variant:`destructive`})}},k=async()=>{try{let e=await b({mode:`experimental`});D(YL(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open experimental session`,variant:`destructive`})}},A=async()=>{try{await b({mode:`incognito`}),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open incognito session`,variant:`destructive`})}},j=async e=>{try{e.isExperimental?await x({mode:`experimental`}):await x({mode:`persistent`,sessionId:e.id}),D(e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}},M=async e=>{if(p.trim())try{let t=(await S(e.id,p.trim())).sessions.sessions.find(t=>t.id===e.id);f(null),m(``),w?.id===e.id&&D(t||e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to rename session`,variant:`destructive`})}},N=async e=>{if(!e.isExperimental&&window.confirm(`Delete session "${qL(e)}"?`))try{await C(e.id),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete session`,variant:`destructive`})}};return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:a?.label||a?.name||n,onBack:t,action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(`/agents/${encodeURIComponent(T)}/settings`),className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Agent settings`,children:(0,$.jsx)(yn,{className:`h-3.5 w-3.5`})})}),(0,$.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,$.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,$.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:g?.mode===`incognito`?`Incognito mode`:g?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,$.jsxs)(Z,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:_,children:[(0,$.jsx)(sn,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,$.jsxs)(Z,{size:`sm`,variant:g?.mode===`experimental`?`default`:`outline`,onClick:k,disabled:_,children:[(0,$.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,$.jsx)(Z,{size:`sm`,variant:g?.mode===`incognito`?`default`:`outline`,onClick:A,disabled:_,children:`Incognito`})]})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[v&&(0,$.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:v}),s&&(0,$.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,$.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),O()),e.key===`Escape`&&(c(!1),u(``))},placeholder:`Debugging auth`,className:`h-8`}),(0,$.jsx)(Z,{size:`sm`,onClick:O,disabled:_,children:`Create`})]})]}),g?.sessions.length?(0,$.jsx)(`div`,{className:`space-y-1.5`,children:g.sessions.map(e=>{let t=w?.id===e.id&&g.mode!==`incognito`,n=d===e.id;return(0,$.jsx)(`div`,{onClick:()=>j(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),j(e))},role:`button`,tabIndex:_?-1:0,className:`group w-full rounded-md border px-3 py-2 text-left transition-colors ${t?`border-foreground bg-accent`:`border-transparent hover:bg-accent/50`} ${_?`opacity-60`:``}`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:p,onChange:e=>m(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),M(e)),t.key===`Escape`&&(f(null),m(``))},placeholder:`Session name`,className:`h-8`}),(0,$.jsx)(Z,{size:`sm`,onClick:t=>{t.stopPropagation(),M(e)},disabled:!p.trim()||_,children:`Save`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:qL(e)}),e.isExperimental&&(0,$.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,$.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,$.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:JL(e)})]})}),!n&&(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),m(e.name||qL(e))},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-muted-foreground/10 text-muted-foreground touch-target`,title:`Rename`,children:(0,$.jsx)(gr,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),N(e)},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,title:`Delete session`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-sm`,children:_?`Loading sessions...`:`No persistent sessions yet.`}),(0,$.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),h?.mode===`incognito`&&(0,$.jsx)(`div`,{className:`mt-3 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground`,children:`Incognito session is active. It lives in memory and stays out of the session list.`})]})]})}function ZL(){let{state:e,closeM2:t}=PT(),n=l_(),r=gl(),i=pl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return sk(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?WO(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,Q.useMemo)(()=>UO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>u&&r(`/agents/${u}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open agent`,children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),(0,$.jsx)(pL,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function QL(){let e=pl(),{state:t}=PT(),[n,r]=(0,Q.useState)(``),i=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{let e=i.current,t=e?.querySelector(`[aria-current="page"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();r.top<n.top?e.scrollTop+=r.top-n.top:r.bottom>n.bottom&&(e.scrollTop+=r.bottom-n.bottom)},[e.pathname,t.user?.userType]);let a=lT.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>dT(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,$.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(XI,{}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`})]}),(0,$.jsx)(Y,{type:`search`,name:`settings-menu-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings menu`,placeholder:`Find a setting…`,value:n,onChange:e=>r(e.target.value)})]}),(0,$.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,$.jsxs)(`section`,{"aria-label":t.label,children:[(0,$.jsx)(`h2`,{className:`px-3 py-2 text-xs font-semibold text-muted-foreground`,children:t.label}),t.items.map(({path:t,icon:n,label:r,description:i})=>(0,$.jsxs)(Nu,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:J(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,$.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,$.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,$.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var $L=280,eR=220,tR=560;function nR(){let{state:e}=PT(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,$.jsx)(mL,{});if(n===`detail`)return(0,$.jsx)(fL,{})}if(t===`workspaces`){if(n===`settings`)return(0,$.jsx)(UL,{});if(n===`detail`)return(0,$.jsx)(PL,{})}if(t===`agents`){if(n===`settings`)return(0,$.jsx)(ZL,{});if(n===`detail`)return(0,$.jsx)(XL,{})}return null}function rR(){let{state:e,closeM1:t,closeM2:n}=PT();Fp(t,e.m1Open&&!e.m2Open),Fp(n,e.m1Open&&e.m2Open);let r=l_(),i=(0,Q.useRef)(null),a=(0,Q.useRef)(null);JI(i,e.m1Open&&!e.m2Open,e.activeSection??``),JI(a,e.m1Open&&e.m2Open,`${e.activeSection}:${e.selectedEntityId}:${e.m2View}`);let[o,s]=(0,Q.useState)($L),[c,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),d=(0,Q.useCallback)(e=>{e.preventDefault(),l(!0),u.current={startX:e.clientX,startWidth:o};let t=e=>{if(!u.current)return;let t=e.clientX-u.current.startX,n=Math.min(tR,Math.max(eR,u.current.startWidth+t));s(n)},n=()=>{u.current=null,l(!1),window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[o]),f=r&&e.m1Open;return(0,$.jsxs)($.Fragment,{children:[f&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,$.jsxs)(`div`,{style:e.m1Open&&!f?{width:o}:void 0,className:J(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!c&&!f&&`transition-[width] duration-normal ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,f?`fixed bottom-2 left-[calc(0.5rem+var(--spacing-rail)+0.5rem)] right-2 top-2 z-40 shadow-elevation-5`:`relative`),children:[(0,$.jsxs)(`div`,{ref:i,"data-menu-view":`list`,inert:!e.m1Open||e.m2Open,className:J(`absolute inset-0 flex flex-col transition-opacity duration-normal ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:f?void 0:{minWidth:o},children:[e.activeSection===`contexts`&&(0,$.jsx)(ZI,{}),e.activeSection===`workspaces`&&(0,$.jsx)(_L,{}),e.activeSection===`agents`&&(0,$.jsx)(KL,{}),e.activeSection===`admin`&&(0,$.jsx)(QL,{}),e.activeSection===`settings`&&(0,$.jsx)(QL,{})]}),(0,$.jsx)(`div`,{ref:a,"data-menu-view":`detail`,inert:!e.m1Open||!e.m2Open,className:J(`absolute inset-0 z-10 bg-card flex flex-col md:transition-transform md:duration-normal md:ease-out`,e.m2Open?`translate-x-0`:`translate-x-full max-md:invisible`),children:e.m2Open&&(0,$.jsx)(nR,{})}),e.m1Open&&!f&&(0,$.jsx)(`div`,{onMouseDown:d,className:`absolute right-0 top-0 bottom-0 z-20 w-1 cursor-col-resize hover:bg-primary/20 transition-colors`})]})]})}var iR=`canvas:readerWidth`,aR=320,oR=1600;function sR(){try{let e=Number(sessionStorage.getItem(iR));return Number.isFinite(e)&&e>=aR&&e<=oR?e:null}catch{return null}}var cR=sR(),lR=new Set;function uR(e){return lR.add(e),()=>{lR.delete(e)}}function dR(e){cR=e===null?null:Math.round(Math.max(aR,Math.min(oR,e)));try{cR===null?sessionStorage.removeItem(iR):sessionStorage.setItem(iR,String(cR))}catch{}lR.forEach(e=>e())}function fR(){return(0,Q.useSyncExternalStore)(uR,()=>cR,()=>null)}var pR=320,mR=1600;function hR({edge:e}){let t=fR(),n=(0,Q.useRef)(null),r=e===`left`?-1:1;return(0,$.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":pR,"aria-valuemax":mR,"aria-valuenow":t??420,tabIndex:0,title:`Drag to resize; arrow keys adjust width; double-click to reset`,className:`absolute inset-y-0 ${e===`left`?`left-0`:`right-0`} z-20 hidden w-2 touch-none cursor-col-resize select-none hover:bg-primary/20 focus-visible:bg-primary/20 focus-visible:outline-none md:block`,onPointerDown:t=>{if(t.button!==0)return;t.preventDefault(),t.stopPropagation();let r=t.currentTarget.closest(`[data-reader-pane]`),i=e===`left`?(r.parentElement?.clientWidth??window.innerWidth)-248:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(pR,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&dR(Math.min(n.current.max,n.current.width+r*(e.clientX-n.current.x)))},onPointerUp:e=>{n.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{n.current=null},onLostPointerCapture:()=>{n.current=null},onDoubleClick:()=>dR(null),onKeyDown:e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`&&e.key!==`Home`)return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.closest(`[data-reader-pane]`);e.key===`Home`?dR(null):dR(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function gR(e){return e.schema===`data/schema/note`?Kn:e.schema===`data/schema/tab`?_n:e.schema===`data/schema/file`?Rn:e.schema===`data/schema/message/email`?bt:Hn}function _R({entry:e,onClose:t,frame:n}={}){let r=Eg(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=Vy(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,$.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,$.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between border-b-[3px] bg-muted pl-4 pr-2`,children:[(0,$.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,$.jsx)(`button`,{type:`button`,onClick:a,className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent`,"aria-label":`Close`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,$.jsx)(`button`,{type:`button`,className:`ml-2 underline`,onClick:r.retry,children:`Retry`})]})]}):null;let{workspaceId:c}=i,l=t=>{s(t),t&&t.id!==i.document.id&&!e&&r.replace?.(t,c)};return(0,$.jsx)(CD,{title:Yr(o).title,icon:gR(o),onClose:a,onSave:async e=>(await Qr(c,e.path,[o.id],e.treeName,e.treeType),[o.id]),canSave:!0,successMessage:`Linked`,lockedWorkspaceName:c,relationSubjectId:o.id,frame:n,fillParent:!0,fullWidthContent:yv(o)===x_,maximized:e?void 0:r.location?.maximized,onMaximizedChange:e?void 0:e=>r.update?.({maximized:e}),children:t=>(0,$.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,$.jsx)(By,{document:o,workspaceId:c,onChanged:l,compact:!0,tabActions:t,initialTab:e?void 0:r.location?.section,onTabChange:e?void 0:e=>r.update?.({section:e})},`${c}:${o.id}`)})})}function vR(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function yR(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`].includes(t)&&!!n}var bR=`max-md:fixed max-md:left-2 max-md:right-2 max-md:top-2 max-md:bottom-2 max-md:z-side max-md:py-0 max-md:mr-0 max-md:rounded-(--panel-radius) max-md:shadow-elevation-5 max-md:animate-fade-in`,xR=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function SR(){let e=fR(),{pathname:t,search:n}=pl(),{state:r}=PT(),i=(0,Q.useRef)(null);JI(i,!r.m1Open,t+n,!r.m0Open);let a=yR(t),o=vR(t),{entry:s,loading:c,error:l,close:u}=Eg();return(0,$.jsx)(`div`,{className:J(`relative flex flex-col flex-1 min-w-0`,!o&&`surface-sheet`),children:(0,$.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,$.jsx)(`main`,{ref:i,id:`content-area`,className:J(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!a&&!o&&`p-page max-md:pb-rail-stack`),children:(0,$.jsx)(Ul,{})}),(s||c||l)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:xR,onClick:u,"aria-hidden":!0}),(0,$.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??420}px`},className:J(`relative z-10 flex shrink-0 items-stretch py-2 mr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_248px)]`,bR),children:[(0,$.jsx)(hR,{edge:`left`}),(0,$.jsx)(_R,{},s?`${s.workspaceId}:${s.document.id}`:`loading`)]})]})]})})}function CR(){let{state:e,setView:t}=zs(),{pathname:n}=pl();return e.t1Open||e.addOpen||!vR(n)?null:(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(`tools`),"aria-label":`Open toolbox`,title:`Open toolbox`,className:`fixed z-50 hidden md:flex h-16 w-16 items-center justify-center rounded-full shadow-elevation-4 transition-colors bottom-fab-inset right-6 bg-foreground text-background hover:bg-foreground`,children:(0,$.jsx)(Un,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var wR={current:null,sessions:null,isLoading:!1,error:null};function TR(e){return e instanceof Error?e.message:`Session request failed`}function ER({children:e}){let[t,n]=(0,Q.useState)({}),r=(0,Q.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||wR,...t}}))},[]),i=(0,Q.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,Q.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([ck(e),lk(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}}},[r]),o=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await uk(e,t))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),s=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await dk(e,t))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),c=(0,Q.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await fk(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),l=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await pk(e,t))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),u=(0,Q.useMemo)(()=>({getState:e=>t[e]||wR,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,$.jsx)(kN.Provider,{value:u,children:e})}function DR(){let e=Ds(),{closeAdd:t}=zs(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,Q.useState)(`Untitled.txt`),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),u=!1;try{hs(``,i.trim()),u=!0}catch{}return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`plaintext-filename`,children:`Filename`}),(0,$.jsx)(Y,{id:`plaintext-filename`,autoFocus:!0,value:i,onChange:e=>a(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Content`}),(0,$.jsx)(Ho,{kind:`text`,value:o,onChange:s,placeholder:`Write plain text…`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a file in the current storage folder. Existing files are never overwritten.`}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:t,disabled:c,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(!(c||!u||e?.mode!==`workspace`||e.treeName!==`backends`)){l(!0);try{let r=await ks(e.workspaceName,e.path);await Br(e.workspaceName,{...r,key:hs(r.key,i.trim())},new Blob([o],{type:`text/plain;charset=utf-8`}),{contentType:`text/plain;charset=utf-8`}),_s(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),n(`Plaintext file created`),t()}catch(e){r(e instanceof Error?e.message:`Failed to create file`)}finally{l(!1)}}},disabled:c||!u,children:c?`Creating…`:`Create file`})]})]})}var OR=`references`;function kR(e){return e?e.documents.map(e=>({predicate:OR,direction:`out`,targetId:e.id,document:e})):[]}function AR(e,t){let[n,r]=(0,Q.useState)(()=>kR(t)),[i,a]=(0,Q.useState)([...ro]),o=e?.mode===`context`?e.contextId:null,[s,c]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!o)return;let e=!1;return Ms({mode:`context`,contextId:o}).then(t=>{e||c({contextId:o,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[o]);let l=e?.mode===`workspace`?e.workspaceName:o&&s?.contextId===o?s.workspaceName:t?.workspaceName??null;return(0,Q.useEffect)(()=>{let e=!1;if(l)return Pi(l).then(t=>{e||a(t)}),()=>{e=!0}},[l]),{rows:n,predicates:i,workspaceName:l,add:(0,Q.useCallback)(async(e,t,i)=>{let a=i.filter(r=>!n.some(n=>n.targetId===r&&n.predicate===e&&n.direction===t));if(a.length===0)return;let o=await Promise.all(a.map(e=>l?Ja(l,e).catch(()=>null):Promise.resolve(null)));r(n=>[...n,...a.map((n,r)=>({predicate:e,direction:t,targetId:n,document:o[r]??null}))])},[n,l]),update:(0,Q.useCallback)((e,t)=>{r(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),remove:(0,Q.useCallback)(e=>{r(t=>t.filter((t,n)=>n!==e))},[]),write:(0,Q.useCallback)(async e=>{if(n.length===0||e.length===0||!l)return 0;let t=new Map;for(let e of n){let n=`${e.direction}:${e.predicate}`,r=t.get(n)??{predicate:e.predicate,direction:e.direction,targets:[]};r.targets.push(e.targetId),t.set(n,r)}let r=0;for(let n of e)for(let e of t.values())try{await go(l,n,e.predicate,e.targets,e.direction)}catch(t){r+=1,console.error(`Failed to relate document`,n,e.predicate,t)}return r<e.length*t.size&&Rg(),r},[n,l]),hasRows:n.length>0}}function jR({f:e,idPrefix:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(!1),o=!e.workspaceName;return(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(Gu,{children:`Related documents`}),(0,$.jsxs)(Z,{type:`button`,variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs`,disabled:o,onClick:()=>r(!0),title:o?`No workspace to relate within`:`Pick documents the new one relates to`,children:[(0,$.jsx)(sn,{className:`mr-1 h-3 w-3`}),` Add`]})]}),e.rows.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None. Relations are written right after the document is created.`}):(0,$.jsx)(`ul`,{className:`space-y-1`,children:e.rows.map((n,r)=>{let i=n.document?Yr(n.document).title:`Document ${n.targetId}`,a=`${t}-relation-${r}`;return(0,$.jsxs)(`li`,{className:`flex items-center gap-1.5 rounded-md border border-input px-2 py-1.5 text-sm`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.update(r,{direction:n.direction===`out`?`in`:`out`}),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground`,title:n.direction===`out`?`The new document ${n.predicate} this one (click to flip)`:`This document ${n.predicate} the new one (click to flip)`,"aria-label":`Flip relation direction`,children:n.direction===`out`?(0,$.jsx)(Dt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Jn,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`label`,{htmlFor:a,className:`sr-only`,children:`Predicate`}),(0,$.jsx)(`select`,{id:a,value:n.predicate,onChange:t=>e.update(r,{predicate:t.target.value}),className:`w-[9.5rem] shrink-0 rounded-md border border-input bg-background px-1.5 py-1 font-mono text-[11px] focus:outline-none focus:ring-2 focus:ring-ring`,children:(e.predicates.includes(n.predicate)?e.predicates:[n.predicate,...e.predicates]).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))}),n.document?(0,$.jsx)(Gm,{document:n.document,size:3.5}):null,(0,$.jsx)(`span`,{className:J(`min-w-0 flex-1 truncate`,!n.document&&`italic text-muted-foreground`),title:i,children:i}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.remove(r),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,title:`Remove`,"aria-label":`Remove relation`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]},`${n.direction}:${n.predicate}:${n.targetId}`)})}),n&&e.workspaceName&&(0,$.jsx)($p,{onClose:()=>{i||r(!1)},children:(0,$.jsx)(ih,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,confirmLabel:`Add`,tabs:[`relations`],fixedWorkspaceName:e.workspaceName,documentCount:1,saving:i,relationPredicates:e.predicates.length?e.predicates:[`references`],relationExcludeIds:new Set(e.rows.map(e=>e.targetId)),onClose:()=>r(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:t,direction:n,targetIds:i})=>{a(!0);try{await e.add(t,n,i),r(!1)}finally{a(!1)}}})})]})}function MR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=AR(n,t.addRelateTo),o=yS(n,a.write,t.addRelateTo?`related:${t.addRelateTo.documents.map(e=>e.id).sort().join(`,`)}`:`add`),s=VD(t.activeWorkspaceName),c=!!n&&o.canSave,l=async()=>{if(n)try{let t=await o.save(n),i=await a.write(t);r(i?`Note created; some relations failed`:`Note created`),o.finish(),e()}catch(e){i(e instanceof Error?e.message:`Failed to create note`)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Body`}),(0,$.jsx)(Ho,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`note-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`note-comment`,value:o.comment,onChange:e=>o.setComment(e.target.value),rows:2,placeholder:`Optional; context you can't infer from the body`,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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsx)(xD,{geotag:o.geotag,idPrefix:`note-geotag`}),(0,$.jsx)(jR,{f:a,idPrefix:`note`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsx)(Go,{...o,onRetry:o.retry}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:o.saving,children:`Close`}),(0,$.jsx)(Z,{size:`sm`,onClick:l,disabled:!c,children:o.saving?`Saving…`:`Done`})]})]})}function NR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=OD(),o=AR(n,t.addRelateTo),s=VD(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`link-url`,children:`URL`}),(0,$.jsx)(Y,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`link-title`,children:`Title`}),(0,$.jsx)(Y,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsx)(xD,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,$.jsx)(jR,{f:o,idPrefix:`link`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Link created; some relations failed`:`Link created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create link`)}},disabled:!c,children:a.saving?`Saving…`:`Save link`})]})]})}function PR(e){let[t,n]=(0,Q.useState)({key:``,list:[]});return(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return pa(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await sa(e,`github`,t.address).catch(()=>[]);for(let e of n){if(e.writable===!1)continue;let n=e.id||e.name;a.push({driver:`github`,address:t.address,container:n,label:`GitHub: ${n}`})}}t||n({key:e,list:a})}).catch(()=>{t||n({key:e,list:[]})}),()=>{t=!0}},[e]),e&&t.key===e?t.list:[]}function FR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=J_(),o=AR(n,t.addRelateTo),s=VD(t.activeWorkspaceName),c=PR(t.activeWorkspaceName),[l,u]=(0,Q.useState)(`canvas`),[d,f]=(0,Q.useState)(!1),p=c.find(e=>`${e.driver}:${e.address}:${e.container}`===l),m=p?a.title.trim().length>0&&!d:!!n&&a.canSave,h=async()=>{if(p){f(!0);try{await aa(t.activeWorkspaceName||``,p.driver,p.address,p.container,{title:a.title.trim(),...a.description.trim()?{description:a.description.trim()}:{},...a.tags.length?{labels:a.tags}:{}}),r(`Issue created in ${p.container}`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create issue`)}finally{f(!1)}return}if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Todo created; some relations failed`:`Todo created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create todo`)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsx)(Gv,{...a}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`todo-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`todo-comment`,value:a.comment,onChange:e=>a.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`})]}),c.length>0&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`todo-destination`,children:`Save to`}),(0,$.jsxs)(`select`,{id:`todo-destination`,value:l,onChange:e=>u(e.target.value),className:`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`,children:[(0,$.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,js(n)]}),c.map(e=>(0,$.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a GitHub issue (due date, priority and status stay Canvas-side until the issue syncs back).`})]}),(0,$.jsx)(xD,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,$.jsx)(jR,{f:o,idPrefix:`todo`}),!p&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function IR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=ey(),o=AR(n,t.addRelateTo),s=VD(t.activeWorkspaceName),c=async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Identity created; some relations failed`:`Identity created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create identity`)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsx)(ay,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`identity-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`identity-comment`,value:a.comment,onChange:e=>a.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`})]}),(0,$.jsx)(jR,{f:o,idPrefix:`identity`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function LR({capture:e=!1}={}){let{closeAdd:t,state:n}=zs(),r=Ds(),i=r?.mode===`workspace`&&r.treeName===`backends`,a=AR(r,n.addRelateTo),{showSuccessToast:o,showErrorToast:s}=Wr(),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(!1),d=PD(),{items:f,running:p}=d,[m,h]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(r?.mode!==`context`)return;let e=!1;return Ms(r).then(t=>{e||h({contextId:r.contextId,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[r]);let g=WD(r?.mode===`workspace`?r.workspaceName:r&&m?.contextId===r.contextId?m.workspaceName:null),_=e=>{e&&d.addFiles(Array.from(e))},v=e=>{e.preventDefault(),u(!1),_(e.dataTransfer.files)},y=f.filter(e=>e.status===`error`).length,b=f.filter(e=>e.status===`done`).length,x=f.length-b,S=!!r&&!p&&x>0;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,onClick:()=>c.current?.click(),className:J(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,l?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,$.jsx)(Qe,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,$.jsx)(`p`,{className:`text-sm`,children:e?`Take a photo or video`:`Drag & drop files here`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`click to open the camera`:`or click to browse`}),(0,$.jsx)(`input`,{ref:c,type:`file`,multiple:!0,accept:e?`image/*,video/*`:void 0,capture:e?`environment`:void 0,className:`hidden`,onChange:e=>{_(e.target.files),e.target.value=``}})]}),(0,$.jsx)(zD,{items:f,running:p,onRemove:d.removeItem}),!i&&(0,$.jsx)(qD,{fields:g,idPrefix:`file`,multiple:f.length>1}),(0,$.jsx)(jR,{f:a,idPrefix:`file`}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[js(r),i?`. Existing files are never overwritten.`:``]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>p?d.cancel():t(),children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(!(!S||!r))try{let e=i?null:await g.geotag.capture(),n=await d.start(r,(t,n)=>GD(t,n,{tags:g.tags,comment:g.comment,geo:e})),c=await a.write(n.docIds);if(n.failed===0){let e=n.resumed?` (${n.resumed} already uploaded)`:``,r=c?`; some relations failed`:``;o(`${n.done} file(s) uploaded${e}${r}`),t()}else s(`${n.failed} of ${n.total} file(s) failed — retry keeps what already made it`)}catch(e){s(e instanceof Error?e.message:`Failed to upload files`)}},disabled:!S,children:p?`Uploading…`:y>0?(0,$.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(ir,{className:`h-3.5 w-3.5`}),`Retry failed (`,y,`)`]}):`Add files`})]})]})}function RR(){let{closeAdd:e}=zs(),t=Ds(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(!1),c=i.trim().replace(/^\/+|\/+$/g,``),l=!!t&&!!c&&!o,u=async()=>{if(!(!l||!t)){s(!0);try{let{workspaceName:r,path:i,treeName:a}=await Ms(t),o=i===`/`?``:i;if(a===`backends`){let e=await ks(r,i);await ca(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),_s(t)}else await Aa(r,`${o}/${c}`,!0,a);n(`Folder created`),e()}catch(e){r(e instanceof Error?e.message:`Failed to create folder`)}finally{s(!1)}}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,$.jsx)(Y,{id:`add-folder-name`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&u()},placeholder:`e.g. projects/alpha`,autoFocus:!0}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,js(t)]})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function zR(){let{openAddPicker:e,closeAdd:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,Q.useState)(!1);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>e(),"aria-hidden":!0}),(0,$.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,$.jsx)(Cg,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:n?.mode===`workspace`?n.workspaceName:void 0,saving:a,onConfirm:async e=>{o(!0);try{await ws(n,e),r(`${e.length} document${e.length===1?``:`s`} added`),t()}catch(e){i(e instanceof Error?e.message:`Failed to add documents`)}finally{o(!1)}},onClose:e})})]})}function BR(){let{state:e,closeAdd:t}=zs(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,$.jsx)(VR,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a},`${r}:${n.id}`)}function VR({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=No(e,t),s=VD(t),c=async()=>{try{await o.save(),i(`Note updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update note`)}};return(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`edit-note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,$.jsx)(Gu,{children:`Body`}),(0,$.jsx)(`div`,{className:`flex-1`,children:(0,$.jsx)(Ho,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsx)(Go,{...o,onRetry:o.save}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Close`}),(0,$.jsx)(Z,{size:`sm`,onClick:c,disabled:!o.canSave,children:o.saving?`Saving…`:`Done`})]})]})}function HR(e,t){let n=Jo(e.metadata?.features),[r,i]=(0,Q.useState)(String(e.data?.label??``)),[a,o]=(0,Q.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,Q.useState)(!1),l=!s;async function u(){c(!0);try{let n=a.map(e=>e.trim()).filter(Boolean);await fa(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data,...r.trim()?{label:r.trim()}:{},tags:n},metadata:{features:Yo(a)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{c(!1)}}return{url:String(e.data?.uri??e.data?.url??``),label:r,setLabel:i,tags:a,setTags:o,saving:s,canSave:l,save:u}}function UR(){let{state:e,closeAdd:t}=zs(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,$.jsx)(WR,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function WR({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=HR(e,t),s=VD(t);return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(Gu,{children:[`URL `,(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,$.jsx)(Y,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`edit-link-label`,children:`Label`}),(0,$.jsx)(Y,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Link updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update link`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save link`})]})]})}var GR=380,KR=300,qR=560,JR={message:{label:`New Message`,icon:b},note:{label:`New Note`,icon:Kn},link:{label:`New Link`,icon:_n},todo:{label:`New Todo`,icon:Vt},identity:{label:`New Identity`,icon:We},sketch:{label:`New Sketch`,icon:le},plaintext:{label:`New Plaintext File`,icon:nn},file:{label:`Add Files`,icon:Qe},photo:{label:`Photo/Video`,icon:Ke},existing:{label:`Add Existing`,icon:En},folder:{label:`New Folder`,icon:st}};function YR(){let{state:e,openAdd:t,openAddPicker:n,closeAdd:r}=zs();Fp(r,e.addOpen);let{addOpen:i,addKind:a,editDocument:o,addModal:s}=e,c=Ds(),l=Ps(c),u=l.isBackend&&!!a&&![`file`,`photo`,`folder`,`message`,`plaintext`].includes(a),d=e.activeWorkspaceName,f=!d||!!e.addRelateTo,p=u||a===`message`&&f,m=l.isBackend?[`note`,`link`,`todo`,`identity`,`sketch`,`existing`]:[`plaintext`];f&&m.push(`message`);let h=c?.mode===`workspace`?`${c.workspaceName}:${c.treeName}:${c.path}`:c?.contextId,g=gl();(0,Q.useEffect)(()=>{!i||a!==`sketch`||l.isBackend||(r(),g(gD.createUrl(c)))},[i,a,c,r,g,l.isBackend]);let _=u_(),[v,y]=(0,Q.useState)(GR),b=(0,Q.useRef)(null),x=(0,Q.useCallback)(e=>{e.preventDefault(),b.current={startX:e.clientX,startWidth:v};let t=e=>{if(!b.current)return;let t=b.current.startX-e.clientX,n=Math.min(qR,Math.max(KR,b.current.startWidth+t));y(n)},n=()=>{b.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[v]);if(!i)return null;let S=!!o,C=!S&&(!a||p),w,T;S?(w=o.schema===`data/schema/note`?`Edit Note`:`Edit Link`,T=o.schema===`data/schema/note`?Kn:_n):a&&!p?(w=JR[a].label,T=JR[a].icon):(w=`Add`,T=sn);let E=(0,$.jsxs)($.Fragment,{children:[_&&!s&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:r,"aria-hidden":!0}),(0,$.jsxs)(`div`,{style:_||s?void 0:{width:v},className:J(`flex flex-col overflow-hidden rounded-[var(--panel-radius)] border bg-card surface-glass`,s?`h-full w-full`:_?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!_&&!s&&(0,$.jsx)(`div`,{onMouseDown:x,className:`absolute left-0 top-0 bottom-0 z-10 w-1 cursor-col-resize transition-colors hover:bg-primary/20`}),(0,$.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center gap-2 border-b-4 px-2`,style:e.activeAccentColor?{borderBottomColor:e.activeAccentColor}:void 0,children:[(0,$.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,"aria-label":`Back one level`,onClick:()=>C||S?r():n(),children:(0,$.jsx)(Jn,{className:`h-5 w-5`})}),(0,$.jsxs)(`span`,{className:`flex flex-1 items-center gap-2 text-sm font-medium`,children:[S?(0,$.jsx)(_e,{className:`h-4 w-4`}):(0,$.jsx)(T,{className:`h-4 w-4`}),w]}),(0,$.jsx)(`button`,{type:`button`,onClick:r,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Close`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[S&&o.schema===`data/schema/note`&&(0,$.jsx)(BR,{}),S&&o.schema===`data/schema/link`&&(0,$.jsx)(UR,{}),!S&&C&&e.addRelateTo&&(0,$.jsxs)(`p`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`The new document will be related to `,e.addRelateTo.documents.length,` selected document`,e.addRelateTo.documents.length===1?``:`s`,`.`]}),!S&&l.isBackend&&a!==`message`&&(0,$.jsx)(`p`,{className:`border-b px-4 py-3 text-xs text-muted-foreground`,children:l.loading?`Checking storage destination…`:l.error||`Files are saved directly to this backend folder. Notes and other database documents belong in context or directory trees.`}),!S&&C&&(!l.isBackend||l.destination)&&(0,$.jsx)(yD,{onSelect:t,omit:m}),!S&&a===`message`&&!f&&d&&(0,$.jsx)(Tv,{workspaceId:d,onClose:r},d),!S&&!l.isBackend&&a===`note`&&(0,$.jsx)(MR,{},h),!S&&!l.isBackend&&a===`link`&&(0,$.jsx)(NR,{}),!S&&!l.isBackend&&a===`todo`&&(0,$.jsx)(FR,{}),!S&&!l.isBackend&&a===`identity`&&(0,$.jsx)(IR,{}),!S&&l.destination&&a===`plaintext`&&(0,$.jsx)(DR,{},h),!S&&(!l.isBackend||l.destination)&&a===`file`&&(0,$.jsx)(LR,{},h),!S&&(!l.isBackend||l.destination)&&a===`photo`&&(0,$.jsx)(LR,{capture:!0},h),!S&&!l.isBackend&&a===`existing`&&(0,$.jsx)(zR,{}),!S&&(!l.isBackend||l.destination)&&a===`folder`&&(0,$.jsx)(RR,{},h)]})]})]});return s?(0,$.jsx)(Lp,{label:w,onClose:r,children:E}):E}var XR=(0,Q.createContext)(null);function ZR(){return(0,Q.useContext)(XR)}function QR(){let e=ZR(),t=e?.notifications??[];return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,$.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,$.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,$.jsx)(N,{className:`w-4 h-4`}),(0,$.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(bn,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,$.jsx)(nt,{className:`w-3 h-3`})})]}),t.length===0?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-(--card-radius)`,children:`No notifications`}):(0,$.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,$.jsxs)(`div`,{className:`rounded-(--card-radius) border p-2.5`,children:[(0,$.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,$.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}function $R({status:e}){return(0,$.jsx)(`span`,{className:J(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function ez(){let{openAgentT2:e}=zs(),{setSection:t}=PT(),n=gl(),{agents:r,isLoading:i,refresh:a}=WL(!0),{showToast:o}=Vr(),[s,c]=(0,Q.useState)(new Set),l=(e,t)=>c(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),u=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await bk(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}},d=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await xk(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,$.jsx)(ct,{className:`w-8 h-8 opacity-30`}),(0,$.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,$.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,$.jsxs)(`div`,{className:`group relative px-3 py-2.5 cursor-pointer transition-colors bg-card hover:bg-accent/50`,style:{borderLeft:`6px solid ${t.color||`transparent`}`},onClick:()=>e(t.id),children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)($R,{status:t.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,$.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,$.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>d(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Stop`,children:(0,$.jsx)(zn,{className:`w-3 h-3`})}):(0,$.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>u(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Start`,children:(0,$.jsx)(xe,{className:`w-3 h-3`})})})]}),t.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function tz(){let e=ZR(),[t,n]=(0,Q.useState)(50),r=e?.notifications??[],i=r.slice(-t).reverse();return(0,$.jsxs)(`section`,{"aria-label":`Notification history`,className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b px-4 py-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Notifications`,r.length>0&&(0,$.jsx)(`span`,{className:`ml-2 font-normal text-muted-foreground`,children:r.length})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:`Saved on this browser`})]}),r.length>0&&(0,$.jsxs)(Z,{variant:`ghost`,size:`sm`,onClick:()=>void e?.clear(),title:`Clear all notifications`,className:`shrink-0 gap-1.5`,children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),`Clear all`]})]}),e?.storageError&&(0,$.jsx)(`p`,{role:`alert`,className:`border-b px-4 py-3 text-xs text-destructive`,children:`Couldn’t access notification history in this browser.`}),e?.loading?(0,$.jsx)(`p`,{role:`status`,className:`p-4 text-sm text-muted-foreground`,children:`Loading notifications…`}):r.length===0?(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,$.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,$.jsx)(bn,{className:`h-5 w-5 text-muted-foreground`})}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No notifications yet`})]}):(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[(0,$.jsx)(`ol`,{className:`space-y-2`,children:i.map(t=>{let n=t.status===`error`?z:t.status===`completed`?be:t.status===`started`?N:bn;return(0,$.jsx)(`li`,{"data-notification-id":t.id,className:`rounded-(--card-radius) border bg-card p-3`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(n,{"aria-hidden":!0,className:`mt-0.5 h-4 w-4 shrink-0 ${t.status===`error`?`text-destructive`:`text-muted-foreground`}`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`break-words text-sm font-medium`,children:t.title}),t.text&&(0,$.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap break-words text-xs text-muted-foreground`,children:t.text}),(0,$.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[(0,$.jsx)(`time`,{dateTime:t.timestamp,children:new Date(t.timestamp).toLocaleString()}),t.status===`started`&&(0,$.jsx)(`span`,{children:` · Started`}),t.status===`completed`&&(0,$.jsx)(`span`,{children:` · Completed`}),t.status===`error`&&(0,$.jsx)(`span`,{children:` · Error`})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void e?.remove(t.id),"aria-label":`Clear notification: ${t.title}`,title:`Clear notification`,className:`-mr-1 -mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent focus-ring touch-target`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})},t.id)})}),r.length>t&&(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,className:`mt-3 w-full`,onClick:()=>n(e=>e+50),children:`Show older notifications`})]})]})}function nz(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(`
53
+ `)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await T(n.id,Array.from(d.values()))})]}),U&&!oe&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,$.jsxs)(`div`,{className:`px-3 py-1.5 text-[10px] text-muted-foreground italic`,children:[`This is a target. Right-click the source (`,u?.path,`) to merge/subtract`]})]})]})}function sL({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,$.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 bg-card ring-1 ring-primary/50 shadow-elevation-3 text-sm font-medium`,children:[(0,$.jsx)(hr,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,$.jsx)(`input`,{ref:r,className:`flex-1 bg-transparent outline-none min-w-0 text-sm font-medium placeholder:font-normal placeholder:text-muted-foreground`,placeholder:n,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),i()),e.key===`Escape`&&t()},onBlur:i})]})}function cL(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function lL(e,t,n){let r=cL(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>lL(e,r,n))??!1}function uL({node:e,parentPath:t,depth:n,isLast:r,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:c,targetLayers:l,clipboard:u,searchQuery:d,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,policyBadgeFor:M,removingPaths:N,accordion:F=!1,trail:I=[]}){let L=Ep(),R=cL(t,e.name),z=M?.(R)??null,ee=S.get(R)??wm(e),[te,ne]=(0,Q.useState)(()=>i!==`/`&&(i===R||i.startsWith(R+`/`))),[B,re]=(0,Q.useState)(i);if(B!==i&&(re(i),i!==`/`&&i.startsWith(R+`/`)&&ne(!0)),d&&!lL(e,t,d))return null;let ie=te||p===R||d.length>0,ae=e.children&&e.children.length>0,oe=i===R,V=a===R,H=c?.path===R,U=l.has(R),se=e.type===`canvas`,W=t=>{if(t.ctrlKey||t.metaKey){_(R,e.id);return}if(t.shiftKey&&h){h(R);return}m(R)},ce=e=>{!ae||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button, input, textarea, select, a, [contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),ne(e=>!e))},le=[...I].reverse().find(Boolean)??null,ue=ee.color||le,de=F?[...I,ue]:I,pe=i!==`/`&&i.startsWith(R+`/`),me=!H&&!U,G=me&&oe,he=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,ge=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,_e=Math.min(n,5),ve=ie&&!!ae,K=n>0&&le?le:ue,q=me&&!G&&!e.locked&&ve,ye=K?Math.min(12+_e*5+(pe?6:0),34):Math.min(_e*7+(pe?5:0)+(V?3:0),30),be=G?`var(--primary)`:H?he(`var(--info)`,22):U?he(`var(--warning)`,22):e.locked?he(`var(--warning)`,20+_e*4):q?ue?he(ue,84):he(`var(--foreground)`,38):he(K||`var(--foreground)`,ye),xe=G?`text-primary-foreground`:q&&ue?Fm(ue):`text-foreground`,Se=F&&ie&&ae&&n<tL,Ce=(0,$.jsxs)(`div`,{"data-active":oe||void 0,className:J(`group relative flex cursor-pointer select-none items-stretch overflow-hidden text-sm`,`after:pointer-events-none after:absolute after:inset-0 after:bg-foreground/0 after:transition-colors hover:after:bg-foreground/[0.07]`,xe,H&&`ring-1 ring-inset ring-info/40`,U&&!H&&`ring-1 ring-inset ring-warning/40`,C===R&&!s&&!w&&`ring-2 ring-inset ring-info`,C===R&&!s&&w&&`ring-2 ring-inset ring-success`),style:{height:eL,background:be,borderBottom:`1px solid ${ge(14)}`,...Se?{position:`sticky`,top:n*eL,zIndex:20-n}:{}},draggable:!s&&!e.metadata?.backendTrash,onClick:W,onDoubleClick:ce,...s?{}:L,onContextMenu:t=>{s||(t.preventDefault(),v(t,R,e))},onDragStart:e=>{s||T(R,e)},onDragEnter:e=>{s||E(R,e)},onDragOver:e=>{s||D(R,e)},onDragLeave:e=>O(R,e),onDragEnd:()=>k(),onDrop:e=>{s||A(R,e)},children:[I.length>0&&(0,$.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:I.map((e,t)=>(0,$.jsx)(`span`,{className:`w-[3px]`,style:{background:e||ge(28)}},t))}),(()=>{let t=ee.color?{background:ee.color}:le?{background:`color-mix(in oklab, ${le} 45%, transparent)`}:{background:ge(10)},n=(0,$.jsx)(f,{icon:ee.icon||(se?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:J(`shrink-0`,ee.color?Pm(ee.color):G?`text-primary-foreground`:q?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return x?(0,$.jsx)(`button`,{type:`button`,className:r,style:t,title:`Change icon`,onClick:t=>{br()||(t.stopPropagation(),x(t,R,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,R,e)},children:n}):(0,$.jsx)(`span`,{className:r,style:t,children:n})})(),(0,$.jsx)(`span`,{className:J(`min-w-0 flex-1 self-center truncate px-2.5`,oe||pe||ve?`font-semibold`:`font-medium`),title:e.description||void 0,children:e.label||e.name}),N.has(R)&&(0,$.jsx)(P,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":N.get(R)}),j?.has(R)&&(0,$.jsx)(P,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),z&&(0,$.jsx)(fe,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":z,children:(0,$.jsx)(`title`,{children:z})}),!s&&(0,$.jsx)(`button`,{type:`button`,className:`reveal-on-hover shrink-0 self-center rounded p-1 hover:bg-foreground/10`,onClick:t=>{t.stopPropagation(),v(t,R,e)},children:(0,$.jsx)(vn,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{type:`button`,className:J(`relative z-[1] flex w-12 shrink-0 cursor-pointer items-center justify-center transition-colors`,`bg-[color-mix(in_oklab,currentColor_9%,transparent)] hover:bg-[color-mix(in_oklab,currentColor_24%,transparent)] active:bg-[color-mix(in_oklab,currentColor_32%,transparent)]`,!ae&&p!==R&&`invisible`),style:{borderLeft:`1px solid ${ge(16)}`},"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,title:ie?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,$.jsx)(Xe,{className:`h-5 w-5`,strokeWidth:2.25}):(0,$.jsx)(hr,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,$.jsxs)(`div`,{className:`relative`,children:[F?Ce:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${$I/2}px`,...r?{height:`1.375rem`}:{bottom:0}}}),(0,$.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${$I/2}px`,width:`${$I/2}px`}}),(0,$.jsxs)(`div`,{"data-active":oe||void 0,className:J(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none overflow-hidden`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,H&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,U&&!H&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!H&&!U&&oe&&!e.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!H&&!U&&oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!H&&!U&&!oe&&V&&`bg-primary/[0.03] before:bg-transparent`,!H&&!U&&!oe&&!V&&!e.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!H&&!U&&!oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,C===R&&!s&&!w&&`ring-2 ring-info bg-info-subtle/50`,C===R&&!s&&w&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:ee.color?`4px solid ${ee.color}`:`4px solid transparent`},draggable:!s&&!e.metadata?.backendTrash,onClick:W,onDoubleClick:ce,...s?{}:L,onContextMenu:t=>{s||(t.preventDefault(),v(t,R,e))},onDragStart:e=>{s||T(R,e)},onDragEnter:e=>{s||E(R,e)},onDragOver:e=>{s||D(R,e)},onDragLeave:e=>O(R,e),onDragEnd:()=>k(),onDrop:e=>{s||A(R,e)},children:[(0,$.jsx)(`button`,{type:`button`,className:J(`shrink-0 text-muted-foreground hover:text-foreground`,!ae&&p!==R&&`invisible`),"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,$.jsx)(Xe,{className:`w-4 h-4`}):(0,$.jsx)(hr,{className:`w-4 h-4`})}),(()=>{let t=(0,$.jsx)(f,{icon:ee.icon||(se?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:ee.color||void 0,className:J(`shrink-0`,!ee.color&&(se?`text-primary`:`text-muted-foreground`))});return x?(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 rounded p-0.5 -m-0.5 hover:bg-muted-foreground/10 touch-target`,title:`Change icon`,onClick:t=>{br()||(t.stopPropagation(),x(t,R,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,R,e)},children:t}):t})(),(0,$.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name}),N.has(R)&&(0,$.jsx)(P,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":N.get(R)}),j?.has(R)&&(0,$.jsx)(P,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),z&&(0,$.jsx)(fe,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":z,children:(0,$.jsx)(`title`,{children:z})}),!s&&(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:t=>{t.stopPropagation(),v(t,R,e)},children:(0,$.jsx)(vn,{className:`w-4 h-4`})})]})]}),ie&&(ae||p===R)&&(0,$.jsxs)(`div`,{className:F?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[p===R&&(0,$.jsx)(sL,{onConfirm:e=>y(R,e),onCancel:b}),e.children?.map((t,r)=>(0,$.jsx)(uL,{node:t,parentPath:R,depth:n+1,isLast:r===(e.children?.length??0)-1,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:c,targetLayers:l,clipboard:u,searchQuery:d,inlineCreateParent:p,onSelect:m,onShiftSelect:h,onShowContent:g,onCtrl:_,onCtxMenu:v,onConfirmCreate:y,onCancelCreate:b,onOpenPicker:x,styleOverrides:S,dragOverPath:C,isCopyDrag:w,onDragStart:T,onDragEnter:E,onDragOver:D,onDragLeave:O,onDragEnd:k,onDrop:A,resyncingPaths:j,policyBadgeFor:M,removingPaths:N,accordion:F,trail:de},t.id||t.name))]})]})}function dL({root:e,workspaceId:t,treeName:n=`context`,isBackendsTree:r=!1,onRestoreTrash:i,onDiscardTrash:a,selectedPath:o,pendingPath:s,onSelect:c,isLoading:l=!1,readOnly:u=!1,onAddRule:d,onAddStoreRule:f,onStoragePolicy:p,policyBadgeFor:m,rootLabel:h,contentPath:g,onShowContent:_,onOpenToSide:v,onShiftSelect:y,onInsertPath:b,onNewCanvas:x,onShareCanvas:S,onRemovePath:C,onRenamePath:w,onMovePath:T,onCopyPath:E,onExportSubtree:D,onImportSubtree:O,pastedDocumentIds:k,onPasteDocuments:A,onLockLayer:j,onUnlockLayer:M,onDestroyLayer:N,onMergeLayer:F,onSubtractLayer:I,onMergeDown:L,onSubtractDown:R,onResyncBackend:z,onCreateBackendFolder:ee,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onUpdateNode:B,isPathPinned:re,onTogglePin:ie,searchQuery:ae=``,resyncingPaths:oe,backends:V}){let H=_A(),[U,se]=(0,Q.useState)(null),[W,ce]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(new Map),[de,fe]=(0,Q.useState)(null),[pe,me]=(0,Q.useState)(new Map),G=(0,Q.useRef)(new Set),he=(0,Q.useCallback)(async(e,t=!1,i=!1,a=!1)=>{if(!(r?ne:C)||[...G.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;G.current.add(e);let o=r?`Deleting from backend…`:a?`Removing documents and backend files…`:i?`Removing and purging documents…`:`Removing folder…`;me(t=>new Map(t).set(e,o));try{return r?await ne(e):await C(e,n===`directory`||t,i,a)}finally{G.current.delete(e),me(t=>{let n=new Map(t);return n.delete(e),n})}},[C,ne,r,n]),[ge,_e]=(0,Q.useState)(null),[ve,K]=(0,Q.useState)(new Map),[q,ye]=(0,Q.useState)(e),be=(0,Q.useRef)(new Map),xe=(0,Q.useRef)(null),[Se,Ce]=(0,Q.useState)(null);if(e!==q){ye(e);let t=Se;K(t?new Map([[t.path,t.style]]):new Map)}let[we,Te]=(0,Q.useState)(null),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)(!1),[Ae,je]=(0,Q.useState)(!1),[Me,Ne]=(0,Q.useState)(!1),Pe=(0,Q.useRef)(!1),Fe=(0,Q.useRef)(null),Ie=(0,Q.useRef)(n),Le=(0,Q.useRef)(!1),Re=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=e=>{se(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||Re.current;Le.current=t,ke(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let ze=(0,Q.useCallback)((e,t,r)=>{if(pb(Ie.current,e)||pb(n,t))return!1;if(Ie.current!==n)return!0;let i=e.endsWith(`/`)?e.slice(0,-1):e,a=t.endsWith(`/`)?t.slice(0,-1):t,o=i.substring(0,i.lastIndexOf(`/`))||`/`;return!(a.startsWith(i+`/`)||i===a||!r&&a===o)},[n]),Be=(0,Q.useCallback)((e,t)=>{if(pb(n,e)){t.preventDefault();return}Fe.current=e,Ie.current=n,t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:n})),t.dataTransfer.effectAllowed=`copyMove`},[n]),Ve=e=>e.ctrlKey||e.altKey||Re.current,He=(0,Q.useCallback)((e,t)=>{if(pb(n,e))return;let i=Fe.current,a=Ve(t);if(a!==Le.current&&(Le.current=a,ke(a)),i){if(!ze(i,e,a))return}else if(iL(t)&&!rL(e,r))return;t.preventDefault(),De(e)},[ze,n,r]),Ue=(0,Q.useCallback)((e,t)=>{if(pb(n,e)){t.dataTransfer.dropEffect=`none`;return}let i=Ve(t);i!==Le.current&&(Le.current=i,ke(i));let a=Fe.current;if(a){if(!ze(a,e,i)){t.dataTransfer.dropEffect=`none`;return}}else if(iL(t)&&!rL(e,r)){t.dataTransfer.dropEffect=`none`;return}t.preventDefault(),t.dataTransfer.dropEffect=i&&!r?`copy`:`move`},[ze,n,r]),We=(0,Q.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||De(t=>t===e?null:t)},[]),Ge=(0,Q.useCallback)(()=>{Fe.current=null,Ie.current=n,Le.current=!1,ke(!1),De(null)},[n]),Ke=(0,Q.useCallback)(async(e,i)=>{if(i.preventDefault(),i.stopPropagation(),pb(n,e))return;let a=(()=>{try{return JSON.parse(i.dataTransfer.getData(`application/json`))}catch{return null}})();if(a?.type===`document`&&Array.isArray(a.documentIds)&&a.documentIds.length){if(Fe.current=null,Le.current=!1,ke(!1),De(null),_g(a,t,n,e))return;if(A&&rL(e,r))try{await A(e,a.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let o=(()=>{try{return JSON.parse(i.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),s=o?.path||i.dataTransfer.getData(`text/plain`),c=o?.treeName||Ie.current||n;if(pb(c,s))return;let l=Ve(i)||Le.current;if(Fe.current=null,Ie.current=n,Le.current=!1,ke(!1),De(null),!s)return;let u=i.shiftKey,d=c!==n;if(!(!d&&s===e)&&!(!d&&!ze(s,e,l)))try{if(l&&E)await E(s,e,u,c,n);else if(!l&&T){let t=Pe.current&&!r&&!!L;await T(s,e,u,c,n,t?{mergeDown:t}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[ze,E,T,A,t,n,r,L]),qe=ae.toLowerCase().trim(),Je=(0,Q.useCallback)((e,t,n)=>{e.stopPropagation(),fe({x:e.clientX,y:e.clientY,path:t,node:n})},[]),Ye=(0,Q.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(xe.current=null,Ce(null),_e({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),Ze=(0,Q.useCallback)(e=>{if(!ge||!B)return;let t=ge.path,n={...ve.get(t)??(xe.current?.path===t?xe.current.style:wm(ge.node)),...e};xe.current={path:t,style:n},Ce({path:t,style:n}),K(e=>new Map(e).set(t,n));let r=Em(ge.node.metadata,n),i=be.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),B(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[ge,B,ve]),Qe=(0,Q.useCallback)((e,t)=>{W?e===W.path?(ce(null),ue(new Map)):ue(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(ce({path:e,id:t}),ue(new Map))},[W]),$e=(0,Q.useCallback)(async e=>{!U||!T||!E||U.treeName===n&&(e===U.path||e.startsWith(U.path+`/`))||(U.mode===`cut`?(await T(U.path,e,!1,U.treeName,n),se(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))):await E(U.path,e,!0,U.treeName,n))},[U,T,E,n]);(0,Q.useEffect)(()=>{if(u)return;let e=e=>{let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),U?.mode===`cut`){$e(o);return}let r={mode:`cut`,path:o,treeName:n};se(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[U,$e,u,o,n]);let et=(0,Q.useCallback)(async(e,t)=>{Te(null);let n=e===`/`?`/${t}`:`${e}/${t}`;try{nL(e,r)&&ee?await ee(e,t)&&c(n):b&&await b(n,!0)&&c(n)}catch(e){alert(e instanceof Error?e.message:String(e))}},[b,ee,c,r]),tt=(0,Q.useCallback)(()=>{Te(null)},[]),nt=(0,Q.useCallback)((e,t)=>{let r={mode:t,path:e,treeName:n};se(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))},[n]),rt=(0,Q.useCallback)(t=>{if(u||am(t.target)||o&&pb(n,o))return;if(im(t,`Mod+V`)){k?.length&&A&&o&&rL(o,r)?(t.preventDefault(),A(o,k).catch(()=>{})):U&&o&&(t.preventDefault(),$e(o).catch(e=>alert(e instanceof Error?e.message:String(e))));return}if(o&&o!==`/`&&(im(t,`Mod+C`)||!r&&im(t,`Mod+X`))){t.preventDefault(),nt(o,t.key.toLowerCase()===`x`?`cut`:`copy`);return}if((r?!ne||!po(o||``,V):!C)||t.key!==`Delete`&&t.key!==`Backspace`||!o||o===`/`)return;t.preventDefault();let i=di(e,o);if(!r&&i?.locked){alert(`"${o}" is locked`);return}confirm(r?`Delete "${o}" and its contents from this backend?`:`Remove "${o}"${n===`directory`?` and all children`:``}?`)&&he(o,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))},[u,C,ne,he,o,e,k,A,U,$e,r,nt,n,V]),it=(0,Q.useCallback)(()=>{je(e=>{let t=!e;return Re.current=t,Le.current=t,ke(t),t})},[]);if(l)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let at=W||le.size>0,ot={accordion:H,selectedPath:o,pendingPath:s,contentPath:g,readOnly:u,sourceLayer:W,targetLayers:le,clipboard:U,searchQuery:qe,inlineCreateParent:we,onSelect:c,onShiftSelect:y,onShowContent:_,onCtrl:Qe,onCtxMenu:Je,onConfirmCreate:et,onCancelCreate:tt,onOpenPicker:B?Ye:void 0,styleOverrides:ve,dragOverPath:Ee,isCopyDrag:Oe,onDragStart:Be,onDragEnter:He,onDragOver:Ue,onDragLeave:We,onDragEnd:Ge,onDrop:Ke,resyncingPaths:oe,backends:V,policyBadgeFor:r?void 0:m,removingPaths:pe};return(0,$.jsxs)(`div`,{className:`px-3 py-2 space-y-1.5 outline-none`,tabIndex:0,onKeyDown:rt,children:[pe.size>0&&(0,$.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-1 rounded-md border bg-muted/50 p-2 text-xs`,children:[...pe].map(([e,t])=>(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(P,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block`,children:t}),(0,$.jsx)(`span`,{className:`block truncate text-muted-foreground`,title:e,children:e})]})]},e))}),!u&&(0,$.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:it,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:J(`px-2 py-0.5 rounded-full border transition-colors select-none`,Ae?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:Ae?`Drag → Copy`:`Drag → Move`}),L&&!r&&!Ae&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>Ne(e=>(Pe.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:J(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,Me?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:Me?`+ merge down`:`merge down: off`})]}),at&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,$.jsx)(`span`,{children:W?`Source: ${W.path} · ${le.size} target(s)`:`Select source with ⌃-click`}),(0,$.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{ce(null),ue(new Map)},children:`clear`})]}),(0,$.jsxs)(`div`,{"data-active":o===`/`&&!g||void 0,className:J(`group relative flex min-h-11 items-center gap-2 rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all select-none`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,o===`/`&&!g?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,Ee===`/`&&!u&&!Oe&&`ring-2 ring-info bg-info-subtle/50`,Ee===`/`&&!u&&Oe&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>c(`/`),onDragEnter:e=>{u||He(`/`,e)},onDragOver:e=>{u||Ue(`/`,e)},onDragLeave:e=>We(`/`,e),onDrop:e=>{u||Ke(`/`,e)},onContextMenu:e=>{!u&&b&&(e.preventDefault(),fe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,$.jsx)(Xe,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,h&&(0,$.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,h,`]`]})]}),!u&&b&&(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 reveal-on-hover p-1 rounded hover:bg-muted-foreground/10 text-muted-foreground`,onClick:e=>{e.stopPropagation(),fe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,$.jsx)(vn,{className:`w-4 h-4`})})]}),(0,$.jsxs)(`div`,{className:H?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[we===`/`&&(0,$.jsx)(sL,{onConfirm:e=>et(`/`,e),onCancel:tt}),e.children?.map((t,n)=>(0,$.jsx)(uL,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...ot},t.id||t.name)),!e.children?.length&&we!==`/`&&(0,$.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),de&&(0,$.jsx)(oL,{x:de.x,y:de.y,node:de.node,path:de.path,isBackendsTree:r,backends:V,isDirectoryTree:n===`directory`,onClose:()=>fe(null),onShowContent:de.node.metadata?.backendTrash?c:_,onRestoreTrash:u?void 0:i,onDiscardTrash:u?void 0:a,onOpenToSide:v?e=>v(e,n):void 0,sourceLayer:W,targetLayers:le,clipboard:U,onStartInlineCreate:e=>Te(e),onChangeIcon:B?()=>Ye({clientX:de.x,clientY:de.y,stopPropagation:()=>{}},de.path,de.node):void 0,onNewCanvas:x,onShareCanvas:S,onExportSubtree:D,onImportSubtree:u?void 0:O,onRemove:!u&&C&&![...pe.keys()].some(e=>e===de.path||e.startsWith(de.path+`/`)||de.path.startsWith(e+`/`))?he:void 0,onRename:u?void 0:w,onLock:u?void 0:j,onUnlock:u?void 0:M,onDestroy:u?void 0:N,onMerge:u?void 0:F,onSubtract:u?void 0:I,onMergeDown:u?void 0:L,onSubtractDown:u?void 0:R,onResyncBackend:z,onAddRule:d,onAddStoreRule:f,onStoragePolicy:!u&&!r?p:void 0,onRenameBackendFolder:te,onDeleteBackendFolder:!u&&ne&&![...pe.keys()].some(e=>e===de.path||e.startsWith(de.path+`/`)||de.path.startsWith(e+`/`))?e=>he(e,!0):void 0,onCopy:e=>nt(e,`copy`),onCut:e=>nt(e,`cut`),onPaste:$e,pastedDocumentIds:k,onPasteDocuments:A,isPinned:re?re(de.path):!1,onTogglePin:ie?()=>ie(de.path,de.node):void 0}),ge&&B&&(0,$.jsx)(Zw,{x:ge.x,y:ge.y,current:ve.get(ge.path)??wm(ge.node),onChange:Ze,onClose:()=>_e(null)})]})}function fL(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=PT(),a=l_(),o=gl(),s=e.selectedEntityId,{showToast:c}=Vr(),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(`/`),[x,S]=(0,Q.useState)(null),[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(!1),k=(0,Q.useCallback)(async e=>{w(!0);try{let t=await gs(e);f(t),E(null)}catch(e){E(e instanceof Error?e.message:`Failed to load the tree`)}finally{w(!1)}},[]);(0,Q.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await Cs(e);if(t)return;u(n),m(n.url||``),g(void 0),v(``),S(null),b(n.path||`/`),w(!0);try{let n=await gs(e);t||(f(n),E(null))}catch(e){t||E(e instanceof Error?e.message:`Failed to load the tree`)}finally{t||w(!1)}}catch{t||c({title:`Error`,description:`Failed to load context`,variant:`destructive`})}}n();let r=t=>{t.detail?.contextId===e&&n()};return window.addEventListener(`contexts:refresh`,r),()=>{t=!0,window.removeEventListener(`contexts:refresh`,r)}},[s,c]);let A=jb({contextId:s??void 0,onRefresh:()=>{s&&k(s)}}),j=e=>{g(void 0),S(e),m(l?.workspaceName?`${l.workspaceName}://${e.replace(/^\//,``)}`:e)},M=l!=null&&(p.trim()!==(l.url||``)||h!==void 0);return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(QI,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>{s&&(a?i(`settings`,s):o(`/contexts/${s}/settings/general`))},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Settings`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})}),(0,$.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,$.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(ah,{presentation:`breadcrumbs`,value:p,fixedWorkspaceName:l?.workspaceName,pickerTitle:`Switch context to…`,onPickTarget:(e,t)=>{m(`${t.workspaceName}://${e.replace(/^\/+/,``)}`),g(t.treeName),S(null)},onChange:e=>{m(e),S(h?null:`/`+e.replace(/^.*?:\/\//,``).replace(/^\/+/,``))},disabled:D,className:`min-w-0 flex-1`,inputClassName:J(`text-xs transition-colors`,M&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,$.jsx)(Z,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;O(!0);try{await is(e,p,void 0,h);let t=await Cs(e);u(t),m(t.url||``),b(t.path||`/`),S(null),g(void 0),window.dispatchEvent(new CustomEvent(`contexts:refresh`)),await k(e),c({title:`Saved`,description:`Context URL updated`}),window.matchMedia(`(max-width: 767px)`).matches&&(n(),r())}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Save failed`,variant:`destructive`})}finally{O(!1)}},disabled:D||!M,children:D?`…`:`Set`})]})]}),h&&(0,$.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,h,` · press Set to apply`]}),(0,$.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,$.jsx)(Y,{type:`search`,name:`context-tree-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search context tree`,placeholder:`Search paths…`,value:_,onChange:e=>v(e.target.value),className:`h-7 text-xs`})}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,$.jsxs)(`div`,{className:`text-[10px] text-muted-foreground px-3 pt-2 pb-1 font-medium uppercase tracking-wide shrink-0`,children:[l?.workspaceName||`Workspace`,` · `,d?.type===`directory`?`directory`:`context`,` tree`]}),T&&!d&&(0,$.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:T}),(0,$.jsx)(dL,{root:d,workspaceId:l?.workspaceName,searchQuery:_,selectedPath:y,pendingPath:x,onSelect:j,isLoading:C,rootLabel:l?.workspaceName,...A})]})]})}function pL({items:e,activeId:t,onSelect:n}){let[r,i]=(0,Q.useState)(``),a=e.filter(e=>dT(r,e.label,e.description||``));return(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,$.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,$.jsx)(Y,{type:`search`,name:`settings-section-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,$.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No matching settings.`}),a.map(e=>{let r=e.id===t;return(0,$.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:J(`flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left transition-colors`,r?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50 hover:text-foreground`),children:[(0,$.jsx)(`span`,{className:J(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,$.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,$.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,$.jsx)(hr,{className:J(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}function mL(){let{state:e,closeM2:t}=PT(),n=l_(),r=gl(),i=pl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return Cs(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?HO(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,Q.useMemo)(()=>VO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>u&&r(u),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open context`,children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),(0,$.jsx)(pL,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function hL(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Ni();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>hd.emit(`subscribe`,{channel:`workspace`}),r=()=>hd.emit(`unsubscribe`,{channel:`workspace`}),i=hd.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e,r=t?.workspaceId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},o=e=>{let t=e?.workspace??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},c=e=>{let t=e,r=t?.workspaceId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=[[`workspaces.scanned`,e=>{let t=e?.report;t&&(t.discovered.length||t.adopted.length||t.updated.length||t.missing.length)&&s()}],[`workspace:status:changed`,a],[`workspace.status.changed`,a],[`workspace:created`,o],[`workspace.created`,o],[`workspace:deleted`,c],[`workspace.deleted`,c]];return l.forEach(([e,t])=>hd.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>hd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,Q.useMemo)(()=>JT(t),[t]),isLoading:r,refresh:c}}function gL({status:e}){return(0,$.jsx)(`span`,{className:J(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function _L(){let e=Gw(),{state:t,selectEntity:n,openM2:r,closeM2:i}=PT(),a=l_(),{workspaces:o,isLoading:s}=hL(t.activeSection===`workspaces`),{showToast:c}=Vr(),l=gl(),[u,d]=(0,Q.useState)(new Set),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(new Map),_=(0,Q.useRef)(new Map),[v,y]=(0,Q.useState)(null),b=v&&v.base===o?v.order:o,{rowProps:x,handleProps:S,draggingIndex:C,insertLineClass:w}=ZT((e,t)=>{let n=YT(b,e,t);y({base:o,order:n}),XT(n,(e,t)=>Eo(Kw(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&c({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),E=e=>h.get(Kw(e))??{icon:e.icon??void 0,color:e.color??void 0},D=(e,t,n)=>{let r={...t,...n};g(t=>new Map(t).set(e,r));let i=_.current,a=i.get(e);a&&clearTimeout(a),i.set(e,setTimeout(()=>{i.delete(e);let t={icon:r.icon??null};r.color&&(t.color=r.color),Eo(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>c({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},O=e=>{n(Kw(e)),r(`detail`,Kw(e)),!a&&sT(Kw(e))&&l(cT(Kw(e)))},k=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(Kw(t)));try{await so(Kw(t)),c({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(Kw(t)),n})}},A=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(Kw(t)));try{await ha(Kw(t)),c({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){c({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(Kw(t)),n})}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(XI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`})]}),!e.local&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{i(),l(`/workspaces?create=1`)},title:`Create workspace`,"aria-label":`Create workspace`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,$.jsx)(`div`,{className:`space-y-1.5 px-2`,children:b.map((e,i)=>{let o=t.selectedEntityId===Kw(e),s=Op(e),c=u.has(Kw(e)),d=e.status!==`active`,p=E(e),h=Nm(p.color);return(0,$.jsxs)(`div`,{...x(i),"data-active":o||void 0,className:J(`group relative rounded-(--card-radius) py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,o?`bg-accent shadow cursor-pointer hover:shadow`:d?`bg-card opacity-60 cursor-not-allowed`:`bg-card hover:bg-accent/50 cursor-pointer hover:shadow`,w(i,b.length),C===i&&`opacity-60`),onClick:()=>{d||O(e)},children:[(0,$.jsx)(`button`,{type:`button`,...S(i),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:J(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-(--card-radius) active:cursor-grabbing`,!h&&`bg-muted`),style:h?{backgroundColor:h}:void 0,children:(0,$.jsx)(T,{className:J(`h-3.5 w-3.5`,Pm(h))})}),(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,title:s?`Change icon`:`Workspace appearance requires admin access`,onClick:t=>{!s||br()||(t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Kw(e)}))},onContextMenu:t=>{s&&(t.preventDefault(),t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Kw(e)}))},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,$.jsx)(f,{icon:p.icon||`ph:stack-fill`,width:18,height:18,color:h,className:J(!h&&`text-muted-foreground`)})}),(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(gL,{status:e.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,$.jsx)(`button`,{type:`button`,disabled:c,onClick:t=>A(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,$.jsx)(zn,{className:`w-3.5 h-3.5`})}):(0,$.jsx)(`button`,{type:`button`,disabled:c,onClick:t=>k(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,$.jsx)(xe,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(Kw(e)),a?r(`settings`,Kw(e)):l(`/workspaces/${Kw(e)}/settings/general`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,disabled:!s,title:s?`Settings`:`Workspace settings require admin access`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,$.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),p&&(()=>{let e=o.find(e=>Kw(e)===p.name);if(!e)return null;let t=E(e);return(0,$.jsx)(Zw,{x:p.x,y:p.y,current:t,onChange:e=>D(p.name,t,e),onClose:()=>m(null)})})()]})}function vL(e,t){let n=(0,Q.useRef)(null),r=(0,Q.useRef)(0);return(0,Q.useEffect)(()=>{if(!e)return;let n=e=>{if(e.defaultPrevented||e.repeat||e.isComposing||e.getModifierState(`AltGraph`))return;let n=e.target;if(n instanceof Element&&n.closest(`input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="dialog"], [role="alertdialog"]`)||document.querySelector(`[aria-modal="true"], dialog[open]`))return;let r=rj(e);if(!r)return;let i=tj(),a=r===i.previousTree?-1:+(r===i.nextTree);a&&(e.preventDefault(),t(a))};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),{onTouchStart(e){r.current=0,n.current=e.touches.length===1?{x:e.touches[0].clientX,y:e.touches[0].clientY}:null},onTouchMove(e){e.touches.length!==1&&(n.current=null)},onTouchCancel(){n.current=null},onTouchEnd(i){if(!n.current||!e)return;let a=i.changedTouches[0],o=aj(a.clientX-n.current.x,a.clientY-n.current.y);n.current=null,o&&(r.current=Date.now()+500,i.stopPropagation(),t(o))},onClickCapture(e){Date.now()<r.current&&(e.preventDefault(),e.stopPropagation(),r.current=0)}}}function yL(e,t,n,r=!1){if(!t.startsWith(`/`)||!n.length)throw Error(`Choose a source folder and at least one destination.`);let i=new Map;for(let e of n){if(![`context`,`directory`].includes(e.tree)||!e.path.startsWith(`/`))throw Error(`Choose a context or directory destination.`);if(e.path.includes(`{{`))throw Error(`Auto-Link destinations cannot contain {{ template markers.`);i.set(`${e.tree}:${e.path}`,e)}return{id:e,enabled:!0,description:`Auto-Link backends:${t} → ${[...i.keys()].join(`, `)}`,cascade:!0,when:{event:[`document.inserted`,`document.updated`,`document.linked`],...r?{path:`backends:${t}`}:{pathExact:`backends:${t}`}},then:[...i.values()].map(e=>({action:`link`,paths:[`${e.tree===`context`?`ctx`:`dir`}:${e.path}`],...r?{recursive:!0}:{}}))}}function bL(e,t,n,r=!1,i=`forward`,a=`copy`,o,s){let c=yL(e,t,n,r);if(i===`forward`)return[c];if(a===`move`&&!s?.trim())throw Error(`Choose the source backend whose copy should be moved.`);if(r&&n.some(e=>e.tree===`context`))throw Error(`Recursive storage requires a directory source. Context paths can store files in a fixed backend folder.`);let l=t.split(`/`).filter(Boolean);if(l.length<2||t.includes(`{{`)||l.some(e=>e===`.`||e===`..`))throw Error(`Choose a backend folder with a valid storage address.`);if(!o)throw Error(`Choose a writable backend folder.`);let u=o.address,d=o.key,f=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],p={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${f.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:f.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:u,folder:d,mode:a,...a===`move`?{from:s.trim()}:{},autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[c,p]:[p]}function xL(e,t){let n=as(e,t);if(t.find(e=>e.driver===n.driver&&e.address===n.address)?.capabilities.paths!==!0)throw Error(`This backend has not reported support for folder paths. Choose a writable storage folder to copy or move files here.`);return n}function SL({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(`forward`),u=c===`forward`||!i.some(e=>e.tree===`context`),[d,f]=(0,Q.useState)(`copy`),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)(!0),[y,b]=(0,Q.useState)(0),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(!0),[T]=(0,Q.useState)(()=>`autolink-${crypto.randomUUID()}`),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(0),[I,L]=(0,Q.useState)(0),[R,z]=(0,Q.useState)(0),[ee]=(0,Q.useState)(pp),[te,ne]=(0,Q.useState)(1),[B,re]=(0,Q.useState)(0),[ie,ae]=(0,Q.useState)(),[oe,V]=(0,Q.useState)(0),H=()=>{O||n()},U=_?`Checking whether this backend can receive files…`:``;if(!_)try{xL(t,h)}catch(e){U=e instanceof Error?e.message:`Choose a writable storage folder.`}let se=e=>{l(e),e!==`forward`&&(w(!1),i.some(e=>e.tree===`context`)&&S(!1))},W=e=>`${e.replace(/\/+$/,``)}/${x?`Subfolder/`:``}example.pdf`;return(0,Q.useEffect)(()=>{let t=!1;return pa(e).then(e=>{t||g(e)}).catch(()=>{t||N(`Could not load storage backends. Reopen Autolink to retry.`)}).finally(()=>{t||v(!1)}),()=>{t=!0}},[e]),(0,$.jsx)(Lp,{label:o?`Choose virtual paths`:`Autolink documents`,onClose:o?()=>s(!1):H,children:o?(0,$.jsx)(ih,{fixedWorkspaceName:e,tabs:c!==`forward`&&x?[`directory`]:[`context`,`directory`],initialTab:c===`forward`?void 0:`directory`,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-full rounded-none border-0 shadow-none`,onClose:()=>s(!1),onConfirm:(e,t)=>{c!==`forward`&&t.treeType===`context`&&S(!1),a(n=>{let r=[...n];for(let n of e)r.some(e=>e.tree===t.treeType&&e.path===n)||r.push({tree:t.treeType,path:n});return r}),s(!1)}}):(0,$.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b p-5`,children:[(0,$.jsxs)(`h2`,{className:`flex items-center gap-2 text-lg font-semibold`,children:[(0,$.jsx)(Zt,{className:`h-5 w-5`}),`Autolink documents`]}),(0,$.jsx)(`button`,{type:`button`,onClick:H,disabled:O,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-5`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Current backend folder`}),(0,$.jsxs)(`p`,{className:`mt-1 break-words text-sm`,children:[`backends:`,t]})]}),(0,$.jsxs)(`fieldset`,{disabled:O||E,className:`space-y-2 text-sm`,children:[(0,$.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,$.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>se(e.target.value),children:[(0,$.jsx)(`option`,{value:`forward`,children:`Backend → virtual folders (link)`}),(0,$.jsx)(`option`,{value:`reverse`,disabled:!!U,children:`Virtual folders → backend (Copy/Move)`}),(0,$.jsx)(`option`,{value:`both`,disabled:!!U,children:`Both directions`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link documents from this backend folder into the selected virtual folders. Files stay where they are.`:`When a document is added or explicitly linked to a selected virtual folder, ${d} its file to the current backend folder.${c===`both`?` Documents arriving on the backend are also linked into the virtual folders.`:``}`}),U&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:_?U:`Reverse mapping unavailable: ${U}`}),c!==`forward`&&(0,$.jsxs)(`div`,{className:`space-y-2 rounded-lg border p-3`,children:[(0,$.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-operation`,children:`File operation`}),(0,$.jsxs)(`select`,{id:`autolink-operation`,className:`w-full rounded-md border bg-background p-2`,value:d,onChange:e=>f(e.target.value),children:[(0,$.jsx)(`option`,{value:`copy`,children:`Copy files to this backend`}),(0,$.jsx)(`option`,{value:`move`,children:`Move files to this backend`})]}),d===`copy`&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Keep the source file and its virtual-folder links.`}),d===`move`&&(0,$.jsxs)(`div`,{className:`mt-2 space-y-2`,children:[(0,$.jsx)(`label`,{className:`block`,htmlFor:`autolink-source-backend`,children:`Move files from`}),(0,$.jsxs)(`select`,{id:`autolink-source-backend`,className:`w-full rounded-md border bg-background p-2`,value:p,onChange:e=>m(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:`Choose a source backend…`}),h.filter(e=>e.kind===`storage`&&e.enabled&&e.config?.readOnly!==!0).map(e=>(0,$.jsx)(`option`,{value:e.address,children:e.address},e.address))]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Move the file from this source backend after it has been stored at the destination. Virtual-folder links stay in place. Files missing from this source are skipped; multiple source copies require Copy instead.`})]})]})]}),(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`h3`,{className:`text-sm font-medium`,children:c===`reverse`?`Watch virtual folders`:`Virtual folders`}),i.map((e,t)=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,$.jsx)(`p`,{className:`break-words`,children:e.path})]}),!E&&(0,$.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:O,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(G,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),!E&&(0,$.jsxs)(Z,{variant:`outline`,size:`sm`,disabled:O,onClick:()=>s(!0),children:[(0,$.jsx)(sn,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Choose the virtual folders where backend documents should appear.`:`Choose a Directory tree folder to watch for newly added documents. Its files will be stored in the current backend folder.`})]}),(0,$.jsxs)(`fieldset`,{disabled:O||E,className:`space-y-3 text-sm`,children:[(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:x,disabled:!u,onChange:e=>S(e.target.checked),className:`mt-1`}),`Include subfolders and recreate their path in the destination`]}),!u&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Context membership has no single folder path. To preserve subfolders on a backend, choose a directory source. Context paths store files directly in the selected backend folder.`}),(0,$.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),!!i.length&&(0,$.jsxs)(`div`,{className:`space-y-3 rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`Mapping preview`,children:[(0,$.jsx)(`h3`,{className:`font-medium`,children:`Example result`}),i.map(e=>(0,$.jsxs)(`div`,{className:`space-y-2 break-all text-xs`,children:[c!==`reverse`&&(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Link `}),`backends:`,W(t),(0,$.jsx)(`br`,{}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`Into `}),e.tree===`context`?`ctx`:`dir`,`:`,W(e.path)]}),c!==`forward`&&(0,$.jsxs)(`p`,{children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground`,children:[d===`move`?`Move`:`Copy`,` `]}),e.tree===`context`?`ctx`:`dir`,`:`,W(e.path),(0,$.jsx)(`br`,{}),(0,$.jsx)(`span`,{className:`text-muted-foreground`,children:`To `}),`backends:`,W(t)]})]},`preview:${e.tree}:${e.path}`)),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:x?`The selected folders are the roots. Only the subfolder path beneath each root is recreated at its destination.`:`Only direct folder contents are included.`})]}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[C?`Existing matching documents are processed when you enable this rule.`:c===`forward`?`Future backend arrivals and updates are linked automatically.`:`Newly added or explicitly linked virtual-folder documents are processed automatically.`,` `,c===`both`&&`Both directions creates two rules in workspace Rules. `,`Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`]}),O&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm`,children:E?`${te>1?`Rule ${Math.min(y+1,te)}/${te}: `:``}Processing ${B}${ie===void 0?``:`/${ie}`} existing documents… ${I} matches applied.`:`Saving Auto-Link…`}),A&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Auto-Link is enabled for future documents.`,C?` ${oe} document${te>1?` checks across ${te} rules`:`s checked`}. ${I} matches applied.`:``]}),R>0&&(0,$.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[R,` document operations failed. Check the rule’s run log in Rules and rerun it after resolving the errors.`]}),M&&(0,$.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[E?`Auto-Link is enabled. `:``,M]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,$.jsx)(Z,{variant:`ghost`,disabled:O,onClick:r,children:`Manage rules`}),A?(0,$.jsx)(Z,{onClick:n,children:`Done`}):(0,$.jsx)(Z,{disabled:O||!i.length||c!==`forward`&&(!!U||d===`move`&&!p),onClick:async()=>{if(!O){k(!0),N(``);try{let n=c===`forward`?void 0:xL(t,await pa(e)),r=bL(T,t,i,x,c,d,n,p);if(ne(r.length),E||(await Sp(e,r),D(!0)),C){for(let t=y;t<r.length;t++){let n=t===y?P:0;re(n),ae(void 0);let i=await gp(e,{ruleId:r[t].id,limit:1,offset:n,dryRun:!0});for(ae(i.total);n!==null;){let i=await gp(e,{ruleId:r[t].id,limit:ee,offset:n});if(L(e=>e+i.matched-i.failed),z(e=>e+i.failed),re(n+i.processed),V(e=>e+i.processed),ae(i.total),i.nextOffset===void 0)throw Error(`The rule is enabled, but applying the full folder needs an updated server. Use Rules to rerun existing documents after updating.`);n=i.nextOffset,n!==null&&F(n)}b(t+1),F(0)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}j(!0)}catch(e){N(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{k(!1)}}},children:O?`Applying…`:E?`Retry existing documents`:`Enable Autolink`})]})]})})}async function CL(){return await X.get(`${Lr}/users/me/config/webui`)??{}}async function wL(e){return await X.put(`${Lr}/users/me/config/webui`,e)??e}var TL=`application/x-canvas-workspace-pin`;function EL({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:i,onShowInTree:a,onUnpin:o,onMove:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),p=n.toLowerCase().trim(),m=p?e.filter(e=>(e.label||e.name||``).toLowerCase().includes(p)||e.path.toLowerCase().includes(p)||(e.description||``).toLowerCase().includes(p)):e,h=()=>{l(null),d(null)},g=async()=>{let t=u,n=c;if(h(),!n||!t||t.id===n)return;let r=t.id;if(t.id&&!t.before&&(r=e[e.findIndex(e=>e.id===t.id)+1]?.id??null),r!==n)try{await s(n,r)}catch(e){alert(e instanceof Error?e.message:String(e))}};return t&&!e.length?(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,$.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{c&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),c&&!u&&d({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=Nm(e.color),s=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===ei(e.tree,e.path),_=u?.id===e.id&&u.before,v=u?.id===e.id&&!u.before;return(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(TL,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,l(e.id)},onDragEnd:h,onDragOver:t=>{if(!c||c===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;d(t=>t?.id===e.id&&t.before===r?t:{id:e.id,before:r})},onDrop:e=>{e.preventDefault(),e.stopPropagation(),g()},onClick:()=>{t||i(e)},onKeyDown:n=>{n.target===n.currentTarget&&(n.key===`Enter`||n.key===` `)&&!t&&(n.preventDefault(),i(e))},title:t?`${e.path} — folder no longer exists`:`Open ${e.tree}:${e.path}`,className:J(`group relative flex items-stretch gap-2.5 rounded-(--card-radius) border bg-card shadow-elevation-1 text-left transition-colors`,t?`opacity-70 cursor-default`:`cursor-pointer hover:bg-accent/40`,m&&`ring-1 ring-primary/60`,c===e.id&&`opacity-40`,_&&`border-t-2 border-t-primary`,v&&`border-b-2 border-b-primary`),style:{borderLeft:`5px solid ${n??`transparent`}`},children:[(0,$.jsx)(`div`,{className:`flex items-center justify-center w-12 shrink-0 rounded-l-[5px] my-0 self-stretch`,style:n?{backgroundColor:`${n}22`}:void 0,children:t?(0,$.jsx)(W,{className:`w-5 h-5 text-warning`}):(0,$.jsx)(f,{icon:s,width:22,height:22,color:n,className:J(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,$.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,$.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,$.jsx)(Vn,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,$.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,$.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,$.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,$.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:t=>{t.stopPropagation(),a(e)},title:`Show in tree`,"aria-label":`Show in tree`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover focus-visible:opacity-100 hover:bg-accent hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-default`,children:(0,$.jsx)(ne,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:async t=>{t.stopPropagation();try{await o(e)}catch(e){alert(e instanceof Error?e.message:String(e))}},title:`Unpin`,"aria-label":`Unpin`,className:`flex items-center justify-center w-6 h-6 rounded text-muted-foreground reveal-on-hover hover:bg-destructive/10 hover:text-destructive transition-colors`,children:(0,$.jsx)(ee,{className:`w-3.5 h-3.5`})})]}),!p&&(0,$.jsx)(T,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,$.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,$.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,$.jsx)(`p`,{children:`No pinned folders yet.`}),(0,$.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,$.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var DL=[`pins`,`context`,`layers`,`directory`,`backends`],OL=e=>typeof e==`string`&&DL.includes(e),kL=e=>{let t=Array.isArray(e)?e.filter(OL).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...DL.filter(e=>!t.includes(e))]},AL={pins:(0,$.jsx)(Oe,{className:`w-3.5 h-3.5`}),context:(0,$.jsx)(ae,{className:`w-3.5 h-3.5`}),layers:(0,$.jsx)(ur,{className:`w-3.5 h-3.5`}),directory:(0,$.jsx)(ne,{className:`w-3.5 h-3.5`}),backends:(0,$.jsx)(er,{className:`w-3.5 h-3.5`})},jL={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},ML=e=>e===`directory`||e===`backends`?e:lo,NL=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function PL(){let{state:e}=PT();return e.selectedEntityId?(0,$.jsx)(pE,{workspaceName:e.selectedEntityId,children:(0,$.jsx)(FL,{},e.selectedEntityId)}):null}function FL(){let{state:e,closeM2:t,openM2:n,navigateFromMenu:r}=PT(),i=gy(),a=l_(),o=e.selectedEntityId,s=gl(),c=pl(),{treeName:l,path:u}=Px(c.pathname),d=new URLSearchParams(c.search).get(`layer`)===`1`,f=new URLSearchParams(c.search).get(`layerId`),p=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!f,m=p?NL(l,f):DL[0],[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)({icon:null,color:null}),[C,w]=(0,Q.useState)(m),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)([]),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),[z,ee]=(0,Q.useState)(!1),[te,ne]=(0,Q.useState)(u),[B,re]=(0,Q.useState)([]),[ie,ae]=(0,Q.useState)(new Set),[oe,V]=(0,Q.useState)(d&&u!==`/`?u:null),[H,U]=(0,Q.useState)(``),[se,W]=(0,Q.useState)(null),[ce,le]=(0,Q.useState)(null),[ue,de]=(0,Q.useState)(null),{policies:fe,refresh:pe}=hF(o),me=(0,Q.useCallback)(e=>{if(C!==`context`&&C!==`directory`||!fe.length)return null;let t=tF(fe,C,e);return t.length?`Storage policy targets: ${nF(t)} (see Settings for transfer status)`:null},[C,fe]),[G,he]=(0,Q.useState)([]),[ge,_e]=(0,Q.useState)(!1),[ve,K]=(0,Q.useState)(!1),q=(0,Q.useRef)(null),ye=(0,Q.useRef)(!1),[be,xe]=(0,Q.useState)(!1),[Se,Ce]=(0,Q.useState)(DL),we=!p;(0,Q.useEffect)(()=>{let e=!1;return CL().then(t=>{if(e)return;let n=kL(t?.m2?.tabOrder);Ce(n),we&&w(e=>e===DL[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let Te=(0,Q.useCallback)(async e=>{let t=Se;Ce(e);try{let t=await CL();await wL({...t,m2:{...t.m2,tabOrder:e}})}catch{Ce(t)}},[Se]),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)(null),Ae=()=>{De(null),ke(null)},je=()=>{if(Ee&&Oe&&Ee!==Oe.id){let e=Se.filter(e=>e!==Ee),t=e.indexOf(Oe.id);t>=0&&(e.splice(Oe.before?t:t+1,0,Ee),e.some((e,t)=>e!==Se[t])&&Te(e))}Ae()};(0,Q.useEffect)(()=>{let e=e=>W(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[Me,Ne]=(0,Q.useState)(u);u!==Me&&(Ne(u),ne(u));let Pe=(0,Q.useRef)(new Map),Fe=(0,Q.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();Pe.current.set(t,i);let a=()=>Pe.current.get(t)===i,o=t===`context`?P:t===`directory`?I:R,s=t===`context`?E:t===`directory`?O:A;n||o(!0);try{n&&!r&&Da(e,t);let i=await vi(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ie=(0,Q.useCallback)(async(e,t=!1)=>{let n=Symbol();Pe.current.set(`pins`,n);let r=()=>Pe.current.get(`pins`)===n;t||_e(!0);try{let t=await Ai(e);r()&&he(t)}catch{}finally{r()&&_e(!1)}},[]),Le=(0,Q.useCallback)(async(e,t=!1)=>{let n=Symbol();Pe.current.set(`layers`,n);let r=()=>Pe.current.get(`layers`)===n;t||ee(!0);try{let t=await oi(e,`context`);r()&&M(t)}catch{}finally{r()&&ee(!1)}},[]);(0,Q.useEffect)(()=>{if(!o)return;let e=o,t=!1,n=Pe.current;async function r(){qr(e).then(e=>{t||(v(e.label||e.name),g(Op(e)),b(e.id||null),S({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Fe(e,`context`),Fe(e,`directory`),Fe(e,`backends`),Le(e),Ie(e)])}return r(),()=>{t=!0,n.clear()}},[o,Fe,Le,Ie]);let Re=(0,Q.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Fe(e,r,!0,n);(!t||t===`context`)&&Le(e,!0),Ie(e,!0)},[Fe,Le,Ie]),ze=(0,Q.useCallback)(()=>{o&&Re(o)},[o,Re]);(0,Q.useEffect)(()=>{if(!o)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==o||Re(o,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[o,Re]),(0,Q.useEffect)(()=>{if(!o)return;let e=!1,t=()=>pa(o).then(t=>{e||(re(t),ae(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath))))}).catch(()=>{});t();let n=e=>{let n=e.detail;n?.workspaceName&&n.workspaceName!==o||(!n?.treeName||n.treeName===`backends`)&&t()};return window.addEventListener(`workspace:tree:refresh`,n),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,n)}},[o]),(0,Q.useEffect)(()=>{if(!o)return;let e=[`workspace:${o}`,y?`workspace:${y}`:null].filter(Boolean),t=()=>e.forEach(e=>hd.emit(`subscribe`,{channel:e})),n=hd.on(`connect`,t);t();let r=Ab(o,y),i=e=>{if(e?.workspaceId&&y&&e.workspaceId!==y)return;let t=e?.treePath;t&&ae(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};hd.on(`backend.resync.changed`,i);let a=e=>{e?.workspaceId&&y&&e.workspaceId!==y||Ie(o,!0)};return hd.on(`pins.changed`,a),()=>{r(),n?.(),hd.off(`backend.resync.changed`,i),hd.off(`pins.changed`,a)}},[o,y,Ie]);let[Be,Ve]=(0,Q.useState)(null),He=`${c.pathname}|${c.search}`;if(He!==Be){Ve(He);let{treeName:e,path:t}=Px(c.pathname),n=new URLSearchParams(c.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(c.pathname)||!!n;ve?K(!1):w(r||be?r?NL(e,n):C:Se[0]),ne(t),V(t===`/`?null:t)}let{showProgress:Ue}=Vr(),We=jb({workspaceId:o??void 0,treeName:ML(C),onRefresh:ze}),Ge=new Set(G.map(e=>ei(e.tree,e.path))),Ke=ML(C),qe=(0,Q.useCallback)(e=>Ge.has(ei(Ke,e)),[G,Ke]),Je=(0,Q.useCallback)(async e=>{if(!o)return;let t=G.find(t=>ei(t.tree,t.path)===ei(Ke,e));t?await oa(o,t.id):await Yi(o,e,Ke),await Ie(o)},[o,G,Ke,Ie]),Ye=(0,Q.useCallback)(async e=>{if(o){he(t=>t.filter(t=>t.id!==e.id));try{await oa(o,e.id)}finally{await Ie(o)}}},[o,Ie]),Xe=(0,Q.useCallback)(async(e,t)=>{if(!o)return;let n=G.find(t=>t.id===e);if(!n)return;let r=G.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let a=[...r.slice(0,i),n,...r.slice(i)];if(!a.every((e,t)=>e===G[t])){he(a);try{he(await Fi(o,a.map(e=>e.id)))}catch(e){throw await Ie(o),e}}},[o,G,Ie]),Ze=(0,Q.useCallback)(e=>{if(!o)return;K(!0),ne(e.path),V(null);let t=Fx(o,e.path,e.tree);if(i){i.activateRow(`pin:${o}:${e.id}`,e.label||e.name||e.path,t);return}r(t)},[o,r,i]),Qe=(0,Q.useCallback)(e=>{!o||e.resolvable===!1||(K(!1),xe(!0),w(NL(e.tree)),ne(e.path),V(null),U(``),ye.current=!0,i?.setFocus(`main`),r(Fx(o,e.path,e.tree)))},[o,r,i]),$e=C===`context`?T:C===`directory`?D:C===`backends`?k:null,et=C===`context`?N:C===`directory`?F:C===`backends`&&L;(0,Q.useEffect)(()=>{if(!ye.current||et||C===`pins`)return;let e=q.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),ye.current=!1)},[C,te,$e,et]);let tt=(0,Q.useCallback)(e=>{xe(!0),w(e),ne(`/`),V(null),U(``)},[]),nt=(0,Q.useCallback)(e=>{tt(ij(Se,C,e))},[Se,C,tt]),rt=vL(e.m2Open,nt),it=e=>{V(null),ne(e);let t=ML(C);i?.setFocus(`main`),r(Fx(o,e,t))},at=(0,Q.useCallback)((e,t)=>{ne(e),V(e);let n=ML(C),a=new URLSearchParams;a.set(`layer`,`1`),t&&a.set(`layerId`,t),i?.setFocus(`main`),r(`${Fx(o,e,n)}?${a.toString()}`)},[o,C,r,i]),ot=(0,Q.useCallback)((e,t)=>{if(o){if(i){i.openCanvas({kind:`route`,location:Fx(o,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:t,path:e}}))}},[o,i]),st=(0,Q.useCallback)(async e=>{if(!o)return;let t=ML(C),n=await To(o,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[o,C]),ct=H.toLowerCase().trim(),lt=ct?j.filter(e=>e.name.toLowerCase().includes(ct)||(e.label||``).toLowerCase().includes(ct)||(e.description||``).toLowerCase().includes(ct)):j;return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(QI,{title:_||o||`Workspace`,icon:x.icon||`ph:stack-fill`,accentColor:x.color,onBack:t,action:(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>o&&r(cT(o)),className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Open workspace`,children:(0,$.jsx)(Ht,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,disabled:!h,onClick:()=>{a?n(`settings`,o??null):s(`/workspaces/${o}/settings/general`)},className:`flex items-center justify-center w-8 h-8 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,title:h?`Settings`:`Workspace settings require admin access`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})}),(0,$.jsx)(`div`,{...rt,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:Se.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>tt(e),title:`${jL[e]} — drag to reorder; the first tab opens by default`,"aria-label":jL[e],"aria-pressed":C===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,De(e)},onDragEnd:Ae,onDragOver:t=>{if(!Ee||Ee===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;ke(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),je()},className:J(`relative flex-1 flex items-center justify-center py-2 transition-colors`,C===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,Ee===e&&`opacity-40`,Oe?.id===e&&Oe.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Oe?.id===e&&!Oe.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[AL[e],e===`pins`&&G.length>0&&(0,$.jsx)(`span`,{className:`absolute top-1 right-[calc(50%-14px)] min-w-[14px] h-[14px] px-0.5 rounded-full bg-primary text-primary-foreground text-[9px] leading-[14px] text-center font-medium`,children:G.length})]},e))}),(0,$.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,$.jsx)(tr,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,$.jsx)(`input`,{type:`search`,name:`workspace-tree-filter`,"aria-label":`Search workspace tree`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:C===`layers`?`Search layers…`:C===`pins`?`Search pins…`:`Search paths…`,value:H,onChange:e=>U(e.target.value)})]})}),(0,$.jsx)(`div`,{ref:q,className:`flex-1 overflow-y-auto`,children:C===`pins`?(0,$.jsx)(EL,{pins:G,isLoading:ge,searchQuery:H,activeKey:ei(l,u),onOpen:Ze,onShowInTree:Qe,onUnpin:Ye,onMove:Xe}):C===`layers`?(0,$.jsx)(HL,{layers:lt,isLoading:z,wsName:o??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),r(`${Fx(o,`/`)}?${t.toString()}`)},onLock:async e=>{await ci(o,e.id,o,`context`),Re(o)},onUnlock:async e=>{await Ea(o,e.id,o,`context`),Re(o)},onRename:async(e,t)=>{await ia(o,e.id,t,`context`),Re(o)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await Jr(o,e.id,`context`),Re(o))}}):(0,$.jsx)(dL,{root:$e,workspaceId:o??void 0,treeName:C,isBackendsTree:C===`backends`,onRestoreTrash:o?e=>xb(o,e):void 0,onDiscardTrash:o?e=>Cb(o,e):void 0,onShiftSelect:i?e=>ot(e,ML(C)):void 0,selectedPath:te,contentPath:oe,onSelect:it,onShowContent:C===`context`?at:void 0,onOpenToSide:ot,onShareCanvas:st,onNewCanvas:o&&C!==`backends`?e=>{s(`${Fx(o,e,C)}?createCanvas=1`)}:void 0,isLoading:et,rootLabel:o??void 0,searchQuery:H,backends:B,resyncingPaths:C===`backends`?ie:void 0,onAddRule:o&&C===`backends`?le:void 0,onAddStoreRule:o?(e,t=`store`)=>{let n=C===`backends`?(()=>{let n=ep(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${C===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:np(e)};s(`/workspaces/${o}/settings/hooks?${tp(n).toString()}`)}:void 0,onStoragePolicy:o&&(C===`context`||C===`directory`)?e=>de(KP(C,e)):void 0,policyBadgeFor:me,pastedDocumentIds:se?.documentIds,isPathPinned:qe,onTogglePin:o?Je:void 0,onPasteDocuments:o&&C===`backends`?async(e,t)=>{let n=ho(e);if(!n)return!1;let r=e.split(`/`).filter(Boolean).slice(2).join(`/`),i=Ue({title:`Moving…`,description:`${t.length} message(s) → ${r}`});try{let{moved:a,results:s}=await Li(o,n.address,t,e),c=s.filter(e=>!e.ok);return c.length?i.fail({title:`${c.length} message(s) not moved`,description:c[0].error||`Move failed`,variant:`destructive`}):i.done({title:`Moved`,description:`${a} message(s) → ${r}`}),se&&a&&(W(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:`/imap/${n.address}`,treeName:`backends`}})),a>0}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to move messages`,variant:`destructive`}),!1}}:o?async(e,t)=>{let n=C===`directory`?`directory`:`context`,r=C===`directory`?`directory`:lo,i=Ue({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),a=!1;try{a=await Qr(o,e,t,r,n)}catch(e){return i.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}return i.done(a?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),a&&(se&&(W(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:o,path:e,treeName:r}}))),a}:void 0,...We})}),ce&&o&&(0,$.jsx)(SL,{workspaceId:o,sourcePath:ce,onClose:()=>le(null),onManageRules:()=>{le(null),s(`/workspaces/${o}/settings/hooks?section=rules`)}}),ue&&o&&(0,$.jsx)(oF,{workspaceId:o,path:ue,onClose:()=>de(null),onSaved:()=>{pe()}})]})}var IL={canvas:{label:`Canvases`,order:0},dataset:{label:`Datasets`,order:1},context:{label:`Context layers`,order:2},workspace:{label:`Workspaces`,order:3},universe:{label:`Universe`,order:4},label:{label:`Labels`,order:5},system:{label:`System`,order:6}},LL=100,RL=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),zL=e=>IL[e]??{label:`${RL(e)} layers`,order:LL};function BL({type:e}){return e===`canvas`?(0,$.jsx)(gt,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,$.jsx)(er,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,$.jsx)(ur,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function VL(e){let t=new Map;for(let n of e){let e=n.type||`context`,r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t.entries()].map(([e,t])=>({type:e,items:t,meta:zL(e)})).sort((e,t)=>e.meta.order-t.meta.order||e.meta.label.localeCompare(t.meta.label)).map(({type:e,items:t,meta:n})=>({type:e,label:n.label,items:t}))}function HL({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(null);if((0,Q.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,$.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No layers found`});let u=async(e,t)=>{e.stopPropagation();try{await t()}catch(e){alert(e instanceof Error?e.message:String(e))}},d=async(e,t)=>{c(null);let n=t.trim();if(!(!n||n===e.name))try{await a(e,n)}catch(e){alert(e instanceof Error?e.message:String(e))}},f=VL(e);return(0,$.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,$.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,$.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,$.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-l-md px-2 py-1.5 text-xs bg-card shadow-elevation-1 cursor-pointer hover:bg-accent/40 transition-colors`,style:{borderRight:e.color?`4px solid ${e.color}`:`4px solid transparent`},onClick:()=>s!==e.id&&n(e),children:[(0,$.jsx)(`div`,{className:J(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,$.jsx)(BL,{type:e.type}),s===e.id?(0,$.jsx)(`input`,{ref:l,defaultValue:e.label||e.name,className:`flex-1 bg-transparent outline-none min-w-0 font-medium border-b border-primary`,onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&d(e,t.target.value),t.key===`Escape`&&c(null)},onBlur:t=>d(e,t.target.value)}):(0,$.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,$.jsx)(Vn,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,$.jsx)(`button`,{type:`button`,title:`Unlock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-warning hover:text-foreground touch-target`,onClick:t=>u(t,()=>i(e)),children:(0,$.jsx)(Ot,{className:`w-3 h-3`})}):(0,$.jsx)(`button`,{type:`button`,title:`Lock layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>u(t,()=>r(e)),children:(0,$.jsx)(Vn,{className:`w-3 h-3`})}),!e.locked&&(0,$.jsx)(`button`,{type:`button`,title:`Rename layer`,className:`p-0.5 rounded hover:bg-muted-foreground/10 text-muted-foreground hover:text-foreground touch-target`,onClick:t=>{t.stopPropagation(),c(e.id)},children:(0,$.jsx)(Ie,{className:`w-3 h-3`})}),!e.locked&&(0,$.jsx)(`button`,{type:`button`,title:`Destroy layer`,className:`p-0.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,onClick:t=>u(t,()=>o(e)),children:(0,$.jsx)(nt,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function UL(){let{state:e,closeM2:t}=PT(),n=l_(),r=gl(),i=pl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null),c=o?.address===a?o.workspace:null,l=c?.label||c?.name,u=Op(c);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return qr(a).then(t=>{e||s({address:a,workspace:t})}).catch(()=>{}),()=>{e=!0}},[a]);let d=i.pathname.split(`/`).filter(Boolean),f=d[2]===`settings`?BO(d[3]):null,p=(0,Q.useMemo)(()=>RO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:`Settings: ${l||a||`Workspace`}`,icon:c?.icon||`ph:stack-fill`,accentColor:c?.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>a&&r(`/workspaces/${a}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open workspace`,children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),u?(0,$.jsx)(pL,{items:p,activeId:f,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)}):(0,$.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:c?`Workspace settings are available to owners and admins.`:`Loading workspace…`})]})}function WL(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(!1),o=(0,Q.useRef)(!1),s=(0,Q.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ok();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,Q.useCallback)(()=>{a.current=!1,s()},[s]);return(0,Q.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,Q.useEffect)(()=>{if(!e)return;let t=()=>hd.emit(`subscribe`,{channel:`agent`}),r=()=>hd.emit(`unsubscribe`,{channel:`agent`}),i=hd.on(`connect`,()=>{t(),s()});t();let a=e=>{let t=e?.agent??e;t?.id&&n(e=>e.some(e=>e.id===t.id)?e:[...e,t])},o=e=>{let t=e?.agent??e;t?.id&&n(e=>e.map(e=>e.id===t.id?{...e,...t}:e))},c=e=>{let t=e,r=t?.agentId??t?.id;r&&n(e=>e.filter(e=>e.id!==r))},l=e=>{let t=e,r=t?.agentId??t?.id,i=t?.status;!r||!i||n(e=>e.map(e=>e.id===r?{...e,status:i}:e))},u=[[`agent:created`,a],[`agent.created`,a],[`agent:updated`,o],[`agent.updated`,o],[`agent:deleted`,c],[`agent.deleted`,c],[`agent:status:changed`,l],[`agent.status.changed`,l]];return u.forEach(([e,t])=>hd.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>hd.off(e,t))}},[e,s]),(0,Q.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`agents:refresh`,e),()=>window.removeEventListener(`agents:refresh`,e)},[s]),{agents:t,isLoading:r,refresh:c}}function GL({status:e}){return(0,$.jsx)(`span`,{className:J(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function KL(){let e=Gw(),{state:t,selectEntity:n,openM2:r,closeM2:i}=PT(),a=l_(),{agents:o,isLoading:s,refresh:c}=WL(t.activeSection===`agents`),{showToast:l}=Vr(),[u,d]=(0,Q.useState)(new Set),f=gl(),p=e=>{n(e.id),r(`detail`,e.id),f(`/agents/${encodeURIComponent(e.name||e.id)}`)},m=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await bk(t.id),c(),l({title:`Success`,description:`${t.label||t.name} started`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}},h=async(e,t)=>{e.stopPropagation(),d(e=>new Set(e).add(t.id));try{await xk(t.id),c(),l({title:`Success`,description:`${t.label||t.name} stopped`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{d(e=>{let n=new Set(e);return n.delete(t.id),n})}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center`,children:[(0,$.jsx)(XI,{}),(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})]}),!e.local&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>{i(),f(`/agents?create=1`)},title:`Create agent`,"aria-label":`Create agent`,className:`flex items-center justify-center w-6 h-6 rounded-full bg-foreground text-background hover:opacity-80 transition-opacity`,children:(0,$.jsx)(sn,{className:`w-3.5 h-3.5`})})]}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No agents found`}):(0,$.jsx)(`div`,{className:`space-y-1.5 px-2`,children:o.map(e=>{let i=t.selectedEntityId===e.id,o=u.has(e.id);return(0,$.jsxs)(`div`,{"data-active":i||void 0,className:J(`group relative rounded-(--card-radius) px-3 py-2.5 cursor-pointer transition-all shadow-elevation-1 hover:shadow`,i?`bg-accent shadow`:`bg-card hover:bg-accent/50`),style:{borderRight:`6px solid ${e.color||`transparent`}`},onClick:()=>p(e),children:[(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(GL,{status:e.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,$.jsx)(`button`,{type:`button`,disabled:o,onClick:t=>h(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Stop`,children:(0,$.jsx)(zn,{className:`w-3.5 h-3.5`})}):(0,$.jsx)(`button`,{type:`button`,disabled:o,onClick:t=>m(t,e),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50 transition-colors`,title:`Start`,children:(0,$.jsx)(xe,{className:`w-3.5 h-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(e.id),a?r(`settings`,e.id):f(`/agents/${encodeURIComponent(e.name||e.id)}/settings/identity`)},className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground transition-colors`,title:`Settings`,children:(0,$.jsx)(yn,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description})]},e.id)})})})]})}function qL(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function JL(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function YL(e){return e.sessions.sessions.find(t=>t.id===e.current.sessionId||t.path===e.current.sessionFile||t.id===e.sessions.currentSessionId||t.path===e.sessions.currentSessionPath||t.isCurrent)||null}function XL(){let{state:e,closeM2:t}=PT(),n=e.selectedEntityId||``,r=gl(),{showToast:i}=Vr(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),{current:h,sessions:g,isLoading:_,error:v,refresh:y,create:b,select:x,rename:S,remove:C}=AN(n);(0,Q.useEffect)(()=>{n&&(sk(n).then(o).catch(()=>{}),y().catch(e=>{i({title:`Error`,description:e instanceof Error?e.message:`Failed to load sessions`,variant:`destructive`})}))},[n,y,i]);let w=(0,Q.useMemo)(()=>g?.sessions?g.currentSessionId?g.sessions.find(e=>e.id===g.currentSessionId)||null:g.currentSessionPath?g.sessions.find(e=>e.path===g.currentSessionPath)||null:g.sessions.find(e=>e.isCurrent)||null:null,[g]),T=a?.name||n,E=e=>e?.slug||e?.id,D=e=>{let t=typeof e==`string`?e:E(e);r(t?`/agents/${encodeURIComponent(T)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(T)}`)},O=async()=>{try{let e=await b({mode:`persistent`,name:l.trim()||void 0});c(!1),u(``),D(YL(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create session`,variant:`destructive`})}},k=async()=>{try{let e=await b({mode:`experimental`});D(YL(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open experimental session`,variant:`destructive`})}},A=async()=>{try{await b({mode:`incognito`}),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open incognito session`,variant:`destructive`})}},j=async e=>{try{e.isExperimental?await x({mode:`experimental`}):await x({mode:`persistent`,sessionId:e.id}),D(e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}},M=async e=>{if(p.trim())try{let t=(await S(e.id,p.trim())).sessions.sessions.find(t=>t.id===e.id);f(null),m(``),w?.id===e.id&&D(t||e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to rename session`,variant:`destructive`})}},N=async e=>{if(!e.isExperimental&&window.confirm(`Delete session "${qL(e)}"?`))try{await C(e.id),D()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete session`,variant:`destructive`})}};return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:a?.label||a?.name||n,onBack:t,action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(`/agents/${encodeURIComponent(T)}/settings`),className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Agent settings`,children:(0,$.jsx)(yn,{className:`h-3.5 w-3.5`})})}),(0,$.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,$.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,$.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:g?.mode===`incognito`?`Incognito mode`:g?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,$.jsxs)(Z,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:_,children:[(0,$.jsx)(sn,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,$.jsxs)(Z,{size:`sm`,variant:g?.mode===`experimental`?`default`:`outline`,onClick:k,disabled:_,children:[(0,$.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,$.jsx)(Z,{size:`sm`,variant:g?.mode===`incognito`?`default`:`outline`,onClick:A,disabled:_,children:`Incognito`})]})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[v&&(0,$.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:v}),s&&(0,$.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,$.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),O()),e.key===`Escape`&&(c(!1),u(``))},placeholder:`Debugging auth`,className:`h-8`}),(0,$.jsx)(Z,{size:`sm`,onClick:O,disabled:_,children:`Create`})]})]}),g?.sessions.length?(0,$.jsx)(`div`,{className:`space-y-1.5`,children:g.sessions.map(e=>{let t=w?.id===e.id&&g.mode!==`incognito`,n=d===e.id;return(0,$.jsx)(`div`,{onClick:()=>j(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),j(e))},role:`button`,tabIndex:_?-1:0,className:`group w-full rounded-md border px-3 py-2 text-left transition-colors ${t?`border-foreground bg-accent`:`border-transparent hover:bg-accent/50`} ${_?`opacity-60`:``}`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(Y,{value:p,onChange:e=>m(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),M(e)),t.key===`Escape`&&(f(null),m(``))},placeholder:`Session name`,className:`h-8`}),(0,$.jsx)(Z,{size:`sm`,onClick:t=>{t.stopPropagation(),M(e)},disabled:!p.trim()||_,children:`Save`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`truncate text-sm font-medium`,children:qL(e)}),e.isExperimental&&(0,$.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,$.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,$.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:JL(e)})]})}),!n&&(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),m(e.name||qL(e))},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-muted-foreground/10 text-muted-foreground touch-target`,title:`Rename`,children:(0,$.jsx)(gr,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,$.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),N(e)},className:`flex h-7 w-7 items-center justify-center rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive touch-target`,title:`Delete session`,children:(0,$.jsx)(nt,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`text-sm`,children:_?`Loading sessions...`:`No persistent sessions yet.`}),(0,$.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),h?.mode===`incognito`&&(0,$.jsx)(`div`,{className:`mt-3 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground`,children:`Incognito session is active. It lives in memory and stays out of the session list.`})]})]})}function ZL(){let{state:e,closeM2:t}=PT(),n=l_(),r=gl(),i=pl(),a=e.selectedEntityId,[o,s]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!a)return;let e=!1;return sk(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?WO(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,Q.useMemo)(()=>UO.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,$.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(QI,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,$.jsx)(`button`,{type:`button`,onClick:()=>u&&r(`/agents/${u}`),className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground`,title:`Open agent`,children:(0,$.jsx)(Ht,{className:`h-3.5 w-3.5`})})}),(0,$.jsx)(pL,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function QL(){let e=pl(),{state:t}=PT(),[n,r]=(0,Q.useState)(``),i=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{let e=i.current,t=e?.querySelector(`[aria-current="page"]`);if(!e||!t)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();r.top<n.top?e.scrollTop+=r.top-n.top:r.bottom>n.bottom&&(e.scrollTop+=r.bottom-n.bottom)},[e.pathname,t.user?.userType]);let a=lT.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>dT(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,$.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center`,children:[(0,$.jsx)(XI,{}),(0,$.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`})]}),(0,$.jsx)(Y,{type:`search`,name:`settings-menu-filter`,autoComplete:`off`,"data-lpignore":`true`,"data-1p-ignore":`true`,"aria-label":`Search settings menu`,placeholder:`Find a setting…`,value:n,onChange:e=>r(e.target.value)})]}),(0,$.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,$.jsxs)(`section`,{"aria-label":t.label,children:[(0,$.jsx)(`h2`,{className:`px-3 py-2 text-xs font-semibold text-muted-foreground`,children:t.label}),t.items.map(({path:t,icon:n,label:r,description:i})=>(0,$.jsxs)(Nu,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:J(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,$.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,$.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,$.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var $L=280,eR=220,tR=560;function nR(){let{state:e}=PT(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,$.jsx)(mL,{});if(n===`detail`)return(0,$.jsx)(fL,{})}if(t===`workspaces`){if(n===`settings`)return(0,$.jsx)(UL,{});if(n===`detail`)return(0,$.jsx)(PL,{})}if(t===`agents`){if(n===`settings`)return(0,$.jsx)(ZL,{});if(n===`detail`)return(0,$.jsx)(XL,{})}return null}function rR(){let{state:e,closeM1:t,closeM2:n}=PT();Fp(t,e.m1Open&&!e.m2Open),Fp(n,e.m1Open&&e.m2Open);let r=l_(),i=(0,Q.useRef)(null),a=(0,Q.useRef)(null);JI(i,e.m1Open&&!e.m2Open,e.activeSection??``),JI(a,e.m1Open&&e.m2Open,`${e.activeSection}:${e.selectedEntityId}:${e.m2View}`);let[o,s]=(0,Q.useState)($L),[c,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),d=(0,Q.useCallback)(e=>{e.preventDefault(),l(!0),u.current={startX:e.clientX,startWidth:o};let t=e=>{if(!u.current)return;let t=e.clientX-u.current.startX,n=Math.min(tR,Math.max(eR,u.current.startWidth+t));s(n)},n=()=>{u.current=null,l(!1),window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[o]),f=r&&e.m1Open;return(0,$.jsxs)($.Fragment,{children:[f&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,$.jsxs)(`div`,{style:e.m1Open&&!f?{width:o}:void 0,className:J(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!c&&!f&&`transition-[width] duration-normal ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,f?`fixed bottom-2 left-[calc(0.5rem+var(--spacing-rail)+0.5rem)] right-2 top-2 z-40 shadow-elevation-5`:`relative`),children:[(0,$.jsxs)(`div`,{ref:i,"data-menu-view":`list`,inert:!e.m1Open||e.m2Open,className:J(`absolute inset-0 flex flex-col transition-opacity duration-normal ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:f?void 0:{minWidth:o},children:[e.activeSection===`contexts`&&(0,$.jsx)(ZI,{}),e.activeSection===`workspaces`&&(0,$.jsx)(_L,{}),e.activeSection===`agents`&&(0,$.jsx)(KL,{}),e.activeSection===`admin`&&(0,$.jsx)(QL,{}),e.activeSection===`settings`&&(0,$.jsx)(QL,{})]}),(0,$.jsx)(`div`,{ref:a,"data-menu-view":`detail`,inert:!e.m1Open||!e.m2Open,className:J(`absolute inset-0 z-10 bg-card flex flex-col md:transition-transform md:duration-normal md:ease-out`,e.m2Open?`translate-x-0`:`translate-x-full max-md:invisible`),children:e.m2Open&&(0,$.jsx)(nR,{})}),e.m1Open&&!f&&(0,$.jsx)(`div`,{onMouseDown:d,className:`absolute right-0 top-0 bottom-0 z-20 w-1 cursor-col-resize hover:bg-primary/20 transition-colors`})]})]})}var iR=`canvas:readerWidth`,aR=320,oR=1600;function sR(){try{let e=Number(sessionStorage.getItem(iR));return Number.isFinite(e)&&e>=aR&&e<=oR?e:null}catch{return null}}var cR=sR(),lR=new Set;function uR(e){return lR.add(e),()=>{lR.delete(e)}}function dR(e){cR=e===null?null:Math.round(Math.max(aR,Math.min(oR,e)));try{cR===null?sessionStorage.removeItem(iR):sessionStorage.setItem(iR,String(cR))}catch{}lR.forEach(e=>e())}function fR(){return(0,Q.useSyncExternalStore)(uR,()=>cR,()=>null)}var pR=320,mR=1600;function hR({edge:e}){let t=fR(),n=(0,Q.useRef)(null),r=e===`left`?-1:1;return(0,$.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":pR,"aria-valuemax":mR,"aria-valuenow":t??420,tabIndex:0,title:`Drag to resize; arrow keys adjust width; double-click to reset`,className:`absolute inset-y-0 ${e===`left`?`left-0`:`right-0`} z-20 hidden w-2 touch-none cursor-col-resize select-none hover:bg-primary/20 focus-visible:bg-primary/20 focus-visible:outline-none md:block`,onPointerDown:t=>{if(t.button!==0)return;t.preventDefault(),t.stopPropagation();let r=t.currentTarget.closest(`[data-reader-pane]`),i=e===`left`?(r.parentElement?.clientWidth??window.innerWidth)-248:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(pR,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&dR(Math.min(n.current.max,n.current.width+r*(e.clientX-n.current.x)))},onPointerUp:e=>{n.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onPointerCancel:()=>{n.current=null},onLostPointerCapture:()=>{n.current=null},onDoubleClick:()=>dR(null),onKeyDown:e=>{if(e.key!==`ArrowLeft`&&e.key!==`ArrowRight`&&e.key!==`Home`)return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget.closest(`[data-reader-pane]`);e.key===`Home`?dR(null):dR(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function gR(e){return e.schema===`data/schema/note`?Kn:e.schema===`data/schema/tab`?_n:e.schema===`data/schema/file`?Rn:e.schema===`data/schema/message/email`?bt:Hn}function _R({entry:e,onClose:t,frame:n}={}){let r=Eg(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=Vy(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,$.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,$.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between border-b-[3px] bg-muted pl-4 pr-2`,children:[(0,$.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,$.jsx)(`button`,{type:`button`,onClick:a,className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent`,"aria-label":`Close`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,$.jsx)(`button`,{type:`button`,className:`ml-2 underline`,onClick:r.retry,children:`Retry`})]})]}):null;let{workspaceId:c}=i,l=t=>{s(t),t&&t.id!==i.document.id&&!e&&r.replace?.(t,c)};return(0,$.jsx)(CD,{title:Yr(o).title,icon:gR(o),onClose:a,onSave:async e=>(await Qr(c,e.path,[o.id],e.treeName,e.treeType),[o.id]),canSave:!0,successMessage:`Linked`,lockedWorkspaceName:c,relationSubjectId:o.id,frame:n,fillParent:!0,fullWidthContent:yv(o)===x_,maximized:e?void 0:r.location?.maximized,onMaximizedChange:e?void 0:e=>r.update?.({maximized:e}),children:t=>(0,$.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,$.jsx)(By,{document:o,workspaceId:c,onChanged:l,compact:!0,tabActions:t,initialTab:e?void 0:r.location?.section,onTabChange:e?void 0:e=>r.update?.({section:e})},`${c}:${o.id}`)})})}function vR(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function yR(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`].includes(t)&&!!n}var bR=`max-md:fixed max-md:left-2 max-md:right-2 max-md:top-2 max-md:bottom-2 max-md:z-side max-md:py-0 max-md:mr-0 max-md:rounded-(--panel-radius) max-md:shadow-elevation-5 max-md:animate-fade-in`,xR=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function SR(){let e=fR(),{pathname:t,search:n}=pl(),{state:r}=PT(),i=(0,Q.useRef)(null);JI(i,!r.m1Open,t+n,!r.m0Open);let a=yR(t),o=vR(t),{entry:s,loading:c,error:l,close:u}=Eg();return(0,$.jsx)(`div`,{className:J(`relative flex flex-col flex-1 min-w-0`,!o&&`surface-sheet`),children:(0,$.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,$.jsx)(`main`,{ref:i,id:`content-area`,className:J(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!a&&!o&&`p-page max-md:pb-rail-stack`),children:(0,$.jsx)(Ul,{})}),(s||c||l)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:xR,onClick:u,"aria-hidden":!0}),(0,$.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??420}px`},className:J(`relative z-10 flex shrink-0 items-stretch py-2 mr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_248px)]`,bR),children:[(0,$.jsx)(hR,{edge:`left`}),(0,$.jsx)(_R,{},s?`${s.workspaceId}:${s.document.id}`:`loading`)]})]})]})})}function CR(){let{state:e,setView:t}=zs(),{pathname:n}=pl();return e.t1Open||e.addOpen||!vR(n)?null:(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(`tools`),"aria-label":`Open toolbox`,title:`Open toolbox`,className:`fixed z-50 hidden md:flex h-16 w-16 items-center justify-center rounded-full shadow-elevation-4 transition-colors bottom-fab-inset right-6 bg-foreground text-background hover:bg-foreground`,children:(0,$.jsx)(Un,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var wR={current:null,sessions:null,isLoading:!1,error:null};function TR(e){return e instanceof Error?e.message:`Session request failed`}function ER({children:e}){let[t,n]=(0,Q.useState)({}),r=(0,Q.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||wR,...t}}))},[]),i=(0,Q.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,Q.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([ck(e),lk(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}}},[r]),o=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await uk(e,t))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),s=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await dk(e,t))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),c=(0,Q.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await fk(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),l=(0,Q.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await pk(e,t))}catch(t){throw r(e,{isLoading:!1,error:TR(t)}),t}},[i,r]),u=(0,Q.useMemo)(()=>({getState:e=>t[e]||wR,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,$.jsx)(kN.Provider,{value:u,children:e})}function DR(){let e=Ds(),{closeAdd:t}=zs(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,Q.useState)(`Untitled.txt`),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(!1),u=!1;try{hs(``,i.trim()),u=!0}catch{}return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`plaintext-filename`,children:`Filename`}),(0,$.jsx)(Y,{id:`plaintext-filename`,autoFocus:!0,value:i,onChange:e=>a(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Content`}),(0,$.jsx)(Ho,{kind:`text`,value:o,onChange:s,placeholder:`Write plain text…`})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a file in the current storage folder. Existing files are never overwritten.`}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:t,disabled:c,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(!(c||!u||e?.mode!==`workspace`||e.treeName!==`backends`)){l(!0);try{let r=await ks(e.workspaceName,e.path);await Br(e.workspaceName,{...r,key:hs(r.key,i.trim())},new Blob([o],{type:`text/plain;charset=utf-8`}),{contentType:`text/plain;charset=utf-8`}),_s(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`)),n(`Plaintext file created`),t()}catch(e){r(e instanceof Error?e.message:`Failed to create file`)}finally{l(!1)}}},disabled:c||!u,children:c?`Creating…`:`Create file`})]})]})}var OR=`references`;function kR(e){return e?e.documents.map(e=>({predicate:OR,direction:`out`,targetId:e.id,document:e})):[]}function AR(e,t){let[n,r]=(0,Q.useState)(()=>kR(t)),[i,a]=(0,Q.useState)([...ro]),o=e?.mode===`context`?e.contextId:null,[s,c]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!o)return;let e=!1;return Ms({mode:`context`,contextId:o}).then(t=>{e||c({contextId:o,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[o]);let l=e?.mode===`workspace`?e.workspaceName:o&&s?.contextId===o?s.workspaceName:t?.workspaceName??null;return(0,Q.useEffect)(()=>{let e=!1;if(l)return Pi(l).then(t=>{e||a(t)}),()=>{e=!0}},[l]),{rows:n,predicates:i,workspaceName:l,add:(0,Q.useCallback)(async(e,t,i)=>{let a=i.filter(r=>!n.some(n=>n.targetId===r&&n.predicate===e&&n.direction===t));if(a.length===0)return;let o=await Promise.all(a.map(e=>l?Ja(l,e).catch(()=>null):Promise.resolve(null)));r(n=>[...n,...a.map((n,r)=>({predicate:e,direction:t,targetId:n,document:o[r]??null}))])},[n,l]),update:(0,Q.useCallback)((e,t)=>{r(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),remove:(0,Q.useCallback)(e=>{r(t=>t.filter((t,n)=>n!==e))},[]),write:(0,Q.useCallback)(async e=>{if(n.length===0||e.length===0||!l)return 0;let t=new Map;for(let e of n){let n=`${e.direction}:${e.predicate}`,r=t.get(n)??{predicate:e.predicate,direction:e.direction,targets:[]};r.targets.push(e.targetId),t.set(n,r)}let r=0;for(let n of e)for(let e of t.values())try{await go(l,n,e.predicate,e.targets,e.direction)}catch(t){r+=1,console.error(`Failed to relate document`,n,e.predicate,t)}return r<e.length*t.size&&Rg(),r},[n,l]),hasRows:n.length>0}}function jR({f:e,idPrefix:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(!1),o=!e.workspaceName;return(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(Gu,{children:`Related documents`}),(0,$.jsxs)(Z,{type:`button`,variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs`,disabled:o,onClick:()=>r(!0),title:o?`No workspace to relate within`:`Pick documents the new one relates to`,children:[(0,$.jsx)(sn,{className:`mr-1 h-3 w-3`}),` Add`]})]}),e.rows.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None. Relations are written right after the document is created.`}):(0,$.jsx)(`ul`,{className:`space-y-1`,children:e.rows.map((n,r)=>{let i=n.document?Yr(n.document).title:`Document ${n.targetId}`,a=`${t}-relation-${r}`;return(0,$.jsxs)(`li`,{className:`flex items-center gap-1.5 rounded-md border border-input px-2 py-1.5 text-sm`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.update(r,{direction:n.direction===`out`?`in`:`out`}),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground`,title:n.direction===`out`?`The new document ${n.predicate} this one (click to flip)`:`This document ${n.predicate} the new one (click to flip)`,"aria-label":`Flip relation direction`,children:n.direction===`out`?(0,$.jsx)(Dt,{className:`h-3.5 w-3.5`}):(0,$.jsx)(Jn,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`label`,{htmlFor:a,className:`sr-only`,children:`Predicate`}),(0,$.jsx)(`select`,{id:a,value:n.predicate,onChange:t=>e.update(r,{predicate:t.target.value}),className:`w-[9.5rem] shrink-0 rounded-md border border-input bg-background px-1.5 py-1 font-mono text-[11px] focus:outline-none focus:ring-2 focus:ring-ring`,children:(e.predicates.includes(n.predicate)?e.predicates:[n.predicate,...e.predicates]).map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))}),n.document?(0,$.jsx)(Gm,{document:n.document,size:3.5}):null,(0,$.jsx)(`span`,{className:J(`min-w-0 flex-1 truncate`,!n.document&&`italic text-muted-foreground`),title:i,children:i}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.remove(r),className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive`,title:`Remove`,"aria-label":`Remove relation`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]},`${n.direction}:${n.predicate}:${n.targetId}`)})}),n&&e.workspaceName&&(0,$.jsx)($p,{onClose:()=>{i||r(!1)},children:(0,$.jsx)(ih,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,title:`Relate to…`,confirmLabel:`Add`,tabs:[`relations`],fixedWorkspaceName:e.workspaceName,documentCount:1,saving:i,relationPredicates:e.predicates.length?e.predicates:[`references`],relationExcludeIds:new Set(e.rows.map(e=>e.targetId)),onClose:()=>r(!1),onConfirm:()=>{},onConfirmRelation:async({predicate:t,direction:n,targetIds:i})=>{a(!0);try{await e.add(t,n,i),r(!1)}finally{a(!1)}}})})]})}function MR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=AR(n,t.addRelateTo),o=yS(n,a.write,t.addRelateTo?`related:${t.addRelateTo.documents.map(e=>e.id).sort().join(`,`)}`:`add`),s=VD(t.activeWorkspaceName),c=!!n&&o.canSave,l=async()=>{if(n)try{let t=await o.save(n),i=await a.write(t);r(i?`Note created; some relations failed`:`Note created`),o.finish(),e()}catch(e){i(e instanceof Error?e.message:`Failed to create note`)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Body`}),(0,$.jsx)(Ho,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`note-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`note-comment`,value:o.comment,onChange:e=>o.setComment(e.target.value),rows:2,placeholder:`Optional; context you can't infer from the body`,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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsx)(xD,{geotag:o.geotag,idPrefix:`note-geotag`}),(0,$.jsx)(jR,{f:a,idPrefix:`note`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsx)(Go,{...o,onRetry:o.retry}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:o.saving,children:`Close`}),(0,$.jsx)(Z,{size:`sm`,onClick:l,disabled:!c,children:o.saving?`Saving…`:`Done`})]})]})}function NR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=OD(),o=AR(n,t.addRelateTo),s=VD(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`link-url`,children:`URL`}),(0,$.jsx)(Y,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,$.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`link-title`,children:`Title`}),(0,$.jsx)(Y,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsx)(xD,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,$.jsx)(jR,{f:o,idPrefix:`link`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Link created; some relations failed`:`Link created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create link`)}},disabled:!c,children:a.saving?`Saving…`:`Save link`})]})]})}function PR(e){let[t,n]=(0,Q.useState)({key:``,list:[]});return(0,Q.useEffect)(()=>{if(!e)return;let t=!1;return pa(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await sa(e,`github`,t.address).catch(()=>[]);for(let e of n){if(e.writable===!1)continue;let n=e.id||e.name;a.push({driver:`github`,address:t.address,container:n,label:`GitHub: ${n}`})}}t||n({key:e,list:a})}).catch(()=>{t||n({key:e,list:[]})}),()=>{t=!0}},[e]),e&&t.key===e?t.list:[]}function FR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=J_(),o=AR(n,t.addRelateTo),s=VD(t.activeWorkspaceName),c=PR(t.activeWorkspaceName),[l,u]=(0,Q.useState)(`canvas`),[d,f]=(0,Q.useState)(!1),p=c.find(e=>`${e.driver}:${e.address}:${e.container}`===l),m=p?a.title.trim().length>0&&!d:!!n&&a.canSave,h=async()=>{if(p){f(!0);try{await aa(t.activeWorkspaceName||``,p.driver,p.address,p.container,{title:a.title.trim(),...a.description.trim()?{description:a.description.trim()}:{},...a.tags.length?{labels:a.tags}:{}}),r(`Issue created in ${p.container}`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create issue`)}finally{f(!1)}return}if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Todo created; some relations failed`:`Todo created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create todo`)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsx)(Gv,{...a}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`todo-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`todo-comment`,value:a.comment,onChange:e=>a.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`})]}),c.length>0&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`todo-destination`,children:`Save to`}),(0,$.jsxs)(`select`,{id:`todo-destination`,value:l,onChange:e=>u(e.target.value),className:`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`,children:[(0,$.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,js(n)]}),c.map(e=>(0,$.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Creates a GitHub issue (due date, priority and status stay Canvas-side until the issue syncs back).`})]}),(0,$.jsx)(xD,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,$.jsx)(jR,{f:o,idPrefix:`todo`}),!p&&(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function IR(){let{closeAdd:e,state:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=ey(),o=AR(n,t.addRelateTo),s=VD(t.activeWorkspaceName),c=async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Identity created; some relations failed`:`Identity created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create identity`)}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsx)(ay,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`identity-comment`,children:`Comment`}),(0,$.jsx)(`textarea`,{id:`identity-comment`,value:a.comment,onChange:e=>a.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`})]}),(0,$.jsx)(jR,{f:o,idPrefix:`identity`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:js(n)}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function LR({capture:e=!1}={}){let{closeAdd:t,state:n}=zs(),r=Ds(),i=r?.mode===`workspace`&&r.treeName===`backends`,a=AR(r,n.addRelateTo),{showSuccessToast:o,showErrorToast:s}=Wr(),c=(0,Q.useRef)(null),[l,u]=(0,Q.useState)(!1),d=PD(),{items:f,running:p}=d,[m,h]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(r?.mode!==`context`)return;let e=!1;return Ms(r).then(t=>{e||h({contextId:r.contextId,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[r]);let g=WD(r?.mode===`workspace`?r.workspaceName:r&&m?.contextId===r.contextId?m.workspaceName:null),_=e=>{e&&d.addFiles(Array.from(e))},v=e=>{e.preventDefault(),u(!1),_(e.dataTransfer.files)},y=f.filter(e=>e.status===`error`).length,b=f.filter(e=>e.status===`done`).length,x=f.length-b,S=!!r&&!p&&x>0;return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,onClick:()=>c.current?.click(),className:J(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,l?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,$.jsx)(Qe,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,$.jsx)(`p`,{className:`text-sm`,children:e?`Take a photo or video`:`Drag & drop files here`}),(0,$.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`click to open the camera`:`or click to browse`}),(0,$.jsx)(`input`,{ref:c,type:`file`,multiple:!0,accept:e?`image/*,video/*`:void 0,capture:e?`environment`:void 0,className:`hidden`,onChange:e=>{_(e.target.files),e.target.value=``}})]}),(0,$.jsx)(zD,{items:f,running:p,onRemove:d.removeItem}),!i&&(0,$.jsx)(qD,{fields:g,idPrefix:`file`,multiple:f.length>1}),(0,$.jsx)(jR,{f:a,idPrefix:`file`}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[js(r),i?`. Existing files are never overwritten.`:``]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:()=>p?d.cancel():t(),children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{if(!(!S||!r))try{let e=i?null:await g.geotag.capture(),n=await d.start(r,(t,n)=>GD(t,n,{tags:g.tags,comment:g.comment,geo:e})),c=await a.write(n.docIds);if(n.failed===0){let e=n.resumed?` (${n.resumed} already uploaded)`:``,r=c?`; some relations failed`:``;o(`${n.done} file(s) uploaded${e}${r}`),t()}else s(`${n.failed} of ${n.total} file(s) failed — retry keeps what already made it`)}catch(e){s(e instanceof Error?e.message:`Failed to upload files`)}},disabled:!S,children:p?`Uploading…`:y>0?(0,$.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(ir,{className:`h-3.5 w-3.5`}),`Retry failed (`,y,`)`]}):`Add files`})]})]})}function RR(){let{closeAdd:e}=zs(),t=Ds(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(!1),c=i.trim().replace(/^\/+|\/+$/g,``),l=!!t&&!!c&&!o,u=async()=>{if(!(!l||!t)){s(!0);try{let{workspaceName:r,path:i,treeName:a}=await Ms(t),o=i===`/`?``:i;if(a===`backends`){let e=await ks(r,i);await ca(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),_s(t)}else await Aa(r,`${o}/${c}`,!0,a);n(`Folder created`),e()}catch(e){r(e instanceof Error?e.message:`Failed to create folder`)}finally{s(!1)}}};return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,$.jsx)(Y,{id:`add-folder-name`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&u()},placeholder:`e.g. projects/alpha`,autoFocus:!0}),(0,$.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,js(t)]})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function zR(){let{openAddPicker:e,closeAdd:t}=zs(),n=Ds(),{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,Q.useState)(!1);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>e(),"aria-hidden":!0}),(0,$.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,$.jsx)(Cg,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:n?.mode===`workspace`?n.workspaceName:void 0,saving:a,onConfirm:async e=>{o(!0);try{await ws(n,e),r(`${e.length} document${e.length===1?``:`s`} added`),t()}catch(e){i(e instanceof Error?e.message:`Failed to add documents`)}finally{o(!1)}},onClose:e})})]})}function BR(){let{state:e,closeAdd:t}=zs(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,$.jsx)(VR,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a},`${r}:${n.id}`)}function VR({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=No(e,t),s=VD(t),c=async()=>{try{await o.save(),i(`Note updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update note`)}};return(0,$.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`edit-note-title`,children:`Title`}),(0,$.jsx)(Y,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,$.jsx)(Gu,{children:`Body`}),(0,$.jsx)(`div`,{className:`flex-1`,children:(0,$.jsx)(Ho,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsx)(Go,{...o,onRetry:o.save}),(0,$.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Close`}),(0,$.jsx)(Z,{size:`sm`,onClick:c,disabled:!o.canSave,children:o.saving?`Saving…`:`Done`})]})]})}function HR(e,t){let n=Jo(e.metadata?.features),[r,i]=(0,Q.useState)(String(e.data?.label??``)),[a,o]=(0,Q.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,Q.useState)(!1),l=!s;async function u(){c(!0);try{let n=a.map(e=>e.trim()).filter(Boolean);await fa(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data,...r.trim()?{label:r.trim()}:{},tags:n},metadata:{features:Yo(a)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{c(!1)}}return{url:String(e.data?.uri??e.data?.url??``),label:r,setLabel:i,tags:a,setTags:o,saving:s,canSave:l,save:u}}function UR(){let{state:e,closeAdd:t}=zs(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,$.jsx)(WR,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function WR({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=HR(e,t),s=VD(t);return(0,$.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(Gu,{children:[`URL `,(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,$.jsx)(Y,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{htmlFor:`edit-link-label`,children:`Label`}),(0,$.jsx)(Y,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(Gu,{children:`Tags`}),(0,$.jsx)(ng,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Z,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,$.jsx)(Z,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Link updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update link`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save link`})]})]})}var GR=380,KR=300,qR=560,JR={message:{label:`New Message`,icon:b},note:{label:`New Note`,icon:Kn},link:{label:`New Link`,icon:_n},todo:{label:`New Todo`,icon:Vt},identity:{label:`New Identity`,icon:We},sketch:{label:`New Sketch`,icon:le},plaintext:{label:`New Plaintext File`,icon:nn},file:{label:`Add Files`,icon:Qe},photo:{label:`Photo/Video`,icon:Ke},existing:{label:`Add Existing`,icon:En},folder:{label:`New Folder`,icon:st}};function YR(){let{state:e,openAdd:t,openAddPicker:n,closeAdd:r}=zs();Fp(r,e.addOpen);let{addOpen:i,addKind:a,editDocument:o,addModal:s}=e,c=Ds(),l=Ps(c),u=l.isBackend&&!!a&&![`file`,`photo`,`folder`,`message`,`plaintext`].includes(a),d=e.activeWorkspaceName,f=!d||!!e.addRelateTo,p=u||a===`message`&&f,m=l.isBackend?[`note`,`link`,`todo`,`identity`,`sketch`,`existing`]:[`plaintext`];f&&m.push(`message`);let h=c?.mode===`workspace`?`${c.workspaceName}:${c.treeName}:${c.path}`:c?.contextId,g=gl();(0,Q.useEffect)(()=>{!i||a!==`sketch`||l.isBackend||(r(),g(gD.createUrl(c)))},[i,a,c,r,g,l.isBackend]);let _=u_(),[v,y]=(0,Q.useState)(GR),b=(0,Q.useRef)(null),x=(0,Q.useCallback)(e=>{e.preventDefault(),b.current={startX:e.clientX,startWidth:v};let t=e=>{if(!b.current)return;let t=b.current.startX-e.clientX,n=Math.min(qR,Math.max(KR,b.current.startWidth+t));y(n)},n=()=>{b.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[v]);if(!i)return null;let S=!!o,C=!S&&(!a||p),w,T;S?(w=o.schema===`data/schema/note`?`Edit Note`:`Edit Link`,T=o.schema===`data/schema/note`?Kn:_n):a&&!p?(w=JR[a].label,T=JR[a].icon):(w=`Add`,T=sn);let E=(0,$.jsxs)($.Fragment,{children:[_&&!s&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:r,"aria-hidden":!0}),(0,$.jsxs)(`div`,{style:_||s?void 0:{width:v},className:J(`flex flex-col overflow-hidden rounded-[var(--panel-radius)] border bg-card surface-glass`,s?`h-full w-full`:_?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!_&&!s&&(0,$.jsx)(`div`,{onMouseDown:x,className:`absolute left-0 top-0 bottom-0 z-10 w-1 cursor-col-resize transition-colors hover:bg-primary/20`}),(0,$.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center gap-2 border-b-4 px-2`,style:e.activeAccentColor?{borderBottomColor:e.activeAccentColor}:void 0,children:[(0,$.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,"aria-label":`Back one level`,onClick:()=>C||S?r():n(),children:(0,$.jsx)(Jn,{className:`h-5 w-5`})}),(0,$.jsxs)(`span`,{className:`flex flex-1 items-center gap-2 text-sm font-medium`,children:[S?(0,$.jsx)(_e,{className:`h-4 w-4`}):(0,$.jsx)(T,{className:`h-4 w-4`}),w]}),(0,$.jsx)(`button`,{type:`button`,onClick:r,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Close`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[S&&o.schema===`data/schema/note`&&(0,$.jsx)(BR,{}),S&&o.schema===`data/schema/link`&&(0,$.jsx)(UR,{}),!S&&C&&e.addRelateTo&&(0,$.jsxs)(`p`,{className:`border-b px-4 py-2 text-xs text-muted-foreground`,children:[`The new document will be related to `,e.addRelateTo.documents.length,` selected document`,e.addRelateTo.documents.length===1?``:`s`,`.`]}),!S&&l.isBackend&&a!==`message`&&(0,$.jsx)(`p`,{className:`border-b px-4 py-3 text-xs text-muted-foreground`,children:l.loading?`Checking storage destination…`:l.error||`Files are saved directly to this backend folder. Notes and other database documents belong in context or directory trees.`}),!S&&C&&(!l.isBackend||l.destination)&&(0,$.jsx)(yD,{onSelect:t,omit:m}),!S&&a===`message`&&!f&&d&&(0,$.jsx)(Tv,{workspaceId:d,onClose:r},d),!S&&!l.isBackend&&a===`note`&&(0,$.jsx)(MR,{},h),!S&&!l.isBackend&&a===`link`&&(0,$.jsx)(NR,{}),!S&&!l.isBackend&&a===`todo`&&(0,$.jsx)(FR,{}),!S&&!l.isBackend&&a===`identity`&&(0,$.jsx)(IR,{}),!S&&l.destination&&a===`plaintext`&&(0,$.jsx)(DR,{},h),!S&&(!l.isBackend||l.destination)&&a===`file`&&(0,$.jsx)(LR,{},h),!S&&(!l.isBackend||l.destination)&&a===`photo`&&(0,$.jsx)(LR,{capture:!0},h),!S&&!l.isBackend&&a===`existing`&&(0,$.jsx)(zR,{}),!S&&(!l.isBackend||l.destination)&&a===`folder`&&(0,$.jsx)(RR,{},h)]})]})]});return s?(0,$.jsx)(Lp,{label:w,onClose:r,children:E}):E}var XR=(0,Q.createContext)(null);function ZR(){return(0,Q.useContext)(XR)}function QR(){let e=ZR(),t=e?.notifications??[];return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,$.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,$.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,$.jsx)(N,{className:`w-4 h-4`}),(0,$.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(bn,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,$.jsx)(Z,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,$.jsx)(nt,{className:`w-3 h-3`})})]}),t.length===0?(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-(--card-radius)`,children:`No notifications`}):(0,$.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,$.jsxs)(`div`,{className:`rounded-(--card-radius) border p-2.5`,children:[(0,$.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,$.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}function $R({status:e}){return(0,$.jsx)(`span`,{className:J(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:e===`starting`||e===`stopping`?`bg-warning`:`bg-muted-foreground`),title:e})}function ez(){let{openAgentT2:e}=zs(),{setSection:t}=PT(),n=gl(),{agents:r,isLoading:i,refresh:a}=WL(!0),{showToast:o}=Vr(),[s,c]=(0,Q.useState)(new Set),l=(e,t)=>c(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),u=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await bk(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}},d=async(e,t)=>{e.stopPropagation(),l(t.id,!0);try{await xk(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,$.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,$.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,$.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,$.jsx)(ct,{className:`w-8 h-8 opacity-30`}),(0,$.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,$.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,$.jsxs)(`div`,{className:`group relative px-3 py-2.5 cursor-pointer transition-colors bg-card hover:bg-accent/50`,style:{borderLeft:`6px solid ${t.color||`transparent`}`},onClick:()=>e(t.id),children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)($R,{status:t.status}),(0,$.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,$.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,$.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>d(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Stop`,children:(0,$.jsx)(zn,{className:`w-3 h-3`})}):(0,$.jsx)(`button`,{type:`button`,disabled:n,onClick:e=>u(e,t),className:`flex items-center justify-center w-6 h-6 rounded hover:bg-muted-foreground/10 text-muted-foreground disabled:opacity-50`,title:`Start`,children:(0,$.jsx)(xe,{className:`w-3 h-3`})})})]}),t.description&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function tz(){let e=ZR(),[t,n]=(0,Q.useState)(50),r=e?.notifications??[],i=r.slice(-t).reverse();return(0,$.jsxs)(`section`,{"aria-label":`Notification history`,className:`flex h-full min-h-0 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-b px-4 py-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{className:`text-sm font-semibold`,children:[`Notifications`,r.length>0&&(0,$.jsx)(`span`,{className:`ml-2 font-normal text-muted-foreground`,children:r.length})]}),(0,$.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:`Saved on this browser`})]}),r.length>0&&(0,$.jsxs)(Z,{variant:`ghost`,size:`sm`,onClick:()=>void e?.clear(),title:`Clear all notifications`,className:`shrink-0 gap-1.5`,children:[(0,$.jsx)(nt,{className:`h-3.5 w-3.5`}),`Clear all`]})]}),e?.storageError&&(0,$.jsx)(`p`,{role:`alert`,className:`border-b px-4 py-3 text-xs text-destructive`,children:`Couldn’t access notification history in this browser.`}),e?.loading?(0,$.jsx)(`p`,{role:`status`,className:`p-4 text-sm text-muted-foreground`,children:`Loading notifications…`}):r.length===0?(0,$.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,$.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,$.jsx)(bn,{className:`h-5 w-5 text-muted-foreground`})}),(0,$.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No notifications yet`})]}):(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[(0,$.jsx)(`ol`,{className:`space-y-2`,children:i.map(t=>{let n=t.status===`error`?z:t.status===`completed`?be:t.status===`started`?N:bn;return(0,$.jsx)(`li`,{"data-notification-id":t.id,className:`rounded-(--card-radius) border bg-card p-3`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(n,{"aria-hidden":!0,className:`mt-0.5 h-4 w-4 shrink-0 ${t.status===`error`?`text-destructive`:`text-muted-foreground`}`}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`break-words text-sm font-medium`,children:t.title}),t.text&&(0,$.jsx)(`p`,{className:`mt-1 whitespace-pre-wrap break-words text-xs text-muted-foreground`,children:t.text}),(0,$.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[(0,$.jsx)(`time`,{dateTime:t.timestamp,children:new Date(t.timestamp).toLocaleString()}),t.status===`started`&&(0,$.jsx)(`span`,{children:` · Started`}),t.status===`completed`&&(0,$.jsx)(`span`,{children:` · Completed`}),t.status===`error`&&(0,$.jsx)(`span`,{children:` · Error`})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void e?.remove(t.id),"aria-label":`Clear notification: ${t.title}`,title:`Clear notification`,className:`-mr-1 -mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent focus-ring touch-target`,children:(0,$.jsx)(G,{className:`h-3.5 w-3.5`})})]})},t.id)})}),r.length>t&&(0,$.jsx)(Z,{variant:`ghost`,size:`sm`,className:`mt-3 w-full`,onClick:()=>n(e=>e+50),children:`Show older notifications`})]})]})}function nz(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(`
54
54
  `)||``}function rz(e){let[t,n]=(0,Q.useState)([]),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(null),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(e);return c!==e&&(l(e),e||n([])),(0,Q.useEffect)(()=>{let t=!1;if(e)return ck(e).then(e=>{t||n(e.messages.map(e=>({role:e.role,content:e.content,isComplete:!0,...e.metadata?.reasoning?{reasoning:e.metadata.reasoning}:{},...e.metadata?{metadata:e.metadata}:{}})))}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),{messages:t,isStreaming:r,error:a,send:(0,Q.useCallback)(async t=>{if(r||!t.trim()||!e)return;o(null),n(e=>[...e,{role:`user`,content:t,isComplete:!0},{role:`assistant`,content:``,isComplete:!1}]),i(!0);try{await bk(e)}catch(e){let t=e instanceof Error?e.message:void 0;if(!t?.includes(`not active`)&&!t?.includes(`already`)){o(t??`Failed to start agent`),i(!1);return}}s.current=new AbortController;let a=``,c=``,l=``,u;try{await X.stream(`${Lr}/agents/${e}/prompt/stream`,{message:t},{signal:s.current.signal,onChunk:e=>{a+=e;let t=a.split(`
55
55
  `);a=t.pop()??``;for(let e of t){if(!e.startsWith(`data: `))continue;let t=e.slice(6).trim();if(t===`[DONE]`)return;try{let e=JSON.parse(t);if(e.type===`chunk`)c+=e.delta||``,n(e=>{let t=[...e];return t[t.length-1]={role:`assistant`,content:c,isComplete:!1,...l?{reasoning:l}:{},...u?{metadata:u}:{}},t});else if(e.type===`thinking`)l=`${l}${e.delta||``}`.trim(),n(e=>{let t=[...e],n=t[t.length-1]?.content||c;return t[t.length-1]={role:`assistant`,content:n,isComplete:!1,...l?{reasoning:l}:{},...u?{metadata:u}:{}},t});else if(e.type===`complete`){let t=Array.isArray(e.messages)?[...e.messages].reverse().find(e=>e?.role===`assistant`):null,r=nz(t),i=YO(t)||l;u=XO(t),n(e=>{let t=[...e],n=c||t[t.length-1]?.content||``;return t[t.length-1]={role:`assistant`,content:r||n,isComplete:!0,...i?{reasoning:i}:{},...u?{metadata:u}:{}},t})}else e.type===`error`&&o(e.error)}catch{}}},onError:e=>{e.name!==`AbortError`&&o(e.message)},onComplete:()=>{n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}})}catch(e){let t=e instanceof Error?e:null;t?.name!==`AbortError`&&o(t?.message??`Stream failed`),n(e=>{let t=[...e],n=t[t.length-1];return n&&!n.isComplete&&(t[t.length-1]={...n,isComplete:!0}),t}),i(!1)}},[e,r]),sendVoice:(0,Q.useCallback)(async t=>{if(!(r||!e)){o(null),i(!0),n(e=>[...e,{role:`user`,content:`🎤 Transcribing…`,isComplete:!1}]);try{let r=await Dk(e,t);n(e=>{let t=[...e];return t[t.length-1]={role:`user`,content:`🎤 ${r.transcript}`,isComplete:!0},[...t,{role:`assistant`,content:r.reply,isComplete:!0}]}),r.audio&&r.audioMimeType&&new Audio(`data:${r.audioMimeType};base64,${r.audio}`).play().catch(()=>{})}catch(e){o(e instanceof Error?e.message:`Voice prompt failed`),n(e=>{let t=[...e],n=t[t.length-1];return n?.role===`user`&&!n.isComplete&&t.pop(),t})}finally{i(!1)}}},[e,r]),stop:(0,Q.useCallback)(()=>{s.current?.abort(),i(!1)},[]),clear:(0,Q.useCallback)(()=>{n([]),o(null)},[])}}function iz(){let[e,t]=(0,Q.useState)(!1),[n,r]=(0,Q.useState)(null),i=(0,Q.useRef)(null),a=(0,Q.useRef)([]);return{isRecording:e,recorderError:n,start:(0,Q.useCallback)(async()=>{if(!i.current){if(r(null),!navigator.mediaDevices?.getUserMedia||typeof MediaRecorder>`u`){r(`Audio recording is not supported in this browser`);return}try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=MediaRecorder.isTypeSupported(`audio/webm;codecs=opus`)?`audio/webm;codecs=opus`:void 0,r=new MediaRecorder(e,n?{mimeType:n}:void 0);a.current=[],r.ondataavailable=e=>{e.data.size>0&&a.current.push(e.data)},r.start(),i.current=r,t(!0)}catch(e){let t=e instanceof Error?e:null;r(t?.name===`NotAllowedError`?`Microphone access denied`:t?.message??`Could not start recording`)}}},[]),stop:(0,Q.useCallback)(()=>{let e=i.current;return e?new Promise(n=>{e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop()),i.current=null,t(!1);let r=e.mimeType||`audio/webm`,o=new Blob(a.current,{type:r});a.current=[],n(o.size>0?o:null)},e.stop()}):Promise.resolve(null)},[]),cancel:(0,Q.useCallback)(()=>{let e=i.current;e&&(e.onstop=()=>{e.stream.getTracks().forEach(e=>e.stop())},e.stop(),i.current=null,a.current=[],t(!1))},[])}}function az({agentId:e,onClose:t}){let[n,r]=(0,Q.useState)(null),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),{showToast:m}=Vr(),h=es(),g=h?.state.activeContextType===`context`?h.state.activeContextId:null,_=h?.state.activeContextPath??null,v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),{messages:b,isStreaming:x,error:S,send:C,sendVoice:w,stop:T,clear:E}=rz(e),{isRecording:D,recorderError:O,start:k,stop:A}=iz();(0,Q.useEffect)(()=>{sk(e).then(r).catch(()=>{}),tk(e).then(l).catch(()=>l(null))},[e]),(0,Q.useEffect)(()=>{Ek().then(e=>s(!!(e.enabled&&e.stt))).catch(()=>s(!1))},[]),(0,Q.useEffect)(()=>{b.length!==0&&v.current?.scrollIntoView({behavior:`smooth`})},[b]);let j=c?.binding.type===`context`&&!!g&&c?.binding.context===g,M=c?c.binding.type===`global`?`scope: global`:c.binding.type===`context`?j?`scoped to this context`:`context-bound`:`scope: ${c.binding.workspaceName||c.binding.workspace}${c.binding.type===`path`?`:${c.binding.path||`/`}`:``}`:`no canvas access`,N=async()=>{if(!g||u)return;let t=g||_;if(window.confirm(`Bind "${n?.label||n?.name||e}" to the current context (${t})? This mints a new canvas token and restarts the agent if it is running.`)){d(!0);try{let t=await nk(e,{binding:{type:`context`,context:g},permissions:[`read`,`write`]});l(t.access),p(t.token)}catch(e){m({title:`Error`,description:e instanceof Error?e.message:`Bind failed`,variant:`destructive`})}finally{d(!1)}}},P=async()=>{let e=i.trim();!e||x||(a(``),y.current?.focus(),await C(e))};return(0,$.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-3 h-12 border-b border-border shrink-0`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:t,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Back to agents`,children:(0,$.jsx)(Jn,{className:`w-4 h-4`})}),n?.color&&(0,$.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0`,style:{backgroundColor:n.color}}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,$.jsx)(`div`,{className:`text-sm font-medium truncate`,children:n?.label||n?.name||e}),(0,$.jsx)(`div`,{className:`text-[10px] leading-tight text-muted-foreground truncate`,title:M,children:M})]}),(0,$.jsx)(`button`,{type:`button`,onClick:E,className:`p-1 rounded hover:bg-accent/50 text-muted-foreground hover:text-foreground transition-colors`,title:`Clear chat`,children:(0,$.jsx)(nt,{className:`w-3.5 h-3.5`})})]}),g&&!j&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-muted/40 text-xs shrink-0`,children:[(0,$.jsxs)(`span`,{className:`flex-1 truncate text-muted-foreground`,title:g||_||void 0,children:[`Toolbox context: `,g||_]}),(0,$.jsx)(`button`,{type:`button`,disabled:u,onClick:N,className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent disabled:opacity-50`,children:u?`Binding…`:`Bind to this context`})]}),f&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border bg-warning/10 text-xs shrink-0`,children:[(0,$.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:`Token (shown once):`}),(0,$.jsx)(`code`,{className:`flex-1 truncate font-mono`,children:f}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>navigator.clipboard?.writeText(f),className:`shrink-0 rounded border border-input px-2 py-1 hover:bg-accent`,children:`Copy`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>p(null),className:`shrink-0 rounded px-1.5 py-1 hover:bg-accent`,title:`Dismiss`,children:`×`})]}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3 space-y-3`,children:[b.length===0&&(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10`,children:n?`Chat with ${n.label||n.name}`:`Loading…`}),b.map((e,t)=>(0,$.jsxs)(`div`,{className:J(`text-sm rounded-lg px-3 py-2 max-w-[85%] break-words`,e.role===`user`?`ml-auto bg-foreground text-background`:`mr-auto bg-muted text-foreground`),children:[(0,$.jsx)(DN,{reasoning:e.role===`assistant`?e.reasoning:void 0,metadata:e.role===`assistant`?e.metadata:void 0,isStreaming:!e.isComplete,compact:!0}),e.role===`assistant`?(0,$.jsx)(E_,{content:e.content||(e.isComplete?``:`…`)}):(0,$.jsx)(`span`,{className:`whitespace-pre-wrap`,children:e.content})]},t)),(S||O)&&(0,$.jsx)(`div`,{className:`text-xs text-destructive text-center py-1`,children:S||O}),(0,$.jsx)(`div`,{ref:v})]}),(0,$.jsx)(`div`,{className:`p-3 border-t border-border shrink-0`,children:(0,$.jsxs)(`div`,{className:`flex gap-2 items-end`,children:[(0,$.jsx)(`textarea`,{ref:y,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),P())},placeholder:`Message…`,rows:2,className:`flex-1 resize-y text-sm px-3 py-2 border border-input bg-background rounded-md focus:outline-none focus:ring-1 focus:ring-ring min-h-[38px] max-h-[120px]`}),o&&(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{if(D){let e=await A();e&&await w(e)}else x||await k()},disabled:x&&!D,className:J(`flex items-center justify-center w-9 h-9 rounded-md transition-opacity shrink-0 disabled:opacity-40`,D?`bg-destructive text-destructive-foreground hover:opacity-90 animate-pulse`:`bg-muted text-foreground hover:bg-accent`),title:D?`Stop recording and send`:`Record a voice message`,children:D?(0,$.jsx)(zn,{className:`w-4 h-4`}):(0,$.jsx)(at,{className:`w-4 h-4`})}),x?(0,$.jsx)(`button`,{type:`button`,onClick:T,className:`flex items-center justify-center w-9 h-9 rounded-md bg-destructive text-destructive-foreground hover:opacity-90 transition-opacity shrink-0`,title:`Stop`,children:(0,$.jsx)(zn,{className:`w-4 h-4`})}):(0,$.jsx)(`button`,{type:`button`,onClick:P,disabled:!i.trim(),className:`flex items-center justify-center w-9 h-9 rounded-md bg-foreground text-background hover:opacity-90 disabled:opacity-40 transition-opacity shrink-0`,title:`Send`,children:(0,$.jsx)(vt,{className:`w-4 h-4`})})]})})]})}function oz(){let{state:e,openApplet:t}=zs(),[n,r]=(0,Q.useState)(`context`),i=e.appsAppletId,a=i?Dw.find(e=>e.id===i):null;if(a)return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(null),className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Back to applets`,title:`Back to applets`,children:(0,$.jsx)(Jn,{className:`h-4 w-4`})}),(0,$.jsx)(a.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-sm font-medium`,children:a.label})]}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,$.jsx)(a.Component,{})})]});let o=Ow(n);return(0,$.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,$.jsx)(`div`,{className:`flex shrink-0 border-b border-border`,children:[`context`,`global`].map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:J(`flex-1 py-2.5 text-xs capitalize transition-colors`,n===e?`-mb-px border-b-2 border-foreground font-semibold text-foreground`:`font-medium text-muted-foreground hover:text-foreground`),children:e},e))}),(0,$.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[!o.length&&(0,$.jsxs)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:[`No `,n,` applets yet.`]}),(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:o.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex min-h-[4.5rem] flex-col items-center justify-center gap-1.5 rounded-(--card-radius) border border-border bg-muted/40 p-3 text-foreground transition-colors hover:bg-muted`,title:e.description,children:[(0,$.jsx)(e.icon,{className:`h-5 w-5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:e.label})]},e.id))})]})]})}var sz=[{view:`apps`,icon:$n,label:`Apps`},{view:`tools`,icon:Un,label:`Filters`},{view:`agents`,icon:ct,label:`Agents`},{view:`notifications`,icon:bn,label:`Notifications`}],cz=340,lz=`toolbox:width`,uz=360,dz=48,fz=e=>{let t=typeof window<`u`?window.innerWidth:1600,n=Math.max(cz,Math.min(Math.round(t*.7),t-dz-uz));return Math.max(cz,Math.min(e,n))},pz=()=>typeof window<`u`?Math.round(window.innerWidth/2):720;function mz(){let{state:e,setView:t,closeT1:n,closeT2:r}=zs();Fp(n,e.t1Open&&!e.t2Open),Fp(r,e.t2Open);let{t1Open:i,t1View:a,t2Open:o,t2AgentId:s,activeAccentColor:c}=e,l=u_(),[u,d]=(0,Q.useState)(()=>{let e=typeof window<`u`?Number(localStorage.getItem(lz)):NaN;return Number.isFinite(e)&&e>0?e:420}),f=(0,Q.useCallback)(e=>{d(e);try{localStorage.setItem(lz,String(e))}catch{}},[]),p=(0,Q.useRef)(null),m=(0,Q.useCallback)(e=>{e.preventDefault(),p.current={startX:e.clientX,startWidth:u};let t=e=>{if(!p.current)return;let t=fz(p.current.startWidth-(e.clientX-p.current.startX));d(t)},n=()=>{p.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n),d(e=>{try{localStorage.setItem(lz,String(e))}catch{}return e})};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[u]),h=u>=pz()*.9;return(0,Q.useEffect)(()=>{let e=()=>d(e=>fz(e));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),!i||!a?null:(0,$.jsxs)($.Fragment,{children:[l&&(0,$.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,$.jsxs)(`div`,{style:l?void 0:{width:u},className:J(`flex flex-col overflow-hidden rounded-(--panel-radius) border bg-card surface-glass text-foreground`,l?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!l&&(0,$.jsx)(`div`,{onMouseDown:m,className:`absolute left-0 top-0 z-20 h-full w-1.5 cursor-col-resize hover:bg-primary/20`,title:`Drag to resize`,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between gap-1 border-b-4 px-2`,style:c?{borderBottomColor:c}:void 0,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:sz.map(({view:e,icon:n,label:r})=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e),"aria-label":r,title:r,className:J(`flex h-10 w-11 items-center justify-center rounded-md transition-colors`,a===e?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted/60 hover:text-foreground`),children:(0,$.jsx)(n,{className:`h-4 w-4 shrink-0`})},e))}),(0,$.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[!l&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>f(h?420:fz(pz())),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":h?`Shrink toolbox`:`Expand toolbox`,title:h?`Shrink toolbox`:`Expand to half screen`,children:h?(0,$.jsx)(lt,{className:`h-4 w-4`}):(0,$.jsx)(xn,{className:`h-4 w-4`})}),(0,$.jsx)(`button`,{type:`button`,onClick:n,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Close toolbox`,children:(0,$.jsx)(G,{className:`h-4 w-4`})})]})]}),(0,$.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${o&&s?`invisible`:``}`,children:[a===`home`&&(0,$.jsx)(QR,{}),a===`apps`&&(0,$.jsx)(oz,{}),a===`tools`&&(0,$.jsx)(Cw,{}),a===`agents`&&(0,$.jsx)(ez,{}),a===`notifications`&&(0,$.jsx)(tz,{})]}),o&&s&&(0,$.jsx)(`div`,{className:`absolute inset-0 z-10 flex flex-col bg-background`,children:(0,$.jsx)(az,{agentId:s,onClose:r})})]})]})]})}function hz(){let{running:e,hasViewer:t,paused:n,snapshot:r,source:i,lastCount:a,error:o,setPaused:s,stop:c,reopen:l}=LS();if(!e||t)return null;let u=i===`screen`?Fn:i===`photo`?cn:Ke;return(0,$.jsxs)(`div`,{className:J(`fixed right-4 w-56 overflow-hidden rounded-(--panel-radius) border border-border bg-card shadow-elevation-4 z-panel animate-fade-in`,`bottom-fab-inset md:bottom-[calc(var(--spacing-fab-inset)+5rem)]`),role:`status`,"aria-label":`Lens feed running`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:l,title:`Back to Lens`,className:`relative block w-full cursor-pointer bg-black/80 aspect-video`,children:[(0,$.jsx)(ZS,{className:`h-full w-full`}),r&&(0,$.jsx)(`img`,{src:r,alt:``,className:`absolute inset-0 h-full w-full bg-black object-contain`}),n&&(0,$.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white`,children:`paused`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1.5`,children:[(0,$.jsx)(u,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-muted-foreground`,children:o?(0,$.jsx)(`span`,{className:`text-destructive`,children:o}):n?`paused`:r?`${i===`photo`?`photo`:`snapshot`} · ${a??`…`} match${a===1?``:`es`}`:`live · ${a??`…`} match${a===1?``:`es`}`}),i!==`photo`&&(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(!n),"aria-label":n?`Resume Lens`:`Pause Lens`,title:n?`Resume searching`:`Pause searching (camera stays on)`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:n?(0,$.jsx)(xe,{className:`h-3.5 w-3.5`}):(0,$.jsx)(D,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:l,"aria-label":`Reopen Lens panel`,title:`Reopen Lens`,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:(0,$.jsx)(xn,{className:`h-3.5 w-3.5`})}),(0,$.jsx)(`button`,{type:`button`,onClick:c,"aria-label":`Stop Lens feed`,title:`Stop the feed`,className:`rounded p-1 text-destructive transition-colors hover:bg-destructive/10`,children:(0,$.jsx)(on,{className:`h-3.5 w-3.5`})})]})]})}var gz=[`view`,`location`,`metadata`,`json`,`synapses`,`backends`];function _z(e){let t=new URLSearchParams(e.replace(/^#/,``)),n=t.get(`document`)??``,r=t.get(`workspace`);if(!r||!/^\d+$/.test(n)||!Number.isSafeInteger(Number(n))||Number(n)<=0)return null;let i=t.get(`section`);return{workspaceId:r,documentId:Number(n),section:gz.includes(i)?i:`view`,maximized:t.get(`fullscreen`)===`1`}}function vz(e){let t=new URLSearchParams({document:String(e.documentId),workspace:e.workspaceId});return e.section!==`view`&&t.set(`section`,e.section),e.maximized&&t.set(`fullscreen`,`1`),`#${t}`}function yz({children:e}){let t=pl(),n=gl(),r=(0,Q.useMemo)(()=>_z(t.hash),[t.hash]),i=r?.workspaceId,a=r?.documentId,o=i&&a?JSON.stringify([i,a]):null,[s,c]=(0,Q.useState)(0),[l,u]=(0,Q.useState)(null),d=l?.key===o&&l?.revision===s?l:null;(0,Q.useEffect)(()=>{if(!o||!i||!a||d)return;let e=!1;return Ja(i,a).then(t=>{e||u({key:o,revision:s,document:t,error:t?void 0:`Document not found.`})}).catch(t=>{e||u({key:o,revision:s,document:null,error:t?.statusCode===404?`Document not found.`:`Unable to load this document.`})}),()=>{e=!0}},[o,i,a,s,d]);let f=(0,Q.useCallback)((e,r)=>{u({key:JSON.stringify([r,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:vz({workspaceId:r,documentId:e.id,section:`view`,maximized:!1})},{state:t.state})},[n,t.pathname,t.search,t.state,s]),p=(0,Q.useCallback)(()=>{r&&n({pathname:t.pathname,search:t.search,hash:``},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),m=(0,Q.useCallback)((e,i)=>{r&&(u({key:JSON.stringify([i,e.id]),revision:s,document:e}),n({pathname:t.pathname,search:t.search,hash:vz({...r,workspaceId:i,documentId:e.id})},{replace:!0,state:t.state}))},[r,s,n,t.pathname,t.search,t.state]),h=(0,Q.useCallback)(e=>{r&&n({pathname:t.pathname,search:t.search,hash:vz({...r,...e})},{replace:!0,state:t.state})},[r,n,t.pathname,t.search,t.state]),g=(0,Q.useCallback)(()=>c(e=>e+1),[]),_=(0,Q.useMemo)(()=>({entry:d?.document&&i?{document:d.document,workspaceId:i}:null,location:r,loading:!!r&&!d,error:d?.error,open:f,replace:m,close:p,update:h,retry:g}),[d,i,r,f,m,p,h,g]);return(0,$.jsx)(wg.Provider,{value:_,children:e})}var bz={key:`desk`,label:`Desk`,main:`/`,mainExpanded:!1,entries:[]},xz=0,Sz=()=>`c${++xz}`;function Cz(e,t){return e.kind===`route`&&t.kind===`route`?e.location===t.location:e.kind===`document`&&t.kind===`document`&&e.document.id===t.document.id&&e.workspaceId===t.workspaceId}function wz({children:e}){let t=pl(),n=gl(),[r,i]=(0,Q.useState)([bz]),[a,o]=(0,Q.useState)(0),[s,c]=(0,Q.useState)(my),l=(0,Q.useRef)(r),u=(0,Q.useRef)(a),d=(0,Q.useRef)(s);(0,Q.useEffect)(()=>{l.current=r,u.current=a,d.current=s},[r,a,s]);let f=(0,Q.useCallback)((e,t)=>{let n=l.current.slice();n[e]=t,l.current=n,i(n)},[]),p=(0,Q.useCallback)(e=>{let t=u.current,n=l.current[t];n&&f(t,e(n))},[f]),m=t.pathname+t.search;(0,Q.useEffect)(()=>{p(e=>e.main===m?e:{...e,main:m})},[m,p]);let h=(0,Q.useCallback)(e=>{let t=l.current[u.current];if(!t)return;let n=t.entries.find(t=>Cz(e,t));if(n){c(n.id);return}let r={...e,id:Sz()},i=t.entries.findIndex(e=>e.id===d.current),a=t.entries.slice();a.splice(i>=0?i+1:0,0,r),p(e=>({...e,entries:a})),d.current=r.id,c(r.id)},[p]),g=(0,Q.useCallback)((e,t)=>{h({kind:`document`,document:e,workspaceId:t})},[h]),_=(0,Q.useCallback)((e,t)=>{let n=`document-preview`;p(r=>{let i=r.entries.find(e=>e.id===n),a={kind:`document`,id:n,document:e,workspaceId:t,expanded:i?.expanded};return{...r,entries:[a,...r.entries.filter(e=>e.id!==n)]}}),d.current=n,c(n)},[p]),v=(0,Q.useCallback)(e=>{p(t=>({...t,entries:t.entries.filter(t=>t.id!==e)})),c(t=>t===e?my:t)},[p]),y=(0,Q.useCallback)((e,t)=>{p(n=>({...n,entries:n.entries.map(n=>n.id===e&&n.kind===`route`?{...n,location:t}:n)}))},[p]),b=(0,Q.useCallback)(e=>{p(t=>e===`main`?{...t,mainExpanded:!t.mainExpanded}:{...t,entries:t.entries.map(t=>t.id===e?{...t,expanded:!t.expanded}:t)})},[p]),x=(0,Q.useCallback)(e=>{let t=l.current[e];t&&(u.current=e,o(e),c(my),n(t.main))},[n]),S=(0,Q.useCallback)((e,t,n)=>{let r=l.current.findIndex(t=>t.key===e);if(r>=0){x(r);return}let a=[...l.current,{key:e,label:t,main:n,mainExpanded:!1,entries:[]}];l.current=a,i(a),x(a.length-1)},[x]),C=(0,Q.useCallback)(e=>{x(u.current+e)},[x]),w=(0,Q.useCallback)(e=>{let t=l.current.findIndex(t=>t.key===e);if(t<=0)return;let n=l.current.filter(t=>t.key!==e);l.current=n,i(n);let r=u.current;r===t?x(Math.min(t,n.length-1)):r>t&&(u.current=r-1,o(r-1))},[x]),T=(0,Q.useMemo)(()=>({rows:r,activeRow:a,focus:s,setFocus:c,openCanvas:h,openDocument:g,closeCanvas:v,navigateCanvas:y,toggleExpanded:b,activateRow:S,moveRow:C,closeRow:w}),[r,a,s,h,g,v,y,b,S,C,w]),E=(0,Q.useMemo)(()=>({entry:null,open:g,preview:_,close:()=>{}}),[g,_]);return(0,$.jsx)(hy.Provider,{value:T,children:(0,$.jsx)(wg.Provider,{value:E,children:e})})}function Tz(e){return rc(typeof e==`string`?ic(e):e)}function Ez({location:e,onNavigate:t}){let n=(0,Q.useMemo)(()=>{let t=ic(e);return{pathname:t.pathname||`/`,search:t.search||``,hash:t.hash||``,state:null,key:e}},[e]),r=(0,Q.useMemo)(()=>({basename:`/`,static:!1,useTransitions:void 0,future:{},navigator:{createHref:Tz,go:()=>{},push:e=>t(Tz(e)),replace:e=>t(Tz(e))}}),[t]);return(0,$.jsx)(nl.Provider,{value:r,children:(0,$.jsx)(rl.Provider,{value:{location:n,navigationType:Js.Push},children:(0,$.jsx)(il.Provider,{value:{outlet:null,matches:[],isDataRoute:!1},children:(0,$.jsx)(Kl,{children:SI})})})})}var Dz=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,Oz=420,kz=e=>e<=0?0:e>=1?1:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2;function Az(e,t,n){if(window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return e.scrollLeft=t,n?.(),()=>{};let r=e.scrollLeft,i=t-r;if(Math.abs(i)<1)return n?.(),()=>{};let a=e.style.scrollSnapType;e.style.scrollSnapType=`none`;let o=performance.now(),s=0,c=t=>{let l=Math.min(1,(t-o)/Oz);e.scrollLeft=r+i*kz(l),l<1?s=requestAnimationFrame(c):(e.style.scrollSnapType=a,n?.())};return s=requestAnimationFrame(c),()=>{cancelAnimationFrame(s),e.style.scrollSnapType=a}}function jz(e,t){let n=parseFloat(getComputedStyle(e).gap)||0,r=t.getBoundingClientRect().left-e.getBoundingClientRect().left+e.scrollLeft,i=r+t.offsetWidth,a=e.scrollLeft,o=a+e.clientWidth;return r<a?Math.max(0,r-n):i>o?i+n-e.clientWidth:a}function Mz({section:e}){return e===`contexts`?(0,$.jsx)(ZI,{}):e===`workspaces`?(0,$.jsx)(_L,{}):e===`agents`?(0,$.jsx)(KL,{}):e===`admin`||e===`settings`?(0,$.jsx)(QL,{}):null}function Nz(e,t,n){if(e?.kind===`document`)return Yr(e.document).title;let r=(e?.kind===`route`?e.location:t).split(/[?#]/)[0];if(r===`/settings`)return`Settings`;let i=lT.flatMap(e=>[...e.items]).find(e=>e.path===r);if(i)return i.label;let a=r.split(`/`).filter(Boolean);if(a.length===0)return`Desk`;if(a[0]===`workspaces`&&a.length===2){let e=decodeURIComponent(a[1]),t=n.find(t=>t.id===e)??n.find(t=>t.name===e);return t?.label||t?.name||`Workspace`}return decodeURIComponent(a[a.length-1])}function Pz({id:e,title:t,expanded:n,focused:r,onFocus:i,onToggleExpanded:a,onClose:o,badge:s,contentHeader:c,children:l}){let u=fR();return(0,$.jsxs)(`section`,{"data-reader-pane":c?!0:void 0,style:c&&!n?{"--reader-width":`${u??420}px`,...u?{transition:`none`}:{}}:void 0,"data-strip-col":e,className:J(`strip-canvas surface-sheet relative`,n&&`strip-canvas--wide`,r&&`strip-canvas--focused`),onPointerDownCapture:()=>i(e),"aria-label":t,children:[c&&!n&&(0,$.jsx)(hR,{edge:`right`}),!c&&(0,$.jsxs)(`header`,{className:`strip-canvas-bar`,children:[s&&(0,$.jsx)(`span`,{className:`strip-row-label`,children:s}),(0,$.jsx)(`span`,{className:`strip-canvas-title`,title:t,children:t}),(0,$.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:n?`Card size`:`Expand to full width`,"aria-pressed":n,onClick:()=>a(e),children:n?(0,$.jsx)(lt,{className:`size-3.5`}):(0,$.jsx)(xn,{className:`size-3.5`})}),o&&(0,$.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:s?`Close row`:`Close canvas`,onClick:()=>o(e),children:(0,$.jsx)(G,{className:`size-3.5`})})]}),(0,$.jsx)(`div`,{className:`strip-canvas-body`,children:l})]})}function Fz(e){return J(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!yR(e)&&!vR(e)&&`p-page`)}function Iz({row:e,pathname:t,rowLabel:n,onCloseRow:r,workspaces:i}){let{focus:a,setFocus:o,toggleExpanded:s,closeCanvas:c,navigateCanvas:l}=gy(),u=(0,Q.useCallback)(e=>t=>l(e,t),[l]);return(0,$.jsxs)($.Fragment,{children:[t===`/`?(0,$.jsx)(`div`,{hidden:!0,children:(0,$.jsx)(Ul,{})}):(0,$.jsx)(Pz,{id:my,title:Nz(null,t,i),expanded:e.mainExpanded,focused:a===my,onFocus:o,onToggleExpanded:s,badge:n,onClose:r,children:(0,$.jsx)(`main`,{id:`content-area`,className:Fz(t),children:(0,$.jsx)(Ul,{})})}),e.entries.map(e=>(0,$.jsx)(Pz,{id:e.id,title:Nz(e,t,i),expanded:!!e.expanded,focused:a===e.id,onFocus:o,onToggleExpanded:s,contentHeader:e.kind===`document`,onClose:c,children:e.kind===`route`?(0,$.jsx)(`div`,{className:Fz(e.location.split(`?`)[0]),children:(0,$.jsx)(Ez,{location:e.location,onNavigate:u(e.id)})}):(0,$.jsx)(`div`,{className:`flex flex-1 min-h-0 min-w-0 items-stretch`,children:(0,$.jsx)(_R,{entry:e,onClose:()=>c(e.id),frame:{expanded:!!e.expanded,onToggleExpanded:()=>s(e.id)}})})},e.id))]})}function Lz({row:e,workspaces:t}){return(0,$.jsxs)(`div`,{className:`strip-ghost-row`,"aria-hidden":!0,children:[(0,$.jsx)(`span`,{className:`strip-ghost-chip strip-ghost-chip--main`,children:Nz(null,e.main,t)}),e.entries.map(n=>(0,$.jsx)(`span`,{className:`strip-ghost-chip`,children:Nz(n,e.main,t)},n.id))]})}function Rz(){let{state:e,closeM1:t,closeM2:n}=PT(),{rows:r,activeRow:i,focus:a,setFocus:o,moveRow:s,closeRow:c}=gy(),{pathname:l}=pl(),{workspaces:u}=hL(l.startsWith(`/workspaces/`)||r.some(e=>e.main.startsWith(`/workspaces/`)||e.entries.some(e=>e.kind===`route`&&e.location.startsWith(`/workspaces/`)))),d=AT(),f=(0,Q.useRef)(null);Fp(t,e.m1Open&&!e.m2Open),Fp(n,e.m2Open),(0,Q.useLayoutEffect)(()=>{let e=f.current;if(!e)return;let t=()=>{e.style.setProperty(`--strip-w`,`${e.clientWidth}px`),e.style.setProperty(`--strip-h`,`${e.clientHeight}px`)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let p=(0,Q.useRef)(e.m1Open);(0,Q.useEffect)(()=>{e.m1Open&&!p.current&&!e.m2Open&&o(`m1`),p.current=e.m1Open},[e.m1Open,e.m2Open,o]);let m=(0,Q.useRef)(e.m2Open);(0,Q.useEffect)(()=>{e.m2Open&&!m.current&&o(`m2`),!e.m2Open&&m.current&&a===`m2`&&o(e.m1Open?`m1`:my),m.current=e.m2Open},[e.m2Open,e.m1Open,a,o]),(0,Q.useEffect)(()=>{!e.m1Open&&a===`m1`&&o(my)},[e.m1Open,a,o]),(0,Q.useEffect)(()=>{let e=f.current,t=e?.querySelector(`[data-strip-col="${CSS.escape(a)}"]`);if(!(!e||!t))return Az(e,jz(e,t))},[a,r,i,e.m1Open,e.m2Open]);let h=(0,Q.useCallback)(()=>{let t=r[i];return[...e.m1Open?[`m1`]:[],...e.m2Open?[`m2`]:[],...l===`/`?[]:[my],...t?t.entries.map(e=>e.id):[]]},[r,i,e.m1Open,e.m2Open,l]);return(0,Q.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||!e.key.startsWith(`Arrow`)||!jT(e,d))return;let t=e.target;if(!(t?.closest(Dz)||t?.closest(`[role="dialog"]`))){if(e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=h(),n=t[Math.max(0,t.indexOf(a))+(e.key===`ArrowRight`?1:-1)];if(!n)return;e.preventDefault(),o(n)}else(e.key===`ArrowUp`||e.key===`ArrowDown`)&&r.length>1&&(e.preventDefault(),s(e.key===`ArrowDown`?1:-1))}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[h,a,o,s,r.length,d]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`strip-shell flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,$.jsx)(qI,{}),(0,$.jsxs)(`div`,{ref:f,className:`strip-scroller`,children:[e.m1Open&&(0,$.jsx)(`div`,{"data-strip-col":`m1`,className:J(`strip-col strip-menu-col`,a===`m1`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m1`),children:(0,$.jsx)(Mz,{section:e.activeSection})}),e.m2Open&&(0,$.jsx)(`div`,{"data-strip-col":`m2`,className:J(`strip-col strip-menu-col`,a===`m2`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m2`),children:(0,$.jsx)(nR,{})}),(0,$.jsx)(`div`,{className:`strip-rows`,style:{transform:`translateY(${-i*100}%)`},children:r.map((e,t)=>(0,$.jsx)(`div`,{className:J(`strip-row`,t===i&&`strip-row--active`),children:(0,$.jsx)(`div`,{className:`strip-row-canvases`,children:t===i?(0,$.jsx)(Iz,{row:e,workspaces:u,pathname:l,rowLabel:r.length>1?e.label:void 0,onCloseRow:t>0?()=>c(e.key):void 0}):(0,$.jsx)(Lz,{row:e,workspaces:u})})},e.key))})]}),(0,$.jsx)(YR,{}),(0,$.jsx)(mz,{})]}),(0,$.jsx)(CR,{}),(0,$.jsx)(KI,{}),(0,$.jsx)(hz,{})]})}function zz(){let e=xT();return(0,$.jsx)(AI,{children:(0,$.jsx)(ER,{children:(0,$.jsx)(CC,{children:(0,$.jsx)(QS,{children:(0,$.jsx)(yz,{children:e===`strip`?(0,$.jsx)(wz,{children:(0,$.jsx)(Aw,{children:(0,$.jsx)(Rz,{})})}):(0,$.jsxs)(Aw,{children:[(0,$.jsxs)(`div`,{className:`flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,$.jsx)(qI,{}),(0,$.jsx)(rR,{}),(0,$.jsx)(SR,{}),(0,$.jsx)(YR,{}),(0,$.jsx)(mz,{})]}),(0,$.jsx)(CR,{}),(0,$.jsx)(KI,{}),(0,$.jsx)(hz,{})]})})})})})})}var Bz=On,Vz=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(Wt,{ref:n,className:J(`fixed top-0 right-0 z-toast flex max-h-screen w-full flex-col-reverse gap-2 p-4 sm:right-0 sm:flex-col md:max-w-[420px]`,e),...t}));Vz.displayName=Wt.displayName;var Hz=_r(`group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-elevation-3 transition-all duration-normal data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full`,{variants:{variant:{default:`border bg-background`,destructive:`destructive group border-destructive bg-destructive text-destructive-foreground`}},defaultVariants:{variant:`default`}}),Uz=Q.forwardRef(({className:e,variant:t,...n},r)=>(0,$.jsx)(hn,{ref:r,className:J(Hz({variant:t}),e),...n}));Uz.displayName=hn.displayName;var Wz=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(qn,{ref:n,className:J(`inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive`,e),...t}));Wz.displayName=qn.displayName;var Gz=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(jt,{ref:n,className:J(`absolute right-2 top-2 rounded-md p-1 text-foreground/50 reveal-on-hover hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:text-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive group-[.destructive]:focus:ring-offset-destructive`,e),"toast-close":``,...t,children:(0,$.jsx)(G,{className:`h-4 w-4`})}));Gz.displayName=jt.displayName;var Kz=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(Yt,{ref:n,className:J(`text-sm font-semibold`,e),...t}));Kz.displayName=Yt.displayName;var qz=Q.forwardRef(({className:e,...t},n)=>(0,$.jsx)(zt,{ref:n,className:J(`text-sm opacity-90`,e),...t}));qz.displayName=zt.displayName;var Jz=`canvas-notifications`,Yz=`notifications`,Xz=`canvas:notification-history`,Zz,Qz;function $z(){try{let e=localStorage.getItem(`authToken`);if(e){let t=yr(e),n=t.sub||t.userId||t.id||t.email;if(typeof n==`string`||typeof n==`number`)return JSON.stringify([t.iss||``,n])}}catch{}return`anonymous`}function eB(){return Zz||=new Promise((e,t)=>{let n=indexedDB.open(Jz,1);n.onupgradeneeded=()=>{n.result.createObjectStore(Yz,{keyPath:[`account`,`id`]}).createIndex(`account`,`account`)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),Zz=void 0},e(t)},n.onerror=()=>t(n.error)}).catch(e=>{throw Zz=void 0,e}),Zz}function tB(){return!Qz&&typeof BroadcastChannel<`u`&&(Qz=new BroadcastChannel(Xz),Qz.onmessage=e=>window.dispatchEvent(new CustomEvent(Xz,{detail:e.data}))),Qz}function nB(e,t=!1){let n={account:e,error:t};window.dispatchEvent(new CustomEvent(Xz,{detail:n})),t||tB()?.postMessage(n)}function rB(e,t){tB();let n=n=>{let r=n.detail;r?.account===e&&t(!!r.error)};return window.addEventListener(Xz,n),()=>window.removeEventListener(Xz,n)}async function iB(e){let t=await eB();return new Promise((n,r)=>{let i=t.transaction(Yz,`readonly`),a=i.objectStore(Yz).index(`account`).getAll(e);i.oncomplete=()=>n(a.result.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)||e.id.localeCompare(t.id))),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error)})}async function aB(e,t){try{let n=await eB();await new Promise((e,r)=>{let i=n.transaction(Yz,`readwrite`);i.oncomplete=()=>e(),i.onabort=()=>r(i.error),i.onerror=()=>r(i.error),t(i.objectStore(Yz))}),nB(e)}catch(t){throw nB(e,!0),t}}function oB(e,t){return aB(e,n=>{let r=n.get([e,t.id]);r.onsuccess=()=>{r.result||n.put({...t,account:e})}})}function sB(e,t,n){return aB(e,r=>{let i=r.get([e,t]);i.onsuccess=()=>{i.result&&r.put({...i.result,...n})}})}function cB(e,t){return aB(e,n=>{n.delete([e,t])})}function lB(e){return aB(e,t=>{let n=t.index(`account`).openKeyCursor(e);n.onsuccess=()=>{n.result&&(t.delete(n.result.primaryKey),n.result.continue())}})}function uB({children:e}){let[t,n]=(0,Q.useState)([]),r=(0,Q.useRef)(new Set),i=(0,Q.useCallback)((e,t=!0)=>{if(wr(e.description)||wr(e.title))return;let i=`${e.title}:${e.description??``}`;if(t&&(e.historyId||!r.current.has(i))){let t=e.timestamp?new Date(e.timestamp):new Date;oB($z(),{id:e.historyId||crypto.randomUUID(),title:e.title,text:e.description||``,timestamp:Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString(),status:e.variant===`destructive`?`error`:`info`}).catch(()=>{})}if(r.current.has(i))return;r.current.add(i);let a=Math.random().toString(36).substring(2,9);n(t=>[...t,{...e,id:a}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==a)),r.current.delete(i)},5e3)},[]),a=(0,Q.useCallback)(e=>{let t=crypto.randomUUID(),r=$z();oB(r,{id:t,title:e.title,text:e.description||``,timestamp:new Date().toISOString(),status:`started`}).catch(()=>{}),n(n=>[...n,{...e,id:t,busy:!0}]);let a=!1,o=(e,o=!1)=>{a||(a=!0,n(e=>e.filter(e=>e.id!==t)),sB(r,t,{...e?{title:e.title,text:e.description||``}:{},status:o||e?.variant===`destructive`?`error`:`completed`}).catch(()=>{}),e&&i(e,!1))};return{update:e=>{a||n(n=>n.map(n=>n.id===t?{...n,...e}:n))},done:e=>o(e),fail:e=>o(e,!0)}},[i]),o=(0,Q.useMemo)(()=>({showToast:i,showProgress:a}),[i,a]);return(0,$.jsx)(Gr.Provider,{value:o,children:(0,$.jsxs)(Bz,{children:[e,t.map(e=>(0,$.jsxs)(Uz,{variant:e.variant,duration:e.busy?1/0:void 0,children:[(0,$.jsxs)(`div`,{className:`grid gap-1`,children:[(0,$.jsxs)(Kz,{className:`flex items-center gap-2`,children:[e.busy&&(0,$.jsx)(Yn,{className:`h-3.5 w-3.5 shrink-0 animate-spin`}),e.title]}),e.description!=null&&(0,$.jsx)(qz,{children:e.description})]}),!e.busy&&(0,$.jsx)(Gz,{})]},e.id)),(0,$.jsx)(Vz,{})]})})}function dB({children:e}){let[t]=(0,Q.useState)($z),[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(!1),{showToast:c}=Vr();(0,Q.useEffect)(()=>{let e=!0,n=0,i=async()=>{let i=++n;try{let o=await iB(t);e&&i===n&&(r(o),a(!1))}catch{e&&(s(!0),a(!1))}},o=rB(t,e=>{s(e),e||i()});return i(),()=>{e=!1,o()}},[t]),(0,Q.useEffect)(()=>hd.on(`notification`,e=>{let t=e;!t||![`string`,`number`].includes(typeof t.id)||typeof t.text!=`string`||!t.text||c({title:`Notification`,description:t.text,historyId:`message:${t.id}`,timestamp:typeof t.timestamp==`string`?t.timestamp:void 0})}),[c]);let l=(0,Q.useCallback)(async()=>{try{await lB(t)}catch{}},[t]),u=(0,Q.useCallback)(async e=>{try{await cB(t,e)}catch{}},[t]);return(0,$.jsx)(XR.Provider,{value:{notifications:n,loading:i,storageError:o,clear:l,remove:u},children:e})}var fB=e=>`${e.workspaceName}\0${e.treeName}\0${e.path}`;function pB({children:e}){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!0);(0,Q.useEffect)(()=>{let e=!1;return CL().then(t=>{e||n(t)}).catch(()=>{e||n({})}).finally(()=>{e||i(!1)}),()=>{e=!0}},[]);let a=(0,Q.useMemo)(()=>t?.home?.pinnedCanvases??[],[t]),[o]=(0,Q.useState)(()=>uO(CL,wL,n)),s=(0,Q.useCallback)(e=>a.some(t=>fB(t)===fB(e)),[a]),c=(0,Q.useCallback)(async e=>{let t=crypto.randomUUID();await o(n=>n.some(t=>fB(t)===fB(e))?n:[...n,{id:t,...e}])},[o]),l=(0,Q.useCallback)(async e=>{await o(t=>t.filter(t=>t.id!==e))},[o]),u=(0,Q.useCallback)(async(e,t)=>{await o(n=>n.map(n=>n.id===e?{...n,minimized:t}:n))},[o]),d=(0,Q.useCallback)(async(e,t)=>{await o(n=>{let r=n.find(t=>t.id===e);if(!r||e===t)return n;let i=n.filter(t=>t.id!==e),a=t===null?i.length:i.findIndex(e=>e.id===t);return a===-1?n:[...i.slice(0,a),r,...i.slice(a)]})},[o]),f=(0,Q.useMemo)(()=>({pins:a,isLoading:r,isPinned:s,pin:c,unpin:l,movePin:d,setMinimized:u}),[a,r,s,c,l,d,u]);return(0,$.jsx)(zE.Provider,{value:f,children:e})}var mB=(0,Q.lazy)(()=>g(()=>import(`./NextShell-Cm0yiVMy.js`),__vite__mapDeps([30,3,4,16,10,13,11,12,14,31])));function hB(){let{showToast:e}=Vr();return(0,Q.useEffect)(()=>{Er((t,n)=>{e({title:`Error`,description:n?`${t.message} (${n})`:t.message,variant:`destructive`})})},[e]),(0,Q.useEffect)(()=>PI(),[]),(0,$.jsxs)(Mu,{children:[(0,$.jsx)(DI,{}),(0,$.jsx)(Uw,{}),(0,$.jsxs)(Kl,{children:[(0,$.jsx)(Wl,{path:`/login`,element:(0,$.jsx)(Pd,{children:(0,$.jsx)(kd,{})})}),(0,$.jsx)(Wl,{path:`/register`,element:(0,$.jsx)(Pd,{children:(0,$.jsx)(Ad,{})})}),(0,$.jsx)(Wl,{path:`/auth/google/callback`,element:(0,$.jsx)(Pd,{children:(0,$.jsx)(jd,{})})}),(0,$.jsx)(Wl,{path:`/pub/c/:code`,element:(0,$.jsx)(gS,{})}),(0,$.jsx)(Wl,{path:`/apps/:appletId`,element:(0,$.jsx)(Nd,{children:(0,$.jsx)(Mw,{})})}),(0,$.jsx)(Wl,{path:`/next/*`,element:(0,$.jsx)(Nd,{children:(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(mB,{})})})}),(0,$.jsx)(Wl,{path:`/`,element:(0,$.jsx)(Nd,{children:(0,$.jsx)(dB,{children:(0,$.jsx)(pB,{children:(0,$.jsx)(zz,{})})})}),children:SI}),(0,$.jsx)(Wl,{path:`*`,element:(0,$.jsx)(Hl,{to:`/`,replace:!0})})]})]})}function gB(){return(0,$.jsx)(UA,{children:(0,$.jsx)(uB,{children:(0,$.jsx)(hB,{})})})}sA(),$k(),(0,Ws.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(Q.StrictMode,{children:(0,$.jsx)(gB,{})}));