@augmentd-labs/canvas-web 2.20.3 → 2.20.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.
- package/dist/assets/{NextShell-CjpKDJo8.js → NextShell-CichxWps.js} +1 -1
- package/dist/assets/{SketchEditor-QHhsUFje.js → SketchEditor-K3h9uQVw.js} +1 -1
- package/dist/assets/{TextDocumentEditor-DokHJlgX.js → TextDocumentEditor-CB5pebVj.js} +1 -1
- package/dist/assets/{index-CF2LyRj6.js → index-nirphMGg.js} +7 -7
- package/dist/assets/{sha256-DHKenB0x.js → sha256-DMvynruD.js} +1 -1
- package/dist/assets/{text-documents-CO7tM3Vd.js → text-documents-BVErBT1d.js} +1 -1
- package/dist/assets/workspace-csrHeFtj.js +1 -0
- package/dist/index.html +4 -4
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/workspace-DEC1Z8Cv.js +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
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-B0qjhx3p.js","assets/rolldown-runtime-C0FnF6B9.js","assets/react-DQazvoR7.js","assets/sanitize-DrVcFY1Q.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/markdown-html-DtQ7-esK.css","assets/SketchEditor-
|
|
2
|
-
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{Ct as a,St as o,_t as s,bt as c,st as l,vt as u,wt as d,xt as f,yt as p}from"./react-DQazvoR7.js";import{t as m}from"./preload-helper-Czpn1I53.js";import{$ as h,$n as g,$r as _,$t as v,An as y,Ar as b,At as x,B as S,Bn as C,Br as w,Bt as T,C as E,Cn as D,Cr as O,Ct as k,Dn as A,Dr as j,Dt as M,En as N,Er as P,Et as ee,F,Fn as I,Fr as L,Ft as R,G as te,Gn as ne,Gr as z,Gt as re,H as ie,Hn as ae,Hr as oe,Ht as se,I as B,Ir as ce,It as V,J as le,Jn as ue,Jr as de,Jt as fe,K as pe,Kn as me,Kr as he,Kt as ge,L as _e,Lr as ve,Lt as ye,Mn as H,Mr as be,Mt as U,Nn as xe,Nr as Se,Nt as Ce,On as W,Or as G,Ot as we,Pn as Te,Pr as Ee,Pt as De,Q as Oe,Qn as ke,Qr as Ae,Qt as je,R as Me,Rn as Ne,Rr as Pe,Rt as Fe,S as Ie,Sn as Le,Sr as Re,St as ze,T as Be,Tr as Ve,Tt as He,U as Ue,Un as We,Ur as Ge,Ut as Ke,V as qe,Vn as Je,Vr as Ye,Vt as Xe,W as Ze,Wn as Qe,Wr as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zr as dt,Zt as ft,_ as pt,_i as mt,_n as ht,_r as gt,_t,ai as vt,an as yt,ar as bt,at as xt,b as St,bn as Ct,br as wt,bt as Tt,ci as Et,cn as Dt,cr as Ot,ct as kt,d as At,di as jt,dn as Mt,dr as Nt,dt as Pt,ei as Ft,en as It,er as Lt,et as Rt,f as zt,fi as Bt,fr as Vt,ft as Ht,g as Ut,gi as Wt,gn as Gt,gr as Kt,gt as qt,h as Jt,hi as Yt,hn as Xt,hr as Zt,ht as Qt,ii as $t,in as en,ir as tn,it as nn,jn as rn,jr as an,jt as on,kn as sn,kr as cn,kt as ln,li as un,ln as dn,lr as fn,lt as pn,m as mn,mi as hn,mr as gn,mt as _n,ni as vn,nn as yn,nr as bn,nt as xn,oi as Sn,on as Cn,or as wn,ot as Tn,p as En,pi as Dn,pn as On,pr as kn,pt as An,q as jn,qn as Mn,qr as Nn,qt as Pn,rn as Fn,rr as In,rt as Ln,si as Rn,sn as zn,sr as Bn,st as Vn,ti as Hn,tn as Un,tr as Wn,tt as Gn,u as Kn,ui as qn,un as Jn,ur as Yn,ut as Xn,v as Zn,vi as Qn,vn as $n,vr as er,vt as tr,w as nr,wn as rr,wr as ir,wt as ar,x as or,xn as sr,xr as cr,xt as lr,y as ur,yn as dr,yr as fr,yt as pr,z as mr,zn as hr,zr as gr,zt as _r}from"./ui-BX_B5WCf.js";import{i as vr,n as yr,r as br}from"./utils-BxVxyehK.js";import{n as xr,t as K}from"./utils-2pl1SbIp.js";import{_ as Sr,a as Cr,b as q,c as wr,d as Tr,f as Er,g as Dr,h as Or,i as kr,l as Ar,m as jr,n as Mr,o as Nr,p as Pr,r as Fr,s as Ir,t as Lr,u as J,v as Rr,x as Y,y as zr}from"./alert-dialog-C7BWAVBm.js";import{t as Br}from"./socket-hM4c-ZSl.js";import{c as Vr,i as Hr,n as Ur,o as Wr,s as Gr,t as Kr}from"./blobs-Depc3N3o.js";import{$ as qr,$t as Jr,A 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,En as oi,Et as si,F as ci,Ft as li,G as ui,Gt as di,H as fi,Ht as pi,I as mi,In as hi,It as gi,J 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,N 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,Rn as Li,Rt as Ri,S as zi,Sn as Bi,St as Vi,T as Hi,Tn as Ui,Tt as Wi,U as Gi,Ut as Ki,V as qi,Vt as Ji,W as Yi,Wt as Xi,X as Zi,Xt as Qi,Y as $i,Yt as ea,Z as ta,Zt as na,_ as ra,_n as ia,_t as aa,a as oa,an as sa,at as ca,b as la,bn as ua,bt as da,c as fa,cn as pa,ct as ma,d as ha,dn as ga,dt as _a,en as va,et as ya,f as ba,fn as xa,ft as Sa,g as Ca,gn as wa,gt as Ta,h as Ea,hn as Da,ht as Oa,i as ka,in as Aa,it as ja,jt as Ma,k as Na,kn as Pa,kt as Fa,l as Ia,ln as La,lt as Ra,m as za,mn as Ba,mt as Va,n as Ha,nn as Ua,nt as Wa,o as Ga,on as Ka,ot as qa,p as Ja,pn as Ya,pt as Xa,q as Za,qt as Qa,r as $a,rn as eo,rt as to,s as no,sn as ro,st as io,t as ao,tn as oo,tt as so,u as co,un as lo,ut as uo,v as fo,vn as po,vt as mo,w as ho,wn as go,wt as _o,x as vo,xt as yo,y as bo,yn as xo,yt as So,z as Co,zn as wo,zt as To}from"./workspace-DEC1Z8Cv.js";import{n as Eo,t as Do}from"./map-BxCwdK0d.js";import{t as Oo}from"./search-COMZIxA7.js";import{a as ko,c as Ao,d as jo,f as Mo,i as No,l as Po,n as Fo,o as Io,p as Lo,r as Ro,s as zo,t as Bo,u as Vo}from"./text-documents-CO7tM3Vd.js";import{A as Ho,B as Uo,C as Wo,D as Go,E as Ko,F as qo,H as Jo,I as Yo,L as Xo,M as Zo,N as Qo,O as $o,P as es,R as ts,S as ns,T as rs,V as is,_ as as,a as os,b as ss,c as cs,d as ls,f as us,g as ds,h as fs,i as ps,j as ms,k as hs,l as gs,m as _s,o as vs,p as ys,r as bs,s as xs,t as Ss,u as Cs,v as ws,w as Ts,x as Es,y as Ds,z as Os}from"./sha256-DHKenB0x.js";import{t as ks}from"./sanitize-DrVcFY1Q.js";import{t as As}from"./markdown-it-DRESbtwK.js";import{n as js,t as Ms}from"./use-theme-pnVLU4Kg.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var X=n(d(),1),Ns=o(),Ps=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,Fs=/^[\\/]{2}/;function Is(e,t){return t+e.replace(/\\/g,`/`)}var Ls=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(Ls||{}),Rs=`popstate`;function zs(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function Bs(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return Gs(``,{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:Ks(t)}return Js(t,n,null,e)}function Vs(e,t){if(e===!1||e==null)throw Error(t)}function Hs(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function Us(){return Math.random().toString(36).substring(2,10)}function Ws(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 Gs(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?qs(t):t,state:n,key:t&&t.key||r||Us(),mask:i}}function Ks({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 qs(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 Js(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=zs(e)?e:Gs(h.location,e,t);n&&n(r,e),l=u()+1;let d=Ws(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=zs(e)?e:Gs(h.location,e,t);n&&n(r,e),l=u();let i=Ws(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 Ys(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(Rs,d),c=e,()=>{i.removeEventListener(Rs,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 Ys(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Vs(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:Ks(t);return i=i.replace(/ $/,`%20`),!n&&Fs.test(i)&&(i=r+i),new URL(i,r)}function Xs(e,t,n=`/`){return Zs(e,t,n,!1)}function Zs(e,t,n,r,i){let a=gc((typeof t==`string`?qs(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Qs(e),s=null,c=hc(a);for(let e=0;s==null&&e<o.length;++e)s=dc(o[e],c,r);return s}function Qs(e){let t=$s(e);return tc(t),t}function $s(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;Vs(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=wc([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Vs(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),$s(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:lc(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=mc(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 ec(e.path))a(e,t,!0,n)}),t}function ec(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=ec(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 tc(e){e.sort((e,t)=>e.score===t.score?uc(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var nc=/^:[\w-]+$/,rc=3,ic=2,ac=1,oc=10,sc=-2,cc=e=>e===`*`;function lc(e,t){let n=e.split(`/`),r=n.length;return n.some(cc)&&(r+=sc),t&&(r+=ic),n.filter(e=>!cc(e)).reduce((e,t)=>e+(nc.test(t)?rc:t===``?ac:oc),r)}function uc(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 dc(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?pc(u,l,s.matcher,s.compiledParams):fc(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=fc({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:wc([a,d.pathname]),pathnameBase:Ec(wc([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=wc([a,d.pathnameBase]))}return o}function fc(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=mc(e.path,e.caseSensitive,e.end);return pc(e,t,n,r)}function pc(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 mc(e,t=!1,n=!0){Hs(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 hc(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return Hs(!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 gc(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 _c(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?qs(e):e,a;return n?(n=Cc(n),a=n.startsWith(`/`)?vc(n.substring(1),`/`):vc(n,t)):a=t,{pathname:a,search:Dc(r),hash:Oc(i)}}function vc(e,t){let n=Tc(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function yc(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 bc(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function xc(e){let t=bc(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function Sc(e,t,n,r=!1){let i;typeof e==`string`?i=qs(e):(i={...e},Vs(!i.pathname||!i.pathname.includes(`?`),yc(`?`,`pathname`,`search`,i)),Vs(!i.pathname||!i.pathname.includes(`#`),yc(`#`,`pathname`,`hash`,i)),Vs(!i.search||!i.search.includes(`#`),yc(`#`,`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=_c(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Cc=e=>e.replace(/[\\/]{2,}/g,`/`),wc=e=>Cc(e.join(`/`)),Tc=e=>e.replace(/\/+$/,``),Ec=e=>Tc(e).replace(/^\/*/,`/`),Dc=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Oc=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,kc=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 Ac(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function jc(e){return wc(e.map(e=>e.route.path).filter(Boolean))||`/`}var Mc=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Nc(e,t){let n=e;if(typeof n!=`string`||!Ps.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(Mc)try{let e=new URL(window.location.href),r=Fs.test(n)?new URL(Is(n,e.protocol)):new URL(n),a=gc(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{Hs(!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 Pc=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Pc);var Fc=[`GET`,...Pc];new Set(Fc);var Ic=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Lc(e){try{return Ic.includes(new URL(e).protocol)}catch{return!1}}var Rc=X.createContext(null);Rc.displayName=`DataRouter`;var zc=X.createContext(null);zc.displayName=`DataRouterState`;var Bc=X.createContext(!1);function Vc(){return X.useContext(Bc)}var Hc=X.createContext({isTransitioning:!1});Hc.displayName=`ViewTransition`;var Uc=X.createContext(new Map);Uc.displayName=`Fetchers`;var Wc=X.createContext(null);Wc.displayName=`Await`;var Gc=X.createContext(null);Gc.displayName=`Navigation`;var Kc=X.createContext(null);Kc.displayName=`Location`;var qc=X.createContext({outlet:null,matches:[],isDataRoute:!1});qc.displayName=`Route`;var Jc=X.createContext(null);Jc.displayName=`RouteError`;var Yc=`REACT_ROUTER_ERROR`,Xc=`REDIRECT`,Zc=`ROUTE_ERROR_RESPONSE`;function Qc(e){if(e.startsWith(`${Yc}:${Xc}:{`))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 $c(e){if(e.startsWith(`${Yc}:${Zc}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new kc(t.status,t.statusText,t.data)}catch{}}function el(e,{relative:t}={}){Vs(tl(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=X.useContext(Gc),{hash:i,pathname:a,search:o}=ul(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:wc([n,a])),r.createHref({pathname:s,search:o,hash:i})}function tl(){return X.useContext(Kc)!=null}function nl(){return Vs(tl(),`useLocation() may be used only in the context of a <Router> component.`),X.useContext(Kc).location}var rl=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function il(e){X.useContext(Gc).static||X.useLayoutEffect(e)}function al(){let{isDataRoute:e}=X.useContext(qc);return e?Dl():ol()}function ol(){Vs(tl(),`useNavigate() may be used only in the context of a <Router> component.`);let e=X.useContext(Rc),{basename:t,navigator:n}=X.useContext(Gc),{matches:r}=X.useContext(qc),{pathname:i}=nl(),a=JSON.stringify(xc(r)),o=X.useRef(!1);return il(()=>{o.current=!0}),X.useCallback((r,s={})=>{if(Hs(o.current,rl),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=Sc(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:wc([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var sl=X.createContext(null);function cl(e){let t=X.useContext(qc).outlet;return X.useMemo(()=>t&&X.createElement(sl.Provider,{value:e},t),[t,e])}function ll(){let{matches:e}=X.useContext(qc);return e[e.length-1]?.params??{}}function ul(e,{relative:t}={}){let{matches:n}=X.useContext(qc),{pathname:r}=nl(),i=JSON.stringify(xc(n));return X.useMemo(()=>Sc(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function dl(e,t){return fl(e,t)}function fl(e,t,n){Vs(tl(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=X.useContext(Gc),{matches:i}=X.useContext(qc),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||``;kl(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.
|
|
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-B0qjhx3p.js","assets/rolldown-runtime-C0FnF6B9.js","assets/react-DQazvoR7.js","assets/sanitize-DrVcFY1Q.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/markdown-html-DtQ7-esK.css","assets/SketchEditor-K3h9uQVw.js","assets/ui-BX_B5WCf.js","assets/utils-BxVxyehK.js","assets/alert-dialog-C7BWAVBm.js","assets/utils-2pl1SbIp.js","assets/blobs-Depc3N3o.js","assets/workspace-csrHeFtj.js","assets/sha256-DMvynruD.js","assets/chunk-K2UTITRG-D0fgw4vC.js","assets/chunk-SRAX5OIU-Dhm3gOdh.js","assets/chunk-6U3AYISY-C6-Mtja1.js","assets/chunk-Z3N5DIM6-D9TMVU7m.js","assets/EditorOverlay-3oRTnifg.js","assets/SketchEditor-DtRVLazd.css","assets/TextDocumentEditor-CB5pebVj.js","assets/text-documents-BVErBT1d.js","assets/LocationTab-ARqmeXmv.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/subtree-transfer-dialog-9UozkUFv.js","assets/NextShell-CichxWps.js","assets/NextShell-B4NeoNB5.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a as e,n as t,o as n,r,t as i}from"./rolldown-runtime-C0FnF6B9.js";import{Ct as a,St as o,_t as s,bt as c,st as l,vt as u,wt as d,xt as f,yt as p}from"./react-DQazvoR7.js";import{t as m}from"./preload-helper-Czpn1I53.js";import{$ as h,$n as g,$r as _,$t as v,An as y,Ar as b,At as x,B as S,Bn as C,Br as w,Bt as T,C as E,Cn as D,Cr as O,Ct as k,Dn as A,Dr as j,Dt as M,En as N,Er as P,Et as ee,F,Fn as I,Fr as L,Ft as R,G as te,Gn as ne,Gr as z,Gt as re,H as ie,Hn as ae,Hr as oe,Ht as se,I as B,Ir as ce,It as V,J as le,Jn as ue,Jr as de,Jt as fe,K as pe,Kn as me,Kr as he,Kt as ge,L as _e,Lr as ve,Lt as ye,Mn as H,Mr as be,Mt as U,Nn as xe,Nr as Se,Nt as Ce,On as W,Or as G,Ot as we,Pn as Te,Pr as Ee,Pt as De,Q as Oe,Qn as ke,Qr as Ae,Qt as je,R as Me,Rn as Ne,Rr as Pe,Rt as Fe,S as Ie,Sn as Le,Sr as Re,St as ze,T as Be,Tr as Ve,Tt as He,U as Ue,Un as We,Ur as Ge,Ut as Ke,V as qe,Vn as Je,Vr as Ye,Vt as Xe,W as Ze,Wn as Qe,Wr as $e,Wt as et,X as tt,Xn as nt,Xr as rt,Xt as it,Y as at,Yn as ot,Yr as st,Yt as ct,Z as lt,Zn as ut,Zr as dt,Zt as ft,_ as pt,_i as mt,_n as ht,_r as gt,_t,ai as vt,an as yt,ar as bt,at as xt,b as St,bn as Ct,br as wt,bt as Tt,ci as Et,cn as Dt,cr as Ot,ct as kt,d as At,di as jt,dn as Mt,dr as Nt,dt as Pt,ei as Ft,en as It,er as Lt,et as Rt,f as zt,fi as Bt,fr as Vt,ft as Ht,g as Ut,gi as Wt,gn as Gt,gr as Kt,gt as qt,h as Jt,hi as Yt,hn as Xt,hr as Zt,ht as Qt,ii as $t,in as en,ir as tn,it as nn,jn as rn,jr as an,jt as on,kn as sn,kr as cn,kt as ln,li as un,ln as dn,lr as fn,lt as pn,m as mn,mi as hn,mr as gn,mt as _n,ni as vn,nn as yn,nr as bn,nt as xn,oi as Sn,on as Cn,or as wn,ot as Tn,p as En,pi as Dn,pn as On,pr as kn,pt as An,q as jn,qn as Mn,qr as Nn,qt as Pn,rn as Fn,rr as In,rt as Ln,si as Rn,sn as zn,sr as Bn,st as Vn,ti as Hn,tn as Un,tr as Wn,tt as Gn,u as Kn,ui as qn,un as Jn,ur as Yn,ut as Xn,v as Zn,vi as Qn,vn as $n,vr as er,vt as tr,w as nr,wn as rr,wr as ir,wt as ar,x as or,xn as sr,xr as cr,xt as lr,y as ur,yn as dr,yr as fr,yt as pr,z as mr,zn as hr,zr as gr,zt as _r}from"./ui-BX_B5WCf.js";import{i as vr,n as yr,r as br}from"./utils-BxVxyehK.js";import{n as xr,t as K}from"./utils-2pl1SbIp.js";import{_ as Sr,a as Cr,b as q,c as wr,d as Tr,f as Er,g as Dr,h as Or,i as kr,l as Ar,m as jr,n as Mr,o as Nr,p as Pr,r as Fr,s as Ir,t as Lr,u as J,v as Rr,x as Y,y as zr}from"./alert-dialog-C7BWAVBm.js";import{t as Br}from"./socket-hM4c-ZSl.js";import{c as Vr,i as Hr,n as Ur,o as Wr,s as Gr,t as Kr}from"./blobs-Depc3N3o.js";import{$ as qr,$t as Jr,A 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,En as oi,Et as si,F as ci,Ft as li,G as ui,Gt as di,H as fi,Ht as pi,I as mi,In as hi,It as gi,J 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,N 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,Rn as Li,Rt as Ri,S as zi,Sn as Bi,St as Vi,T as Hi,Tn as Ui,Tt as Wi,U as Gi,Ut as Ki,V as qi,Vt as Ji,W as Yi,Wt as Xi,X as Zi,Xt as Qi,Y as $i,Yt as ea,Z as ta,Zt as na,_ as ra,_n as ia,_t as aa,a as oa,an as sa,at as ca,b as la,bn as ua,bt as da,c as fa,cn as pa,ct as ma,d as ha,dn as ga,dt as _a,en as va,et as ya,f as ba,fn as xa,ft as Sa,g as Ca,gn as wa,gt as Ta,h as Ea,hn as Da,ht as Oa,i as ka,in as Aa,it as ja,jt as Ma,k as Na,kn as Pa,kt as Fa,l as Ia,ln as La,lt as Ra,m as za,mn as Ba,mt as Va,n as Ha,nn as Ua,nt as Wa,o as Ga,on as Ka,ot as qa,p as Ja,pn as Ya,pt as Xa,q as Za,qt as Qa,r as $a,rn as eo,rt as to,s as no,sn as ro,st as io,t as ao,tn as oo,tt as so,u as co,un as lo,ut as uo,v as fo,vn as po,vt as mo,w as ho,wn as go,wt as _o,x as vo,xt as yo,y as bo,yn as xo,yt as So,z as Co,zn as wo,zt as To}from"./workspace-csrHeFtj.js";import{n as Eo,t as Do}from"./map-BxCwdK0d.js";import{t as Oo}from"./search-COMZIxA7.js";import{a as ko,c as Ao,d as jo,f as Mo,i as No,l as Po,n as Fo,o as Io,p as Lo,r as Ro,s as zo,t as Bo,u as Vo}from"./text-documents-BVErBT1d.js";import{A as Ho,B as Uo,C as Wo,D as Go,E as Ko,F as qo,H as Jo,I as Yo,L as Xo,M as Zo,N as Qo,O as $o,P as es,R as ts,S as ns,T as rs,V as is,_ as as,a as os,b as ss,c as cs,d as ls,f as us,g as ds,h as fs,i as ps,j as ms,k as hs,l as gs,m as _s,o as vs,p as ys,r as bs,s as xs,t as Ss,u as Cs,v as ws,w as Ts,x as Es,y as Ds,z as Os}from"./sha256-DMvynruD.js";import{t as ks}from"./sanitize-DrVcFY1Q.js";import{t as As}from"./markdown-it-DRESbtwK.js";import{n as js,t as Ms}from"./use-theme-pnVLU4Kg.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var X=n(d(),1),Ns=o(),Ps=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,Fs=/^[\\/]{2}/;function Is(e,t){return t+e.replace(/\\/g,`/`)}var Ls=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(Ls||{}),Rs=`popstate`;function zs(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function Bs(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return Gs(``,{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:Ks(t)}return Js(t,n,null,e)}function Vs(e,t){if(e===!1||e==null)throw Error(t)}function Hs(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function Us(){return Math.random().toString(36).substring(2,10)}function Ws(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 Gs(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?qs(t):t,state:n,key:t&&t.key||r||Us(),mask:i}}function Ks({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 qs(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 Js(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=zs(e)?e:Gs(h.location,e,t);n&&n(r,e),l=u()+1;let d=Ws(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=zs(e)?e:Gs(h.location,e,t);n&&n(r,e),l=u();let i=Ws(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 Ys(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(Rs,d),c=e,()=>{i.removeEventListener(Rs,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 Ys(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Vs(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:Ks(t);return i=i.replace(/ $/,`%20`),!n&&Fs.test(i)&&(i=r+i),new URL(i,r)}function Xs(e,t,n=`/`){return Zs(e,t,n,!1)}function Zs(e,t,n,r,i){let a=gc((typeof t==`string`?qs(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Qs(e),s=null,c=hc(a);for(let e=0;s==null&&e<o.length;++e)s=dc(o[e],c,r);return s}function Qs(e){let t=$s(e);return tc(t),t}function $s(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;Vs(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=wc([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Vs(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),$s(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:lc(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=mc(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 ec(e.path))a(e,t,!0,n)}),t}function ec(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=ec(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 tc(e){e.sort((e,t)=>e.score===t.score?uc(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var nc=/^:[\w-]+$/,rc=3,ic=2,ac=1,oc=10,sc=-2,cc=e=>e===`*`;function lc(e,t){let n=e.split(`/`),r=n.length;return n.some(cc)&&(r+=sc),t&&(r+=ic),n.filter(e=>!cc(e)).reduce((e,t)=>e+(nc.test(t)?rc:t===``?ac:oc),r)}function uc(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 dc(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?pc(u,l,s.matcher,s.compiledParams):fc(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=fc({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:wc([a,d.pathname]),pathnameBase:Ec(wc([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=wc([a,d.pathnameBase]))}return o}function fc(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=mc(e.path,e.caseSensitive,e.end);return pc(e,t,n,r)}function pc(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 mc(e,t=!1,n=!0){Hs(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 hc(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return Hs(!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 gc(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 _c(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?qs(e):e,a;return n?(n=Cc(n),a=n.startsWith(`/`)?vc(n.substring(1),`/`):vc(n,t)):a=t,{pathname:a,search:Dc(r),hash:Oc(i)}}function vc(e,t){let n=Tc(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function yc(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 bc(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function xc(e){let t=bc(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function Sc(e,t,n,r=!1){let i;typeof e==`string`?i=qs(e):(i={...e},Vs(!i.pathname||!i.pathname.includes(`?`),yc(`?`,`pathname`,`search`,i)),Vs(!i.pathname||!i.pathname.includes(`#`),yc(`#`,`pathname`,`hash`,i)),Vs(!i.search||!i.search.includes(`#`),yc(`#`,`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=_c(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Cc=e=>e.replace(/[\\/]{2,}/g,`/`),wc=e=>Cc(e.join(`/`)),Tc=e=>e.replace(/\/+$/,``),Ec=e=>Tc(e).replace(/^\/*/,`/`),Dc=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Oc=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,kc=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 Ac(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function jc(e){return wc(e.map(e=>e.route.path).filter(Boolean))||`/`}var Mc=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Nc(e,t){let n=e;if(typeof n!=`string`||!Ps.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(Mc)try{let e=new URL(window.location.href),r=Fs.test(n)?new URL(Is(n,e.protocol)):new URL(n),a=gc(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{Hs(!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 Pc=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Pc);var Fc=[`GET`,...Pc];new Set(Fc);var Ic=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Lc(e){try{return Ic.includes(new URL(e).protocol)}catch{return!1}}var Rc=X.createContext(null);Rc.displayName=`DataRouter`;var zc=X.createContext(null);zc.displayName=`DataRouterState`;var Bc=X.createContext(!1);function Vc(){return X.useContext(Bc)}var Hc=X.createContext({isTransitioning:!1});Hc.displayName=`ViewTransition`;var Uc=X.createContext(new Map);Uc.displayName=`Fetchers`;var Wc=X.createContext(null);Wc.displayName=`Await`;var Gc=X.createContext(null);Gc.displayName=`Navigation`;var Kc=X.createContext(null);Kc.displayName=`Location`;var qc=X.createContext({outlet:null,matches:[],isDataRoute:!1});qc.displayName=`Route`;var Jc=X.createContext(null);Jc.displayName=`RouteError`;var Yc=`REACT_ROUTER_ERROR`,Xc=`REDIRECT`,Zc=`ROUTE_ERROR_RESPONSE`;function Qc(e){if(e.startsWith(`${Yc}:${Xc}:{`))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 $c(e){if(e.startsWith(`${Yc}:${Zc}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new kc(t.status,t.statusText,t.data)}catch{}}function el(e,{relative:t}={}){Vs(tl(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=X.useContext(Gc),{hash:i,pathname:a,search:o}=ul(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:wc([n,a])),r.createHref({pathname:s,search:o,hash:i})}function tl(){return X.useContext(Kc)!=null}function nl(){return Vs(tl(),`useLocation() may be used only in the context of a <Router> component.`),X.useContext(Kc).location}var rl=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function il(e){X.useContext(Gc).static||X.useLayoutEffect(e)}function al(){let{isDataRoute:e}=X.useContext(qc);return e?Dl():ol()}function ol(){Vs(tl(),`useNavigate() may be used only in the context of a <Router> component.`);let e=X.useContext(Rc),{basename:t,navigator:n}=X.useContext(Gc),{matches:r}=X.useContext(qc),{pathname:i}=nl(),a=JSON.stringify(xc(r)),o=X.useRef(!1);return il(()=>{o.current=!0}),X.useCallback((r,s={})=>{if(Hs(o.current,rl),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=Sc(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:wc([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var sl=X.createContext(null);function cl(e){let t=X.useContext(qc).outlet;return X.useMemo(()=>t&&X.createElement(sl.Provider,{value:e},t),[t,e])}function ll(){let{matches:e}=X.useContext(qc);return e[e.length-1]?.params??{}}function ul(e,{relative:t}={}){let{matches:n}=X.useContext(qc),{pathname:r}=nl(),i=JSON.stringify(xc(n));return X.useMemo(()=>Sc(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function dl(e,t){return fl(e,t)}function fl(e,t,n){Vs(tl(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=X.useContext(Gc),{matches:i}=X.useContext(qc),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||``;kl(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=nl(),d;if(t){let e=typeof t==`string`?qs(t):t;Vs(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})):Xs(e,{pathname:p});Hs(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Hs(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=yl(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:wc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:wc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?X.createElement(Kc.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function pl(){let e=El(),t=Ac(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=X.createElement(X.Fragment,null,X.createElement(`p`,null,`💿 Hey developer 👋`),X.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,X.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,X.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),X.createElement(X.Fragment,null,X.createElement(`h2`,null,`Unexpected Application Error!`),X.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?X.createElement(`pre`,{style:i},n):null,o)}var ml=X.createElement(pl,null),hl=class extends X.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=$c(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:X.createElement(qc.Provider,{value:this.props.routeContext},X.createElement(Jc.Provider,{value:e,children:this.props.component}));return this.context?X.createElement(_l,{error:e},t):t}};hl.contextType=Bc;var gl=new WeakMap;function _l({children:e,error:t}){let{basename:n}=X.useContext(Gc);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Qc(t.digest);if(e){let r=gl.get(t);if(r)throw r;let i=Nc(e.location,n),a=i.absoluteURL||i.to;if(Lc(a))throw Error(`Invalid redirect location`);if(Mc&&!gl.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 gl.set(t,n),n}}return X.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function vl({routeContext:e,match:t,children:n}){let r=X.useContext(Rc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),X.createElement(qc.Provider,{value:e},n)}function yl(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);Vs(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:jc(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||ml,o&&(s<0&&c===0?(kl(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?X.createElement(n.route.Component,null):n.route.element?n.route.element:e,X.createElement(vl,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?X.createElement(hl,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function bl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function xl(e){let t=X.useContext(Rc);return Vs(t,bl(e)),t}function Sl(e){let t=X.useContext(zc);return Vs(t,bl(e)),t}function Cl(e){let t=X.useContext(qc);return Vs(t,bl(e)),t}function wl(e){let t=Cl(e),n=t.matches[t.matches.length-1];return Vs(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Tl(){return wl(`useRouteId`)}function El(){let e=X.useContext(Jc),t=Sl(`useRouteError`),n=wl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Dl(){let{router:e}=xl(`useNavigate`),t=wl(`useNavigate`),n=X.useRef(!1);return il(()=>{n.current=!0}),X.useCallback(async(r,i={})=>{Hs(n.current,rl),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Ol={};function kl(e,t,n){!t&&!Ol[e]&&(Ol[e]=!0,Hs(!1,n))}X.memo(Al);function Al({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return fl(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function jl({to:e,replace:t,state:n,relative:r}){Vs(tl(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=X.useContext(Gc);Hs(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=X.useContext(qc),{pathname:o}=nl(),s=al(),c=Sc(e,xc(a),o,r===`path`),l=JSON.stringify(c);return X.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function Ml(e){return cl(e.context)}function Nl(e){Vs(!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 Pl({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Vs(!tl(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=X.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=qs(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=X.useMemo(()=>{let e=gc(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 Hs(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:X.createElement(Gc.Provider,{value:c},X.createElement(Kc.Provider,{children:t,value:h}))}function Fl({children:e,location:t}){return dl(Il(e),t)}X.Component;function Il(e,t=[]){let n=[];return X.Children.forEach(e,(e,r)=>{if(!X.isValidElement(e))return;let i=[...t,r];if(e.type===X.Fragment){n.push.apply(n,Il(e.props.children,i));return}Vs(e.type===Nl,`[${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>`),Vs(!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=Il(e.props.children,i)),n.push(a)}),n}var Ll=`get`,Rl=`application/x-www-form-urlencoded`;function zl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Bl(e){return zl(e)&&e.tagName.toLowerCase()===`button`}function Vl(e){return zl(e)&&e.tagName.toLowerCase()===`form`}function Hl(e){return zl(e)&&e.tagName.toLowerCase()===`input`}function Ul(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Wl(e,t){return e.button===0&&(!t||t===`_self`)&&!Ul(e)}function Gl(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 Kl(e,t){let n=Gl(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var ql=null;function Jl(){if(ql===null)try{new FormData(document.createElement(`form`),0),ql=!1}catch{ql=!0}return ql}var Yl=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Xl(e){return e!=null&&!Yl.has(e)?(Hs(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Rl}"`),null):e}function Zl(e,t){let n,r,i,a,o;if(Vl(e)){let o=e.getAttribute(`action`);r=o?gc(o,t):null,n=e.getAttribute(`method`)||Ll,i=Xl(e.getAttribute(`enctype`))||Rl,a=new FormData(e)}else if(Bl(e)||Hl(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?gc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Ll,i=Xl(e.getAttribute(`formenctype`))||Xl(o.getAttribute(`enctype`))||Rl,a=new FormData(o,e),!Jl()){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(zl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Ll,r=null,i=Rl,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 Ql(e,t){if(e===!1||e==null)throw Error(t)}function $l(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&&gc(i.pathname,t)===`/`?`${Tc(t)}/_root.${r}`:`${Tc(i.pathname)}.${r}`,i}async function eu(e,t){if(e.id in t)return t[e.id];try{let n=await m(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function tu(e){return e!=null&&typeof e.page==`string`}function nu(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 ru(e,t,n){return cu((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await eu(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(nu).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function iu(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 au(e,t,{includeHydrateFallback:n}={}){return ou(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 ou(e){return[...new Set(e)]}function su(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function cu(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!tu(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(su(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function lu(){let e=X.useContext(Rc);return Ql(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function uu(){let e=X.useContext(zc);return Ql(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var du=X.createContext(void 0);du.displayName=`FrameworkContext`;function fu(){let e=X.useContext(du);return Ql(e,`You must render this element inside a <HydratedRouter> element`),e}function pu(e,t){let n=X.useContext(du),[r,i]=X.useState(!1),[a,o]=X.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=X.useRef(null);X.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),X.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:mu(s,p),onBlur:mu(c,m),onMouseEnter:mu(l,p),onMouseLeave:mu(u,m),onTouchStart:mu(d,p)}]:[a,f,{}]:[!1,f,{}]}function mu(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function hu({page:e,...t}){let n=Vc(),{nonce:r}=fu(),{router:i}=lu(),a=X.useMemo(()=>Xs(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?X.createElement(_u,{page:e,matches:a,...t}):X.createElement(vu,{page:e,matches:a,...t})):null}function gu(e){let{manifest:t,routeModules:n}=fu(),[r,i]=X.useState([]);return X.useEffect(()=>{let r=!1;return ru(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function _u({page:e,matches:t,...n}){let r=nl(),{future:i}=fu(),{basename:a}=lu(),o=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=$l(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return X.createElement(X.Fragment,null,o.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function vu({page:e,matches:t,...n}){let r=nl(),{future:i,manifest:a,routeModules:o}=fu(),{basename:s}=lu(),{loaderData:c,matches:l}=uu(),u=X.useMemo(()=>iu(e,t,l,a,r,`data`),[e,t,l,a,r]),d=X.useMemo(()=>iu(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=$l(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=X.useMemo(()=>au(d,a),[d,a]),m=gu(d);return X.createElement(X.Fragment,null,f.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>X.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>X.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function yu(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}X.Component;var bu=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{bu&&(window.__reactRouterVersion=`7.18.2`)}catch{}function xu({basename:e,children:t,useTransitions:n,window:r}){let i=X.useRef();i.current??=Bs({window:r,v5Compat:!0});let a=i.current,[o,s]=X.useState({action:a.action,location:a.location}),c=X.useCallback(e=>{n===!1?s(e):X.startTransition(()=>s(e))},[n]);return X.useLayoutEffect(()=>a.listen(c),[a,c]),X.createElement(Pl,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var Su=X.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=X.useContext(Gc),v=typeof l==`string`&&Ps.test(l),y=Nc(l,h);l=y.to;let b=el(l,{relative:r}),x=nl(),S=null;if(o){let e=Sc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:wc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=pu(n,p),E=Du(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=X.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:yu(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?X.createElement(X.Fragment,null,k,X.createElement(hu,{page:b})):k});Su.displayName=`Link`;var Cu=X.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=ul(a,{relative:c.relative}),d=nl(),f=X.useContext(zc),{navigator:p,basename:m}=X.useContext(Gc),h=f!=null&&Nu(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=gc(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return X.createElement(Su,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Cu.displayName=`NavLink`;var wu=X.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Ll,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=X.useContext(Gc),g=ju(),_=Mu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Ps.test(s);return X.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?X.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});wu.displayName=`Form`;function Tu(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Eu(e){let t=X.useContext(Rc);return Vs(t,Tu(e)),t}function Du(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=al(),d=nl(),f=ul(e,{relative:o});return X.useCallback(p=>{if(Wl(p,t)){p.preventDefault();let t=n===void 0?Ks(d)===Ks(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?X.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function Ou(e){Hs(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=X.useRef(Gl(e)),n=X.useRef(!1),r=nl(),i=X.useMemo(()=>Kl(r.search,n.current?null:t.current),[r.search]),a=al();return[i,X.useCallback((e,t)=>{let r=Gl(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var ku=0,Au=()=>`__${String(++ku)}__`;function ju(){let{router:e}=Eu(`useSubmit`),{basename:t}=X.useContext(Gc),n=Tl(),r=e.fetch,i=e.navigate;return X.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Zl(e,t);if(a.navigate===!1){let e=a.fetcherKey||Au();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 Mu(e,{relative:t}={}){let{basename:n}=X.useContext(Gc),r=X.useContext(qc);Vs(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...ul(e||`.`,{relative:t})},o=nl();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:wc([n,a.pathname])),Ks(a)}function Nu(e,{relative:t}={}){let n=X.useContext(Hc);Vs(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Eu(`useViewTransitionState`),i=ul(e,{relative:t});if(!n.isTransitioning)return!1;let a=gc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=gc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return fc(i.pathname,o)!=null||fc(i.pathname,a)!=null}var Z=f(),Pu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Qn,{ref:n,className:K(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Pu.displayName=Qn.displayName;var Fu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-lg border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Fu.displayName=`Card`;var Iu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Iu.displayName=`CardHeader`;var Lu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Lu.displayName=`CardTitle`;var Ru=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));Ru.displayName=`CardDescription`;var zu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));zu.displayName=`CardContent`;var Bu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Bu.displayName=`CardFooter`;var Vu=`2.20.3`,Hu=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Uu(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Hu(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`),Hu(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Wu=`session.open`,Gu=`session.set`,Ku=`session.ids`,qu=`session.materialize`,Ju=`session.close`,Yu=`session.delta`;function Xu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await J.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 Zu=`https://github.com/canvas-ui/canvas-server`,Qu=null;function $u(){return Qu||=J.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||Zu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Qu=null,{sourceUrl:Zu,version:null,commit:null,license:null})),Qu}function ed(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return $u().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function td({className:e=``}){let t=ed();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function nd({children:e}){Uu(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Xu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(Fu,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(Su,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Vu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,Z.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,Z.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(td,{className:`mt-4 text-center`})]})]})})]})})}function rd(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var id=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=zr,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||rd();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=Br(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 ad(e,t,n=`auto`){try{let r=await J.post(Sr.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)+`...`),J.setAuthToken(i.token),id.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)+`...`),J.setAuthToken(i.payload.token),id.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),J.clearAuthToken(),e}}async function od(e,t,n){try{return await J.post(Sr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function sd(e){return e instanceof Error&&/^Network error/i.test(e.message)}function cd(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return br(e).exp*1e3>Date.now()}catch{return!1}}function ld(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=br(e);return t.exp*1e3<Date.now()?(J.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),J.clearAuthToken(),null}}async function ud(){try{if(!J.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await J.get(Sr.me);return console.log(`Current user response:`,e),e&&e?(id.isConnected()||id.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),sd(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),J.clearAuthToken(),id.disconnect(),null):null}}function dd(){return J.isAuthenticated()}function fd(){let e=new URL(`${Rr}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function pd(e){let t=await J.post(`${Rr}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);J.setAuthToken(t.token),id.connect(t.token)}async function md(){try{let e=await J.get(Sr.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 hd(e){try{await J.post(Sr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var gd=e=>e?.strategies?.local?.enabled!==!1,_d=e=>e?.allowUserRegistrations!==!1;function vd(){let e=al(),[t,n]=X.useState(!1),[r,i]=X.useState(``),[a,o]=X.useState(``),[s,l]=X.useState(!1),[u,d]=X.useState({}),[f,p]=X.useState(null),[m,h]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{dd()&&e(`/workspaces`),fetch(`${Rr}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),md().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`),d(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()){l(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await ad(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),d({}),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)}d({password:t})}finally{l(!1)}}}return t?(0,Z.jsx)(nd,{children:(0,Z.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),l(!0),o(``);try{if(J.setAuthToken(r.trim()),!await ud())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){J.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{l(!1)}},children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,Z.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,Z.jsx)(Pu,{htmlFor:`local-token`,children:`Local access token`}),(0,Z.jsx)(q,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(Y,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,Z.jsx)(nd,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:v,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[f?.strategies?.imap?.enabled&&f.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.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,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),u.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:u.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),u.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:u.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),f?.strategies?.google?.enabled&&(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,disabled:s,onClick:()=>fd(),children:[(0,Z.jsx)(c,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),gd(f)&&_d(f)&&(0,Z.jsx)(Y,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function yd(){let e=al(),{showToast:t}=Vr(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await md(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=X.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,Z.jsxs)(nd,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(Y,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(Su,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(nd,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await od(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(Y,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(Su,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,Z.jsx)(Su,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(Su,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function bd(){let e=al(),[t]=Ou(),[n,r]=X.useState(t.get(`error`)),i=X.useRef(!1);return X.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,pd(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,Z.jsx)(nd,{children:(0,Z.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function xd({className:e=`h-5 w-5`,...t}){return(0,Z.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,Z.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Z.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}function Sd({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!dd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await ud();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),sd(e)){n(cd()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),J.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(xd,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(jl,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function Cd({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{(async()=>{try{await J.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),J.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Z.jsx)(jl,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var wd=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})}))})),Td=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)}})),Ed=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=se,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=R,e.setTopLeft=ne,e.setTransform=te,e.sortLayoutItems=z,e.sortLayoutItemsByColRow=ie,e.sortLayoutItemsByRowCol=re,e.synchronizeLayoutWithChildren=ae,e.validateLayout=oe,e.withLayoutItem=p;var t=wd(),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=Td();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=z(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=z(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},L={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function R(e,t,n,r){let i=L[e];return i?i(t,a(a({},t),n),r):n}function te(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 ne(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 z(e,t){return t===`horizontal`?ie(e):t===`vertical`?re(e):e}function re(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ie(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function ae(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function oe(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 se(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Dd=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)}})),Od=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),kd=i(((e,t)=>{var n=Od();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}})),Ad=i(((e,t)=>{t.exports=kd()()})),jd=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,a)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&r(e,s,{get:()=>t[s],enumerable:!(a=i(t,s))||a.enumerable});return e},f=(e,t,i)=>(i=e==null?{}:n(s(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),p=e=>u(r({},`__esModule`,{value:!0}),e),m={};l(m,{DraggableCore:()=>xe,default:()=>Se}),t.exports=p(m);var h=f(d()),g=f(Ad()),_=f(a()),v=yr();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function L(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 R(e,t){let n=ne(e,t,`px`);return{[E(`transform`,O)]:n}}function te(e,t){return ne(e,t,``)}function ne({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 z(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function re(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ie(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ae(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ie();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
4
|
+
Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=nl(),d;if(t){let e=typeof t==`string`?qs(t):t;Vs(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})):Xs(e,{pathname:p});Hs(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Hs(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=yl(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:wc([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:wc([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?X.createElement(Kc.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function pl(){let e=El(),t=Ac(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=X.createElement(X.Fragment,null,X.createElement(`p`,null,`💿 Hey developer 👋`),X.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,X.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,X.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),X.createElement(X.Fragment,null,X.createElement(`h2`,null,`Unexpected Application Error!`),X.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?X.createElement(`pre`,{style:i},n):null,o)}var ml=X.createElement(pl,null),hl=class extends X.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=$c(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:X.createElement(qc.Provider,{value:this.props.routeContext},X.createElement(Jc.Provider,{value:e,children:this.props.component}));return this.context?X.createElement(_l,{error:e},t):t}};hl.contextType=Bc;var gl=new WeakMap;function _l({children:e,error:t}){let{basename:n}=X.useContext(Gc);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Qc(t.digest);if(e){let r=gl.get(t);if(r)throw r;let i=Nc(e.location,n),a=i.absoluteURL||i.to;if(Lc(a))throw Error(`Invalid redirect location`);if(Mc&&!gl.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 gl.set(t,n),n}}return X.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function vl({routeContext:e,match:t,children:n}){let r=X.useContext(Rc);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),X.createElement(qc.Provider,{value:e},n)}function yl(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);Vs(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:jc(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||ml,o&&(s<0&&c===0?(kl(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?X.createElement(n.route.Component,null):n.route.element?n.route.element:e,X.createElement(vl,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?X.createElement(hl,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function bl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function xl(e){let t=X.useContext(Rc);return Vs(t,bl(e)),t}function Sl(e){let t=X.useContext(zc);return Vs(t,bl(e)),t}function Cl(e){let t=X.useContext(qc);return Vs(t,bl(e)),t}function wl(e){let t=Cl(e),n=t.matches[t.matches.length-1];return Vs(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Tl(){return wl(`useRouteId`)}function El(){let e=X.useContext(Jc),t=Sl(`useRouteError`),n=wl(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Dl(){let{router:e}=xl(`useNavigate`),t=wl(`useNavigate`),n=X.useRef(!1);return il(()=>{n.current=!0}),X.useCallback(async(r,i={})=>{Hs(n.current,rl),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Ol={};function kl(e,t,n){!t&&!Ol[e]&&(Ol[e]=!0,Hs(!1,n))}X.memo(Al);function Al({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return fl(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function jl({to:e,replace:t,state:n,relative:r}){Vs(tl(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=X.useContext(Gc);Hs(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=X.useContext(qc),{pathname:o}=nl(),s=al(),c=Sc(e,xc(a),o,r===`path`),l=JSON.stringify(c);return X.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function Ml(e){return cl(e.context)}function Nl(e){Vs(!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 Pl({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Vs(!tl(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=X.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=qs(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=X.useMemo(()=>{let e=gc(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 Hs(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:X.createElement(Gc.Provider,{value:c},X.createElement(Kc.Provider,{children:t,value:h}))}function Fl({children:e,location:t}){return dl(Il(e),t)}X.Component;function Il(e,t=[]){let n=[];return X.Children.forEach(e,(e,r)=>{if(!X.isValidElement(e))return;let i=[...t,r];if(e.type===X.Fragment){n.push.apply(n,Il(e.props.children,i));return}Vs(e.type===Nl,`[${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>`),Vs(!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=Il(e.props.children,i)),n.push(a)}),n}var Ll=`get`,Rl=`application/x-www-form-urlencoded`;function zl(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Bl(e){return zl(e)&&e.tagName.toLowerCase()===`button`}function Vl(e){return zl(e)&&e.tagName.toLowerCase()===`form`}function Hl(e){return zl(e)&&e.tagName.toLowerCase()===`input`}function Ul(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Wl(e,t){return e.button===0&&(!t||t===`_self`)&&!Ul(e)}function Gl(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 Kl(e,t){let n=Gl(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var ql=null;function Jl(){if(ql===null)try{new FormData(document.createElement(`form`),0),ql=!1}catch{ql=!0}return ql}var Yl=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Xl(e){return e!=null&&!Yl.has(e)?(Hs(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Rl}"`),null):e}function Zl(e,t){let n,r,i,a,o;if(Vl(e)){let o=e.getAttribute(`action`);r=o?gc(o,t):null,n=e.getAttribute(`method`)||Ll,i=Xl(e.getAttribute(`enctype`))||Rl,a=new FormData(e)}else if(Bl(e)||Hl(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?gc(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Ll,i=Xl(e.getAttribute(`formenctype`))||Xl(o.getAttribute(`enctype`))||Rl,a=new FormData(o,e),!Jl()){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(zl(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Ll,r=null,i=Rl,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 Ql(e,t){if(e===!1||e==null)throw Error(t)}function $l(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&&gc(i.pathname,t)===`/`?`${Tc(t)}/_root.${r}`:`${Tc(i.pathname)}.${r}`,i}async function eu(e,t){if(e.id in t)return t[e.id];try{let n=await m(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function tu(e){return e!=null&&typeof e.page==`string`}function nu(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 ru(e,t,n){return cu((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await eu(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(nu).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function iu(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 au(e,t,{includeHydrateFallback:n}={}){return ou(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 ou(e){return[...new Set(e)]}function su(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function cu(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!tu(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(su(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function lu(){let e=X.useContext(Rc);return Ql(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function uu(){let e=X.useContext(zc);return Ql(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var du=X.createContext(void 0);du.displayName=`FrameworkContext`;function fu(){let e=X.useContext(du);return Ql(e,`You must render this element inside a <HydratedRouter> element`),e}function pu(e,t){let n=X.useContext(du),[r,i]=X.useState(!1),[a,o]=X.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=X.useRef(null);X.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),X.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:mu(s,p),onBlur:mu(c,m),onMouseEnter:mu(l,p),onMouseLeave:mu(u,m),onTouchStart:mu(d,p)}]:[a,f,{}]:[!1,f,{}]}function mu(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function hu({page:e,...t}){let n=Vc(),{nonce:r}=fu(),{router:i}=lu(),a=X.useMemo(()=>Xs(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?X.createElement(_u,{page:e,matches:a,...t}):X.createElement(vu,{page:e,matches:a,...t})):null}function gu(e){let{manifest:t,routeModules:n}=fu(),[r,i]=X.useState([]);return X.useEffect(()=>{let r=!1;return ru(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function _u({page:e,matches:t,...n}){let r=nl(),{future:i}=fu(),{basename:a}=lu(),o=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=$l(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return X.createElement(X.Fragment,null,o.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function vu({page:e,matches:t,...n}){let r=nl(),{future:i,manifest:a,routeModules:o}=fu(),{basename:s}=lu(),{loaderData:c,matches:l}=uu(),u=X.useMemo(()=>iu(e,t,l,a,r,`data`),[e,t,l,a,r]),d=X.useMemo(()=>iu(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=X.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=$l(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=X.useMemo(()=>au(d,a),[d,a]),m=gu(d);return X.createElement(X.Fragment,null,f.map(e=>X.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>X.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>X.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function yu(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}X.Component;var bu=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{bu&&(window.__reactRouterVersion=`7.18.2`)}catch{}function xu({basename:e,children:t,useTransitions:n,window:r}){let i=X.useRef();i.current??=Bs({window:r,v5Compat:!0});let a=i.current,[o,s]=X.useState({action:a.action,location:a.location}),c=X.useCallback(e=>{n===!1?s(e):X.startTransition(()=>s(e))},[n]);return X.useLayoutEffect(()=>a.listen(c),[a,c]),X.createElement(Pl,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var Su=X.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=X.useContext(Gc),v=typeof l==`string`&&Ps.test(l),y=Nc(l,h);l=y.to;let b=el(l,{relative:r}),x=nl(),S=null;if(o){let e=Sc(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:wc([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=pu(n,p),E=Du(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=X.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:yu(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?X.createElement(X.Fragment,null,k,X.createElement(hu,{page:b})):k});Su.displayName=`Link`;var Cu=X.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=ul(a,{relative:c.relative}),d=nl(),f=X.useContext(zc),{navigator:p,basename:m}=X.useContext(Gc),h=f!=null&&Nu(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=gc(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return X.createElement(Su,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Cu.displayName=`NavLink`;var wu=X.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Ll,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=X.useContext(Gc),g=ju(),_=Mu(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&Ps.test(s);return X.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?X.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});wu.displayName=`Form`;function Tu(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Eu(e){let t=X.useContext(Rc);return Vs(t,Tu(e)),t}function Du(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=al(),d=nl(),f=ul(e,{relative:o});return X.useCallback(p=>{if(Wl(p,t)){p.preventDefault();let t=n===void 0?Ks(d)===Ks(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?X.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function Ou(e){Hs(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=X.useRef(Gl(e)),n=X.useRef(!1),r=nl(),i=X.useMemo(()=>Kl(r.search,n.current?null:t.current),[r.search]),a=al();return[i,X.useCallback((e,t)=>{let r=Gl(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var ku=0,Au=()=>`__${String(++ku)}__`;function ju(){let{router:e}=Eu(`useSubmit`),{basename:t}=X.useContext(Gc),n=Tl(),r=e.fetch,i=e.navigate;return X.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Zl(e,t);if(a.navigate===!1){let e=a.fetcherKey||Au();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 Mu(e,{relative:t}={}){let{basename:n}=X.useContext(Gc),r=X.useContext(qc);Vs(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...ul(e||`.`,{relative:t})},o=nl();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:wc([n,a.pathname])),Ks(a)}function Nu(e,{relative:t}={}){let n=X.useContext(Hc);Vs(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=Eu(`useViewTransitionState`),i=ul(e,{relative:t});if(!n.isTransitioning)return!1;let a=gc(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=gc(n.nextLocation.pathname,r)||n.nextLocation.pathname;return fc(i.pathname,o)!=null||fc(i.pathname,a)!=null}var Z=f(),Pu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Qn,{ref:n,className:K(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));Pu.displayName=Qn.displayName;var Fu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`rounded-lg border bg-card text-card-foreground shadow-elevation-1`,e),...t}));Fu.displayName=`Card`;var Iu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex flex-col space-y-1.5 p-6`,e),...t}));Iu.displayName=`CardHeader`;var Lu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`h3`,{ref:n,className:K(`text-2xl font-semibold leading-none tracking-tight`,e),...t}));Lu.displayName=`CardTitle`;var Ru=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`p`,{ref:n,className:K(`text-sm text-muted-foreground`,e),...t}));Ru.displayName=`CardDescription`;var zu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`p-6 pt-0`,e),...t}));zu.displayName=`CardContent`;var Bu=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{ref:n,className:K(`flex items-center p-6 pt-0`,e),...t}));Bu.displayName=`CardFooter`;var Vu=`2.20.4`,Hu=e=>{window.particlesJS.load(e,`/js/particles.config.json`,()=>{console.log(`particles.js config loaded for`,e)})};function Uu(e){(0,X.useEffect)(()=>{if(window.particlesJS!==void 0)Hu(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`),Hu(e)},document.head.appendChild(t)}return()=>{window.pJS&&window.pJS[e]?.destroy&&window.pJS[e].destroy()}},[e])}var Wu=`session.open`,Gu=`session.set`,Ku=`session.ids`,qu=`session.materialize`,Ju=`session.close`,Yu=`session.delta`;function Xu(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;async function n(){try{r(!0),a(null);let n=await J.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 Zu=`https://github.com/canvas-ui/canvas-server`,Qu=null;function $u(){return Qu||=J.get(`/ping`,{skipAuth:!0}).then(e=>{let t=e??{};return{sourceUrl:t.sourceUrl||Zu,version:t.version??null,commit:t.commit??null,license:t.license??null}}).catch(e=>(console.error(`Failed to fetch server source info:`,e),Qu=null,{sourceUrl:Zu,version:null,commit:null,license:null})),Qu}function ed(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!0;return $u().then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function td({className:e=``}){let t=ed();if(!t)return null;let n=[t.version?`v${t.version}`:null,t.commit?.slice(0,7)].filter(Boolean).join(` `);return(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground ${e}`,children:[`Powered by`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Canvas`}),n?` ${n}`:``,t.license?`, ${t.license}`:``,`.`,` `,(0,Z.jsx)(`a`,{href:t.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})}function nd({children:e}){Uu(`particle-js`);let{serverVersion:t,isLoading:n,error:r}=Xu();return(0,Z.jsx)(`div`,{className:`flex min-h-viewport w-full items-center justify-center p-4 flex-col`,children:(0,Z.jsxs)(Fu,{className:`flex w-[95vw] h-viewport-modal overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`hidden md:block w-1/2 relative bg-background`,"data-scheme":`dark`,id:`particle-js`,children:[(0,Z.jsxs)(Su,{className:`absolute top-8 left-8 font-bold text-foreground flex items-center z-raised`,to:`/`,children:[(0,Z.jsx)(`img`,{src:`/images/logo-wr_128x128.png`,alt:`Canvas Logo`,className:`mr-2 h-6 w-6 touch-target`}),(0,Z.jsx)(`span`,{className:`text-2xl font-bold text-foreground`,children:`Canvas`})]}),(0,Z.jsxs)(`div`,{className:`absolute bottom-8 left-8 text-sm text-foreground max-w-[80%] z-raised`,children:[`Web UI: v`,Vu,`, Server: `,n?`Loading...`:r?`Unavailable`:t?`v${t}`:`Unknown`]})]}),(0,Z.jsx)(`div`,{className:`flex w-full md:w-1/2 flex-col justify-center px-4 py-12 sm:px-6 lg:px-8`,children:(0,Z.jsxs)(`div`,{className:`mx-auto w-full max-w-sm`,children:[e,(0,Z.jsxs)(`div`,{className:`mt-8 border-t pt-6`,children:[(0,Z.jsxs)(`a`,{href:`https://github.com/canvas-ui`,target:`_blank`,className:`text-muted-foreground hover:text-foreground justify-center flex items-center space-x-2`,rel:`noopener noreferrer`,children:[(0,Z.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`24`,height:`24`,stroke:`currentColor`,fill:`none`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`w-6 h-6`,children:(0,Z.jsx)(`path`,{d:`M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22`})}),(0,Z.jsx)(`span`,{children:`View on GitHub`})]}),(0,Z.jsx)(td,{className:`mt-4 text-center`})]})]})})]})})}function rd(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var id=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=zr,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||rd();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=Br(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 ad(e,t,n=`auto`){try{let r=await J.post(Sr.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)+`...`),J.setAuthToken(i.token),id.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)+`...`),J.setAuthToken(i.payload.token),id.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),J.clearAuthToken(),e}}async function od(e,t,n){try{return await J.post(Sr.register,{name:e,email:t,password:n},{skipAuth:!0})}catch(e){throw console.error(`Registration failed:`,e),e}}function sd(e){return e instanceof Error&&/^Network error/i.test(e.message)}function cd(){let e=localStorage.getItem(`authToken`);if(!e)return!1;if(e.startsWith(`canvas-`))return!0;try{return br(e).exp*1e3>Date.now()}catch{return!1}}function ld(){let e=localStorage.getItem(`authToken`);if(!e||e.startsWith(`canvas-`))return null;try{let t=br(e);return t.exp*1e3<Date.now()?(J.clearAuthToken(),null):{id:t.sub,email:t.email,userType:t.userType||`user`}}catch(e){return console.error(`Failed to decode token:`,e),J.clearAuthToken(),null}}async function ud(){try{if(!J.isAuthenticated())return console.log(`Not authenticated, skipping getCurrentUser request`),null;let e=await J.get(Sr.me);return console.log(`Current user response:`,e),e&&e?(id.isConnected()||id.reconnect(),e):(console.warn(`Invalid user profile response structure:`,e),null)}catch(e){if(console.error(`Failed to get current user:`,e),sd(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),J.clearAuthToken(),id.disconnect(),null):null}}function dd(){return J.isAuthenticated()}function fd(){let e=new URL(`${Rr}/oauth/google/login`);e.searchParams.set(`origin`,window.location.origin),window.location.assign(e.toString())}async function pd(e){let t=await J.post(`${Rr}/oauth/google/exchange`,{code:e},{skipAuth:!0});if(!t?.token)throw Error(`Invalid login response: missing token`);J.setAuthToken(t.token),id.connect(t.token)}async function md(){try{let e=await J.get(Sr.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 hd(e){try{await J.post(Sr.verifyEmailRequest,{email:e},{skipAuth:!0})}catch(e){throw console.error(`Failed to request email verification:`,e),e}}var gd=e=>e?.strategies?.local?.enabled!==!1,_d=e=>e?.allowUserRegistrations!==!1;function vd(){let e=al(),[t,n]=X.useState(!1),[r,i]=X.useState(``),[a,o]=X.useState(``),[s,l]=X.useState(!1),[u,d]=X.useState({}),[f,p]=X.useState(null),[m,h]=X.useState({email:``,password:``,strategy:`auto`});X.useEffect(()=>{dd()&&e(`/workspaces`),fetch(`${Rr}/runtime/capabilities`).then(e=>e.ok?e.json():null).then(e=>n(e?.payload?.local===!0)).catch(()=>{}),md().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`),d(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()){l(!0);try{console.log(`Attempting login with:`,m.email,`strategy:`,m.strategy);let t=await ad(m.email,m.password,m.strategy);console.log(`Login successful, received token:`,`token`in t?!!t.token:!!t.payload?.token),d({}),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)}d({password:t})}finally{l(!1)}}}return t?(0,Z.jsx)(nd,{children:(0,Z.jsxs)(`form`,{className:`grid gap-4`,onSubmit:async t=>{t.preventDefault(),l(!0),o(``);try{if(J.setAuthToken(r.trim()),!await ud())throw Error(`The local token was not accepted`);e(`/workspaces`)}catch(e){J.clearAuthToken(),o(e instanceof Error?e.message:`Authentication failed`)}finally{l(!1)}},children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold`,children:`Connect to your local runtime`}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Enter the token shown by `,(0,Z.jsx)(`code`,{children:`canvas runtime token`}),` in the runtime folder.`]}),(0,Z.jsx)(Pu,{htmlFor:`local-token`,children:`Local access token`}),(0,Z.jsx)(q,{id:`local-token`,type:`password`,autoComplete:`off`,value:r,onChange:e=>i(e.target.value),required:!0}),a&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(Y,{disabled:s,children:s?`Connecting…`:`Connect`})]})}):(0,Z.jsx)(nd,{children:(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Welcome back`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your credentials to access your account`})]}),(0,Z.jsx)(`form`,{onSubmit:v,children:(0,Z.jsxs)(`div`,{className:`grid gap-4`,children:[f?.strategies?.imap?.enabled&&f.strategies.imap.domains.length>0&&(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`strategy`,children:`Authentication Method`}),(0,Z.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,Z.jsx)(`option`,{value:`auto`,children:`Auto-detect`}),(0,Z.jsx)(`option`,{value:`local`,children:`Local Account`}),(0,Z.jsx)(`option`,{value:`imap`,children:`Email Server (IMAP)`})]})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,name:`email`,placeholder:`name@example.com`,type:`email`,autoCapitalize:`none`,autoComplete:`email`,autoCorrect:`off`,disabled:s,value:m.email,onChange:_}),u.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:u.email})]}),(0,Z.jsxs)(`div`,{className:`grid gap-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,name:`password`,type:`password`,disabled:s,value:m.password,onChange:_}),u.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:u.password})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-4`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:s,children:s?`Signing in...`:`Sign In`}),f?.strategies?.google?.enabled&&(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,disabled:s,onClick:()=>fd(),children:[(0,Z.jsx)(c,{icon:`logos:google-icon`,width:16,height:16,className:`mr-2`}),`Sign in with Google`]}),gd(f)&&_d(f)&&(0,Z.jsx)(Y,{variant:`outline`,type:`button`,disabled:s,onClick:()=>e(`/register`),children:`Don't have an account? Sign up`})]})]})})]})})}function yd(){let e=al(),{showToast:t}=Vr(),[n,r]=X.useState(!1),[i,a]=X.useState({}),[o,s]=X.useState({name:``,email:``,password:``}),[c,l]=X.useState(!1),[u,d]=X.useState(!1),[f,p]=X.useState(null);X.useEffect(()=>{(async()=>{let t=await md(),n=t?.strategies?.local;if(t?.allowUserRegistrations===!1||n?.enabled===!1){e(`/login`,{replace:!0});return}n?.passwordPolicy&&p(n.passwordPolicy),d(!!n?.requireEmailVerification)})()},[e]);let m=X.useMemo(()=>{if(!f)return null;let e=o.password||``;return{minLength:!f.minLength||e.length>=f.minLength,maxLength:!f.maxLength||e.length<=f.maxLength,uppercase:!f.requireUppercase||/[A-Z]/.test(e),lowercase:!f.requireLowercase||/[a-z]/.test(e),number:!f.requireNumbers||/[0-9]/.test(e),special:!f.requireSpecialChars||/[^A-Za-z0-9]/.test(e)}},[f,o.password]),h=()=>{let e={};if(!o.name)e.name=`Username is required`;else if(o.name.trim().length===0)e.name=`Username cannot be empty`;else{let t=o.name.toLowerCase().trim();t.length<3?e.name=`Username must be at least 3 characters long`:t.length>39?e.name=`Username cannot be longer than 39 characters`:/^[a-z0-9_-]+$/.test(t)?[`admin`,`administrator`,`root`,`system`,`support`,`help`,`api`,`www`,`mail`,`ftp`,`localhost`,`test`,`demo`,`canvas`,`universe`,`workspace`,`context`,`user`,`users`].includes(t)&&(e.name=`Username '${t}' is reserved and cannot be used`):e.name=`Username can only contain lowercase letters, numbers, underscores, and hyphens`}if(o.email?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.email)||(e.email=`Please enter a valid email address`):e.email=`Email is required`,!o.password)e.password=`Password is required`;else if(f){let t=o.password,n=[];f.minLength&&t.length<f.minLength&&n.push(`at least ${f.minLength} characters`),f.maxLength&&t.length>f.maxLength&&n.push(`no more than ${f.maxLength} characters`),f.requireUppercase&&!/[A-Z]/.test(t)&&n.push(`an uppercase letter`),f.requireLowercase&&!/[a-z]/.test(t)&&n.push(`a lowercase letter`),f.requireNumbers&&!/[0-9]/.test(t)&&n.push(`a number`),f.requireSpecialChars&&!/[^A-Za-z0-9]/.test(t)&&n.push(`a special character`),n.length&&(e.password=`Password must contain ${n.join(`, `).replace(/, ([^,]*)$/,` and $1`)}.`)}else o.password.length<8&&(e.password=`Password must be at least 8 characters long`);return a(e),Object.keys(e).length===0},g=e=>{let t={...o,[e.target.id]:e.target.value};s(t),(e.target.id===`name`||e.target.id===`email`||e.target.id===`password`)&&h()};return c?(0,Z.jsxs)(nd,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Registration Successful!`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:u?`Check your email for a verification link to activate your account.`:`Your account has been created.`})]}),(0,Z.jsx)(`div`,{className:`space-y-6 text-center pt-6`,children:!u&&(0,Z.jsx)(Y,{asChild:!0,className:`w-full`,children:(0,Z.jsx)(Su,{to:`/login`,children:`Go to Login`})})})]}):(0,Z.jsxs)(nd,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Create an account`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Enter your email below to create your account`})]}),(0,Z.jsxs)(`form`,{onSubmit:async e=>{if(e.preventDefault(),h()){r(!0);try{let e=await od(o.name,o.email,o.password);console.log(`Registration successful:`,e),t({title:`Registration Successful`,description:u?`Check your email for a verification link before logging in.`:`You can now log in with your credentials.`,variant:`default`}),l(!0),s({name:``,email:``,password:``}),a({})}catch(e){console.error(`Registration failed:`,e);let n=e?.message||`Registration failed`;n.toLowerCase().includes(`password`)?a({...i,password:n}):a({...i,email:n}),t({title:`Registration Failed`,description:n,variant:`destructive`})}finally{r(!1)}}},className:`space-y-4 pt-6`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`name`,children:`Username`}),(0,Z.jsx)(q,{id:`name`,type:`text`,placeholder:`Enter your username (e.g., john_doe)`,value:o.name,onChange:g,disabled:n,className:i.name?`border-destructive`:``}),i.name&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.name}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`3-39 characters, lowercase letters, numbers, underscores, and hyphens only`})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`email`,children:`Email`}),(0,Z.jsx)(q,{id:`email`,type:`email`,placeholder:`name@example.com`,value:o.email,onChange:g,disabled:n,className:i.email?`border-destructive`:``}),i.email&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.email})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(Pu,{htmlFor:`password`,children:`Password`}),(0,Z.jsx)(q,{id:`password`,type:`password`,placeholder:`Enter your password`,value:o.password,onChange:g,disabled:n,className:i.password?`border-destructive`:``}),i.password&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i.password}),f&&m&&(0,Z.jsxs)(`ul`,{className:`text-xs list-disc pl-4 space-y-1`,children:[(0,Z.jsxs)(`li`,{className:m.minLength?`text-success`:`text-muted-foreground`,children:[`At least `,f.minLength,` characters`]}),f.requireUppercase&&(0,Z.jsx)(`li`,{className:m.uppercase?`text-success`:`text-muted-foreground`,children:`At least one uppercase letter`}),f.requireLowercase&&(0,Z.jsx)(`li`,{className:m.lowercase?`text-success`:`text-muted-foreground`,children:`At least one lowercase letter`}),f.requireNumbers&&(0,Z.jsx)(`li`,{className:m.number?`text-success`:`text-muted-foreground`,children:`At least one number`}),f.requireSpecialChars&&(0,Z.jsx)(`li`,{className:m.special?`text-success`:`text-muted-foreground`,children:`At least one special character`}),f.maxLength&&(0,Z.jsxs)(`li`,{className:m.maxLength?`text-success`:`text-muted-foreground`,children:[`No more than `,f.maxLength,` characters`]})]})]}),(0,Z.jsx)(Y,{type:`submit`,className:`w-full`,disabled:n,children:n?`Creating Account...`:`Create Account`})]}),(0,Z.jsxs)(`div`,{className:`mt-4 text-center text-sm`,children:[`Already have an account?`,` `,(0,Z.jsx)(Su,{to:`/login`,className:`underline`,children:`Sign in`})]}),(0,Z.jsxs)(`div`,{className:`px-8 py-4 text-center text-sm text-muted-foreground border-t mt-6`,children:[`By clicking continue, you agree to our`,` `,(0,Z.jsx)(Su,{to:`/terms`,className:`underline underline-offset-4 hover:text-primary`,children:`Terms of Service`}),` `,`and`,` `,(0,Z.jsx)(Su,{to:`/privacy`,className:`underline underline-offset-4 hover:text-primary`,children:`Privacy Policy`}),`.`]})]})}function bd(){let e=al(),[t]=Ou(),[n,r]=X.useState(t.get(`error`)),i=X.useRef(!1);return X.useEffect(()=>{let n=t.get(`code`);!n||i.current||(i.current=!0,pd(n).then(()=>e(`/home`,{replace:!0})).catch(e=>r(e instanceof Error?e.message:`Google sign-in failed`)))},[t,e]),(0,Z.jsx)(nd,{children:(0,Z.jsx)(`div`,{className:`flex flex-col space-y-4 text-center`,children:n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Google sign-in failed`}),(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:n}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>e(`/login`,{replace:!0}),children:`Back to sign in`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Signing you in…`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Completing Google sign-in.`})]})})})}function xd({className:e=`h-5 w-5`,...t}){return(0,Z.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,Z.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Z.jsx)(`path`,{className:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z`})]})}function Sd({children:e}){let[t,n]=(0,X.useState)(`loading`);return(0,X.useEffect)(()=>{(async()=>{try{if(!dd()){console.log(`No authentication token found, redirecting to login`),n(`unauthenticated`);return}let e=await ud();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),sd(e)){n(cd()?`authenticated`:`unauthenticated`);return}e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from ProtectedRoute`),J.clearAuthToken()),n(`unauthenticated`)}})()},[]),t===`loading`?(0,Z.jsx)(`div`,{className:`flex h-screen items-center justify-center`,children:(0,Z.jsx)(xd,{className:`h-8 w-8`})}):t===`unauthenticated`?(0,Z.jsx)(jl,{to:`/login`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}function Cd({children:e}){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{(async()=>{try{await J.get(`/auth/me`),n(!0)}catch(e){e instanceof Error&&e.message.includes(`Authentication required`)&&(console.log(`Clearing invalid token from PublicRoute`),J.clearAuthToken()),n(!1)}})()},[]),t===null?null:t?(0,Z.jsx)(jl,{to:`/workspaces`,replace:!0}):(0,Z.jsx)(Z.Fragment,{children:e})}var wd=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})}))})),Td=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)}})),Ed=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=se,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=R,e.setTopLeft=ne,e.setTransform=te,e.sortLayoutItems=z,e.sortLayoutItemsByColRow=ie,e.sortLayoutItemsByRowCol=re,e.synchronizeLayoutWithChildren=ae,e.validateLayout=oe,e.withLayoutItem=p;var t=wd(),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=Td();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=z(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=z(e,o);(o===`vertical`&&typeof r==`number`?d>=r:o===`horizontal`&&typeof n==`number`&&l>=n)&&(f=f.reverse());let p=T(f,t),m=p.length>0;if(m&&c)return u(e);if(m&&a)return`${t.i}`,t.x=l,t.y=d,t.moved=!1,e;for(let n=0,r=p.length;n<r;n++){let r=p[n];`${t.i}${t.x}${t.y}${r.i}${r.x}${r.y}`,!r.moved&&(e=r.static?O(e,r,t,i,o,s):O(e,t,r,i,o,s))}return e}function O(e,t,n,r,i,a){let o=i===`horizontal`,s=i===`vertical`,c=t.static;if(r){r=!1;let l={x:o?Math.max(t.x-n.w,0):n.x,y:s?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:`-1`},u=w(e,l),d=u&&u.y+u.h>t.y,f=u&&t.x+t.w>u.x;if(!u)return`${n.i}${l.x}${l.y}`,D(e,n,o?l.x:void 0,s?l.y:void 0,r,c,i,a);if(d&&s)return D(e,n,void 0,n.y+1,r,c,i,a);if(d&&i==null)return t.y=n.y,n.y+=n.h,e;if(f&&o)return D(e,t,n.x,void 0,r,c,i,a)}let l=o?n.x+1:void 0,u=s?n.y+1:void 0;return l==null&&u==null?e:D(e,n,o?n.x+1:void 0,s?n.y+1:void 0,r,c,i,a)}function k(e){return e*100+`%`}var A=(e,t,n,r)=>e+n>r?t:n,j=(e,t,n)=>e<0?t:n,M=e=>Math.max(0,e),N=e=>Math.max(0,e),P=(e,t,n)=>{let{left:r,height:i,width:a}=t,o=e.top-(i-e.height);return{left:r,width:a,height:j(o,e.height,i),top:N(o)}},ee=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{top:r,height:a,width:A(e.left,e.width,o,n),left:M(i)}},F=(e,t,n)=>{let{top:r,height:i,width:a}=t,o=e.left-(a-e.width);return{height:i,width:o<0?e.width:A(e.left,e.width,a,n),top:N(r),left:M(o)}},I=(e,t,n)=>{let{top:r,left:i,height:a,width:o}=t;return{width:o,left:i,height:j(r,e.height,a),top:N(r)}},L={n:P,ne:function(){return P(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},e:ee,se:function(){return I(arguments.length<=0?void 0:arguments[0],ee(...arguments),arguments.length<=2?void 0:arguments[2])},s:I,sw:function(){return I(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])},w:F,nw:function(){return P(arguments.length<=0?void 0:arguments[0],F(...arguments),arguments.length<=2?void 0:arguments[2])}};function R(e,t,n,r){let i=L[e];return i?i(t,a(a({},t),n),r):n}function te(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 ne(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 z(e,t){return t===`horizontal`?ie(e):t===`vertical`?re(e):e}function re(e){return e.slice(0).sort(function(e,t){return e.y>t.y||e.y===t.y&&e.x>t.x?1:e.y===t.y&&e.x===t.x?0:-1})}function ie(e){return e.slice(0).sort(function(e,t){return e.x>t.x||e.x===t.x&&e.y>t.y?1:-1})}function ae(e,t,r,i,o){e||=[];let s=[];n.default.Children.forEach(t,t=>{if(t?.key==null)return;let n=C(e,String(t.key)),r=t.props[`data-grid`];n&&r==null?s.push(m(n)):r?s.push(m(a(a({},r),{},{i:t.key}))):s.push(m({w:1,h:1,x:0,y:l(s),i:String(t.key)}))});let c=S(s,{cols:r});return o?c:v(c,i,r)}function oe(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 se(e){let{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}e.noop=()=>{}})),Dd=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)}})),Od=i(((e,t)=>{t.exports=`SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED`})),kd=i(((e,t)=>{var n=Od();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}})),Ad=i(((e,t)=>{t.exports=kd()()})),jd=i(((e,t)=>{var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,a)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let s of o(t))!c.call(e,s)&&s!==n&&r(e,s,{get:()=>t[s],enumerable:!(a=i(t,s))||a.enumerable});return e},f=(e,t,i)=>(i=e==null?{}:n(s(e)),u(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)),p=e=>u(r({},`__esModule`,{value:!0}),e),m={};l(m,{DraggableCore:()=>xe,default:()=>Se}),t.exports=p(m);var h=f(d()),g=f(Ad()),_=f(a()),v=yr();function y(e,t){for(let n=0,r=e.length;n<r;n++)if(t.apply(t,[e[n],n,e]))return e[n]}function b(e){return typeof e==`function`||Object.prototype.toString.call(e)===`[object Function]`}function x(e){return typeof e==`number`&&!isNaN(e)}function S(e){return parseInt(e,10)}function C(e,t,n){if(e[t])return Error(`Invalid prop ${t} passed to ${n} - do not set this, set it on the child.`)}var w=[`Moz`,`Webkit`,`O`,`ms`];function T(e=`transform`){if(typeof window>`u`)return``;let t=window.document?.documentElement?.style;if(!t||e in t)return``;for(let n=0;n<w.length;n++)if(E(e,w[n])in t)return w[n];return``}function E(e,t){return t?`${t}${D(e)}`:e}function D(e){let t=``,n=!0;for(let r=0;r<e.length;r++)n?(t+=e[r].toUpperCase(),n=!1):e[r]===`-`?n=!0:t+=e[r];return t}var O=T(),k=``;function A(e,t){k||=y([`matches`,`webkitMatchesSelector`,`mozMatchesSelector`,`msMatchesSelector`,`oMatchesSelector`],function(t){return b(e[t])})??``;let n=e[k];return b(n)?!!n.call(e,t):!1}function j(e,t,n){let r=e;do{if(A(r,t))return!0;if(r===n)return!1;r=r.parentNode}while(r);return!1}function M(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.addEventListener?e.addEventListener(t,a,i):e.attachEvent?e.attachEvent(`on`+t,a):e[`on`+t]=a}function N(e,t,n,r){if(!e)return;let i={capture:!0,...r},a=n;e.removeEventListener?e.removeEventListener(t,a,i):e.detachEvent?e.detachEvent(`on`+t,a):e[`on`+t]=null}function P(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderTopWidth),t+=S(n.borderBottomWidth),t}function ee(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t+=S(n.borderLeftWidth),t+=S(n.borderRightWidth),t}function F(e){let t=e.clientHeight,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingTop),t-=S(n.paddingBottom),t}function I(e){let t=e.clientWidth,n=e.ownerDocument.defaultView.getComputedStyle(e);return t-=S(n.paddingLeft),t-=S(n.paddingRight),t}function L(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 R(e,t){let n=ne(e,t,`px`);return{[E(`transform`,O)]:n}}function te(e,t){return ne(e,t,``)}function ne({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 z(e,t){return e.targetTouches&&y(e.targetTouches,e=>t===e.identifier)||e.changedTouches&&y(e.changedTouches,e=>t===e.identifier)}function re(e){if(e.targetTouches&&e.targetTouches[0])return e.targetTouches[0].identifier;if(e.changedTouches&&e.changedTouches[0])return e.changedTouches[0].identifier}function ie(){return typeof __webpack_nonce__<`u`?__webpack_nonce__:void 0}function ae(e,t){if(!e)return;let n=e.getElementById(`react-draggable-style-el`);if(!n){n=e.createElement(`style`),n.type=`text/css`,n.id=`react-draggable-style-el`;let r=t??ie();r&&n.setAttribute(`nonce`,r),n.innerHTML=`.react-draggable-transparent-selection *::-moz-selection {all: inherit;}
|
|
5
5
|
`,n.innerHTML+=`.react-draggable-transparent-selection *::selection {all: inherit;}
|
|
6
6
|
`,e.getElementsByTagName(`head`)[0].appendChild(n)}e.body&&B(e.body,`react-draggable-transparent-selection`)}function oe(e){window.requestAnimationFrame?window.requestAnimationFrame(()=>{se(e)}):se(e)}function se(e){if(e)try{e.body&&ce(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 B(e,t){e.classList?e.classList.add(t):e.className.match(RegExp(`(?:^|\\s)${t}(?!\\S)`))||(e.className+=` ${t}`)}function ce(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(RegExp(`(?:^|\\s)${t}(?!\\S)`,`g`),``)}function V(e,t,n){if(!e.props.bounds)return[t,n];let{bounds:r}=e.props;r=typeof r==`string`?r:he(r);let i=ge(e);if(typeof r==`string`){let{ownerDocument:e}=i,t=e.defaultView;if(!t)throw Error(`Cannot resolve the owner window of the draggable node.`);let n;if(n=r===`parent`?i.parentNode:i.getRootNode().querySelector(r),!(n instanceof t.HTMLElement))throw Error(`Bounds selector "`+r+`" could not find an element.`);let a=n,o=t.getComputedStyle(i),s=t.getComputedStyle(a);r={left:-i.offsetLeft+S(s.paddingLeft)+S(o.marginLeft),top:-i.offsetTop+S(s.paddingTop)+S(o.marginTop),right:I(a)-ee(i)-i.offsetLeft+S(s.paddingRight)-S(o.marginRight),bottom:F(a)-P(i)-i.offsetTop+S(s.paddingBottom)-S(o.marginBottom)}}return x(r.right)&&(t=Math.min(t,r.right)),x(r.bottom)&&(n=Math.min(n,r.bottom)),x(r.left)&&(t=Math.max(t,r.left)),x(r.top)&&(n=Math.max(n,r.top)),[t,n]}function le(e,t,n){return[Math.round(t/e[0])*e[0],Math.round(n/e[1])*e[1]]}function ue(e){return e.props.axis===`both`||e.props.axis===`x`}function de(e){return e.props.axis===`both`||e.props.axis===`y`}function fe(e,t,n){let r=typeof t==`number`?z(e,t):null;if(typeof t==`number`&&!r)return null;let i=ge(n),a=n.props.offsetParent||i.offsetParent||i.ownerDocument.body;return L(r||e,a,n.props.scale)}function pe(e,t,n){let r=!x(e.lastX),i=ge(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 me(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 he(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom}}function ge(e){let t=e.findDOMNode();if(!t)throw Error(`<DraggableCore>: Unmounted during event!`);return t}var _e=f(d()),ve=f(Ad()),ye=f(a()),H=typeof process<`u`&&{}.DRAGGABLE_DEBUG?console.log.bind(console):function(){},be={touch:{start:`touchstart`,move:`touchmove`,stop:`touchend`},mouse:{start:`mousedown`,move:`mousemove`,stop:`mouseup`}},U=be.mouse,xe=class extends _e.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=re(e);this.touchIdentifier=r;let i=fe(e,r,this);if(i==null)return;let{x:a,y:o}=i,s=pe(this,a,o);H(`DraggableCore: handleDragStart: %j`,s),H(`calling`,this.props.onStart),this.props.onStart(e,s)!==!1&&this.mounted!==!1&&(this.props.enableUserSelectHack&&ae(n,this.props.nonce),this.dragging=!0,this.lastX=a,this.lastY=o,M(n,U.move,this.handleDrag),M(n,U.stop,this.handleDragStop))},this.handleDrag=e=>{let t=fe(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]=le(this.props.grid,e,t),!e&&!t)return;n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(H(`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=fe(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]=le(this.props.grid,e,t),n=this.lastX+e,r=this.lastY+t}let i=pe(this,n,r);if(this.props.onStop(e,i)===!1||this.mounted===!1)return!1;let a=this.findDOMNode();a&&this.props.enableUserSelectHack&&oe(a.ownerDocument),H(`DraggableCore: handleDragStop: %j`,i),this.dragging=!1,this.lastX=NaN,this.lastY=NaN,a&&(H(`DraggableCore: Removing handlers`),N(a.ownerDocument,U.move,this.handleDrag),N(a.ownerDocument,U.stop,this.handleDragStop))},this.onMouseDown=e=>(U=be.mouse,this.handleDragStart(e)),this.onMouseUp=e=>(U=be.mouse,this.handleDragStop(e)),this.onTouchStart=e=>(U=be.touch,this.handleDragStart(e)),this.onTouchEnd=e=>(U=be.touch,this.handleDragStop(e))}componentDidMount(){this.mounted=!0;let e=this.findDOMNode();e&&M(e,be.touch.start,this.onTouchStart,{passive:!1})}componentWillUnmount(){this.mounted=!1;let e=this.findDOMNode();if(e){let{ownerDocument:t}=e;N(t,be.mouse.move,this.handleDrag),N(t,be.touch.move,this.handleDrag),N(t,be.mouse.stop,this.handleDragStop),N(t,be.touch.stop,this.handleDragStop),N(e,be.touch.start,this.onTouchStart,{passive:!1}),this.props.enableUserSelectHack&&oe(t)}}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=ye.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):(H(`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 _e.cloneElement(_e.Children.only(this.props.children),{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onTouchEnd:this.onTouchEnd})}};xe.displayName=`DraggableCore`,xe.propTypes={allowAnyClick:ve.default.bool,allowMobileScroll:ve.default.bool,children:ve.default.node.isRequired,disabled:ve.default.bool,enableUserSelectHack:ve.default.bool,offsetParent:function(e,t){if(e[t]&&e[t].nodeType!==1)throw Error(`Draggable's offsetParent must be a DOM Node.`)},grid:ve.default.arrayOf(ve.default.number),handle:ve.default.string,cancel:ve.default.string,nodeRef:ve.default.object,nonce:ve.default.string,onStart:ve.default.func,onDrag:ve.default.func,onStop:ve.default.func,onMouseDown:ve.default.func,scale:ve.default.number,className:C,style:C,transform:C},xe.defaultProps={allowAnyClick:!1,allowMobileScroll:!1,disabled:!1,enableUserSelectHack:!0,onStart:function(){},onDrag:function(){},onStop:function(){},onMouseDown:function(){},scale:1};var Se=class extends h.Component{constructor(e){super(e),this.onDragStart=(e,t)=>{if(H(`Draggable: onDragStart: %j`,t),this.props.onStart(e,me(this,t))===!1)return!1;this.setState({dragging:!0,dragged:!0})},this.onDrag=(e,t)=>{if(!this.state.dragging)return!1;H(`Draggable: onDrag: %j`,t);let n=me(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]=V(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,me(this,t))===!1)return!1;H(`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)?(H(`Draggable: getDerivedStateFromProps %j`,{position:e,prevPropsPosition:t}),{x:e.x,y:e.y,prevPropsPosition:{...e}}):null}componentDidMount(){window.SVGElement!==void 0&&this.findDOMNode()instanceof window.SVGElement&&this.setState({isElementSVG:!0})}componentWillUnmount(){this.state.dragging&&this.setState({dragging:!1})}findDOMNode(){if(this.props?.nodeRef)return this.props.nodeRef.current;let e=_.default;return typeof e.findDOMNode==`function`?e.findDOMNode(this):null}render(){let{axis:e,bounds:t,children:n,defaultPosition:r,defaultClassName:i,defaultClassNameDragging:a,defaultClassNameDragged:o,position:s,positionOffset:c,scale:l,...u}=this.props,d={},f=null,p=!s||this.state.dragging,m=s||r,g={x:ue(this)&&p?this.state.x:m.x,y:de(this)&&p?this.state.y:m.y};this.state.isElementSVG?f=te(g,c):d=R(g,c);let _=h.Children.only(n),y=(0,v.clsx)(_.props.className||``,i,{[a]:this.state.dragging,[o]:this.state.dragged});return h.createElement(xe,{...u,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop},h.cloneElement(_,{className:y,style:{..._.props.style,...d},transform:f}))}};Se.displayName=`Draggable`,Se.propTypes={...xe.propTypes,axis:g.default.oneOf([`both`,`x`,`y`,`none`]),bounds:g.default.oneOfType([g.default.shape({left:g.default.number,right:g.default.number,top:g.default.number,bottom:g.default.number}),g.default.string,g.default.oneOf([!1])]),defaultClassName:g.default.string,defaultClassNameDragging:g.default.string,defaultClassNameDragged:g.default.string,defaultPosition:g.default.shape({x:g.default.number,y:g.default.number}),positionOffset:g.default.shape({x:g.default.oneOfType([g.default.number,g.default.string]),y:g.default.oneOfType([g.default.number,g.default.string])}),position:g.default.shape({x:g.default.number,y:g.default.number}),className:C,style:C,transform:C},Se.defaultProps={...xe.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:xe})})),Md=i(((e,t)=>{var n=jd(),r=n.DraggableCore,i=n.default||n;t.exports=i,t.exports.default=i,t.exports.DraggableCore=r})),Nd=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)}})),Pd=i((e=>{e.__esModule=!0,e.resizableProps=void 0;var t=n(Ad());Md();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)}}})),Fd=i((e=>{e.__esModule=!0,e.default=void 0;var t=o(d()),n=Md(),r=Nd(),i=Pd(),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}})),Id=i((e=>{e.__esModule=!0,e.default=void 0;var t=s(d()),n=o(Ad()),r=o(Fd()),i=Pd(),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})})),Ld=i(((e,t)=>{t.exports=function(){throw Error(`Don't instantiate Resizable directly! Use require('react-resizable').Resizable`)},t.exports.Resizable=Fd().default,t.exports.ResizableBox=Id().default})),Rd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resizeHandleType=e.resizeHandleAxesType=e.default=void 0;var t=r(Ad()),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&&Ed().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}})),zd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=f(d()),n=a(),r=f(Ad()),i=Md(),o=Ld(),s=Ed(),c=Dd(),l=Rd(),u=f(yr());function f(e){return e&&e.__esModule?e:{default:e}}function p(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function m(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?p(Object(n),!0).forEach(function(t){h(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):p(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function h(e,t,n){return(t=g(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function g(e){var t=_(e,`string`);return typeof t==`symbol`?t:t+``}function _(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var v=class extends t.default.Component{constructor(){super(...arguments),h(this,`state`,{resizing:null,dragging:null,className:``}),h(this,`elementRef`,t.default.createRef()),h(this,`onDragStart`,(e,t)=>{let{node:n}=t,{onDragStart:r,transformScale:i}=this.props;if(!r)return;let a={top:0,left:0},{offsetParent:o}=n;if(!o)return;let s=o.getBoundingClientRect(),l=n.getBoundingClientRect(),u=l.left/i,d=s.left/i,f=l.top/i,p=s.top/i;a.left=u-d+o.scrollLeft,a.top=f-p+o.scrollTop,this.setState({dragging:a});let{x:m,y:h}=(0,c.calcXY)(this.getPositionParams(),a.top,a.left,this.props.w,this.props.h);return r.call(this,this.props.i,m,h,{e,node:n,newPosition:a})}),h(this,`onDrag`,(e,t,r)=>{let{node:i,deltaX:a,deltaY:o}=t,{onDrag:s}=this.props;if(!s)return;if(!this.state.dragging)throw Error(`onDrag called before onDragStart.`);let l=this.state.dragging.top+o,u=this.state.dragging.left+a,{isBounded:d,i:f,w:p,h:m,containerWidth:h}=this.props,g=this.getPositionParams();if(d){let{offsetParent:e}=i;if(e){let{margin:t,rowHeight:n}=this.props,r=e.clientHeight-(0,c.calcGridItemWHPx)(m,n,t[1]);l=(0,c.clamp)(l,0,r);let i=(0,c.calcGridColWidth)(g),a=h-(0,c.calcGridItemWHPx)(p,i,t[0]);u=(0,c.clamp)(u,0,a)}}let _={top:l,left:u};r?this.setState({dragging:_}):(0,n.flushSync)(()=>{this.setState({dragging:_})});let{x:v,y}=(0,c.calcXY)(g,l,u,p,m);return s.call(this,f,v,y,{e,node:i,newPosition:_})}),h(this,`onDragStop`,(e,t)=>{let{node:n}=t,{onDragStop:r}=this.props;if(!r)return;if(!this.state.dragging)throw Error(`onDragEnd called before onDragStart.`);let{w:i,h:a,i:o}=this.props,{left:s,top:l}=this.state.dragging,u={top:l,left:s};this.setState({dragging:null});let{x:d,y:f}=(0,c.calcXY)(this.getPositionParams(),l,s,i,a);return r.call(this,o,d,f,{e,node:n,newPosition:u})}),h(this,`onResizeStop`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStop`)),h(this,`onResizeStart`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResizeStart`)),h(this,`onResize`,(e,t,n)=>this.onResizeHandler(e,t,n,`onResize`))}shouldComponentUpdate(e,t){if(this.props.children!==e.children||this.props.droppingPosition!==e.droppingPosition)return!0;let n=(0,c.calcGridItemPosition)(this.getPositionParams(this.props),this.props.x,this.props.y,this.props.w,this.props.h,this.state),r=(0,c.calcGridItemPosition)(this.getPositionParams(e),e.x,e.y,e.w,e.h,t);return!(0,s.fastPositionEqual)(n,r)||this.props.useCSSTransforms!==e.useCSSTransforms}componentDidMount(){this.moveDroppingItem({})}componentDidUpdate(e){this.moveDroppingItem(e)}moveDroppingItem(e){let{droppingPosition:t}=this.props;if(!t)return;let n=this.elementRef.current;if(!n)return;let r=e.droppingPosition||{left:0,top:0},{dragging:i}=this.state,a=i&&t.left!==r.left||t.top!==r.top;if(!i)this.onDragStart(t.e,{node:n,deltaX:t.left,deltaY:t.top});else if(a){let e=t.left-i.left,r=t.top-i.top;this.onDrag(t.e,{node:n,deltaX:e,deltaY:r},!0)}}getPositionParams(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.props;return{cols:e.cols,containerPadding:e.containerPadding,containerWidth:e.containerWidth,margin:e.margin,maxRows:e.maxRows,rowHeight:e.rowHeight}}createStyle(e){let{usePercentages:t,containerWidth:n,useCSSTransforms:r}=this.props,i;return r?i=(0,s.setTransform)(e):(i=(0,s.setTopLeft)(e),t&&(i.left=(0,s.perc)(e.left/n),i.width=(0,s.perc)(e.width/n))),i}mixinDraggable(e,n){return t.default.createElement(i.DraggableCore,{disabled:!n,onStart:this.onDragStart,onDrag:this.onDrag,onStop:this.onDragStop,handle:this.props.handle,cancel:`.react-resizable-handle`+(this.props.cancel?`,`+this.props.cancel:``),scale:this.props.transformScale,nodeRef:this.elementRef},e)}curryResizeHandler(e,t){return(n,r)=>t(n,r,e)}mixinResizable(e,n,r){let{cols:i,minW:a,minH:s,maxW:l,maxH:u,transformScale:d,resizeHandles:f,resizeHandle:p}=this.props,m=this.getPositionParams(),h=(0,c.calcGridItemPosition)(m,0,0,i,0).width,g=(0,c.calcGridItemPosition)(m,0,0,a,s),_=(0,c.calcGridItemPosition)(m,0,0,l,u),v=[g.width,g.height],y=[Math.min(_.width,h),Math.min(_.height,1/0)];return t.default.createElement(o.Resizable,{draggableOpts:{disabled:!r},className:r?void 0:`react-resizable-hide`,width:n.width,height:n.height,minConstraints:v,maxConstraints:y,onResizeStop:this.curryResizeHandler(n,this.onResizeStop),onResizeStart:this.curryResizeHandler(n,this.onResizeStart),onResize:this.curryResizeHandler(n,this.onResize),transformScale:d,resizeHandles:f,handle:p},e)}onResizeHandler(e,t,r,i){let{node:a,size:o,handle:l}=t,u=this.props[i];if(!u)return;let{x:d,y:f,i:p,maxH:m,minH:h,containerWidth:g}=this.props,{minW:_,maxW:v}=this.props,y=o;a&&(y=(0,s.resizeItemInDirection)(l,r,o,g),(0,n.flushSync)(()=>{this.setState({resizing:i===`onResizeStop`?null:y})}));let{w:b,h:x}=(0,c.calcWH)(this.getPositionParams(),y.width,y.height,d,f,l);b=(0,c.clamp)(b,Math.max(_,1),v),x=(0,c.clamp)(x,h,m),u.call(this,p,b,x,{e,node:a,size:y,handle:l})}render(){let{x:e,y:n,w:r,h:i,isDraggable:a,isResizable:o,droppingPosition:s,useCSSTransforms:l}=this.props,d=(0,c.calcGridItemPosition)(this.getPositionParams(),e,n,r,i,this.state),f=t.default.Children.only(this.props.children),p=t.default.cloneElement(f,{ref:this.elementRef,className:(0,u.default)(`react-grid-item`,f.props.className,this.props.className,{static:this.props.static,resizing:!!this.state.resizing,"react-draggable":a,"react-draggable-dragging":!!this.state.dragging,dropping:!!s,cssTransforms:l}),style:m(m(m({},this.props.style),f.props.style),this.createStyle(d))});return p=this.mixinResizable(p,d,o),p=this.mixinDraggable(p,a),p}};e.default=v,h(v,`propTypes`,{children:r.default.element,cols:r.default.number.isRequired,containerWidth:r.default.number.isRequired,rowHeight:r.default.number.isRequired,margin:r.default.array.isRequired,maxRows:r.default.number.isRequired,containerPadding:r.default.array.isRequired,x:r.default.number.isRequired,y:r.default.number.isRequired,w:r.default.number.isRequired,h:r.default.number.isRequired,minW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minWidth not Number`);if(n>e.w||n>e.maxW)return Error(`minWidth larger than item width/maxWidth`)},maxW:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxWidth not Number`);if(n<e.w||n<e.minW)return Error(`maxWidth smaller than item width/minWidth`)},minH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`minHeight not Number`);if(n>e.h||n>e.maxH)return Error(`minHeight larger than item height/maxHeight`)},maxH:function(e,t){let n=e[t];if(typeof n!=`number`)return Error(`maxHeight not Number`);if(n<e.h||n<e.minH)return Error(`maxHeight smaller than item height/minHeight`)},i:r.default.string.isRequired,resizeHandles:l.resizeHandleAxesType,resizeHandle:l.resizeHandleType,onDragStop:r.default.func,onDragStart:r.default.func,onDrag:r.default.func,onResizeStop:r.default.func,onResizeStart:r.default.func,onResize:r.default.func,isDraggable:r.default.bool.isRequired,isResizable:r.default.bool.isRequired,isBounded:r.default.bool.isRequired,static:r.default.bool,useCSSTransforms:r.default.bool.isRequired,transformScale:r.default.number,className:r.default.string,handle:r.default.string,cancel:r.default.string,droppingPosition:r.default.shape({e:r.default.object.isRequired,left:r.default.number.isRequired,top:r.default.number.isRequired})}),h(v,`defaultProps`,{className:``,cancel:``,handle:``,minH:1,minW:1,maxH:1/0,maxW:1/0,transformScale:1})})),Bd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=wd(),r=c(yr()),i=Ed(),a=Dd(),o=c(zd()),s=c(Rd());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})})),Vd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.findOrGenerateResponsiveLayout=i,e.getBreakpointFromWidth=n,e.getColsFromBreakpoint=r,e.sortBreakpoints=a;var t=Ed();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]})}})),Hd=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=l(d()),n=c(Ad()),r=wd(),i=Ed(),a=Vd(),o=c(Bd()),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})})),Ud=r({default:()=>yf});function Wd(e,t){var n=!1,r=!1,i=0;function a(){n&&(n=!1,e()),r&&s()}function o(){rf(a)}function s(){var e=Date.now();if(n){if(e-i<af)return;r=!0}else n=!0,r=!1,setTimeout(o,t);i=e}return s}function Gd(e){return parseFloat(e)||0}function Kd(e){return[...arguments].slice(1).reduce(function(t,n){var r=e[`border-`+n+`-width`];return t+Gd(r)},0)}function qd(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]=Gd(o)}return n}function Jd(e){var t=e.getBBox();return $d(0,0,t.width,t.height)}function Yd(e){var t=e.clientWidth,n=e.clientHeight;if(!t&&!n)return ff;var r=df(e).getComputedStyle(e),i=qd(r),a=i.left+i.right,o=i.top+i.bottom,s=Gd(r.width),c=Gd(r.height);if(r.boxSizing===`border-box`&&(Math.round(s+a)!==t&&(s-=Kd(r,`left`,`right`)+a),Math.round(c+o)!==n&&(c-=Kd(r,`top`,`bottom`)+o)),!Xd(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 $d(i.left,i.top,s,c)}function Xd(e){return e===df(e).document.documentElement}function Zd(e){return tf?pf(e)?Jd(e):Yd(e):ff}function Qd(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=Object.create((typeof DOMRectReadOnly<`u`?DOMRectReadOnly:Object).prototype);return uf(a,{x:t,y:n,width:r,height:i,top:n,right:t+r,bottom:i+n,left:t}),a}function $d(e,t,n,r){return{x:e,y:t,width:n,height:r}}var ef,tf,nf,rf,af,of,sf,cf,lf,uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf=t((()=>{ef=(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}()})(),tf=typeof window<`u`&&typeof document<`u`&&window.document===document,nf=(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`)()})(),rf=(function(){return typeof requestAnimationFrame==`function`?requestAnimationFrame.bind(nf):function(e){return setTimeout(function(){return e(Date.now())},1e3/60)}})(),af=2,of=20,sf=[`top`,`right`,`bottom`,`left`,`width`,`height`,`size`,`weight`],cf=typeof MutationObserver<`u`,lf=function(){function e(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=Wd(this.refresh.bind(this),of)}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(){!tf||this.connected_||(document.addEventListener(`transitionend`,this.onTransitionEnd_),window.addEventListener(`resize`,this.refresh),cf?(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(){!tf||!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;sf.some(function(e){return!!~n.indexOf(e)})&&this.refresh()},e.getInstance=function(){return this.instance_||=new e,this.instance_},e.instance_=null,e}(),uf=(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}),df=(function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||nf}),ff=$d(0,0,0,0),pf=(function(){return typeof SVGGraphicsElement<`u`?function(e){return e instanceof df(e).SVGGraphicsElement}:function(e){return e instanceof df(e).SVGElement&&typeof e.getBBox==`function`}})(),mf=function(){function e(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=$d(0,0,0,0),this.target=e}return e.prototype.isActive=function(){var e=Zd(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}(),hf=function(){function e(e,t){var n=Qd(t);uf(this,{target:e,contentRect:n})}return e}(),gf=function(){function e(e,t,n){if(this.activeObservations_=[],this.observations_=new ef,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 df(e).Element))throw TypeError(`parameter 1 is not of type "Element".`);var t=this.observations_;t.has(e)||(t.set(e,new mf(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 df(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 hf(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}(),_f=typeof WeakMap<`u`?new WeakMap:new ef,vf=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 gf(t,lf.getInstance(),this);_f.set(this,n)}return e}(),[`observe`,`unobserve`,`disconnect`].forEach(function(e){vf.prototype[e]=function(){var t;return(t=_f.get(this))[e].apply(t,arguments)}}),yf=(function(){return nf.ResizeObserver===void 0?vf:nf.ResizeObserver})()})),xf=i((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=_;var n=c(d()),r=s(Ad()),i=s((bf(),e(Ud))),a=s(yr()),o=[`measureBeforeMount`];function s(e){return e&&e.__esModule?e:{default:e}}function c(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(c=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!=="default"&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l.apply(null,arguments)}function u(e,t){if(e==null)return{};var n,r,i=f(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function f(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function p(e,t,n){return(t=m(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e){var t=h(e,`string`);return typeof t==`symbol`?t:t+``}function h(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var g=`react-grid-layout`;function _(e){var t;return t=class extends n.Component{constructor(){super(...arguments),p(this,`state`,{width:1280}),p(this,`elementRef`,n.createRef()),p(this,`mounted`,!1),p(this,`resizeObserver`,void 0)}componentDidMount(){this.mounted=!0,this.resizeObserver=new i.default(e=>{if(this.elementRef.current instanceof HTMLElement){let t=e[0].contentRect.width;this.setState({width:t})}});let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.observe(e)}componentWillUnmount(){this.mounted=!1;let e=this.elementRef.current;e instanceof HTMLElement&&this.resizeObserver.unobserve(e),this.resizeObserver.disconnect()}render(){let t=this.props,{measureBeforeMount:r}=t,i=u(t,o);return r&&!this.mounted?n.createElement(`div`,{className:(0,a.default)(this.props.className,g),style:this.props.style,ref:this.elementRef}):n.createElement(e,l({innerRef:this.elementRef},i,this.state))}},p(t,`defaultProps`,{measureBeforeMount:!1}),p(t,`propTypes`,{measureBeforeMount:r.default.bool}),t}})),Sf=n(i(((e,t)=>{t.exports=Bd().default,t.exports.utils=Ed(),t.exports.calculateUtils=Dd(),t.exports.Responsive=Hd().default,t.exports.Responsive.utils=Vd(),t.exports.WidthProvider=xf().default}))(),1),Cf=new Map;function wf(e){Cf.set(e.type,e)}function Tf(e){return Cf.get(e)}function Ef(){return[...Cf.values()]}function Df(e){let t=[],n=!1;return{text:e.replace(/"[^"]*"|(^|\s)@id:([^\s]*)/g,(e,r,i)=>{if(i===void 0)return e;let a=i.replace(/^#/,``),o=Number(a);return!/^\d+$/.test(a)||!Number.isInteger(o)||o<=0||o>4294967295?n=!0:t.push(o),r}).trim(),ids:t,invalid:n}}function Of(e,t){return e.slice(0,3).map(e=>{let n=t.get(e.id),r=e.reason===`not-found`?`Source missing from the storage index. Resync the source backend and retry.`:e.reason===`not found`?`Document no longer exists in this workspace. Refresh the list and select it again.`:e.reason;return`${n?`${n} (ID ${e.id})`:`Document ${e.id}`}: ${r}`}).join(`
|
|
7
7
|
`)+(e.length>3?`\n…and ${e.length-3} more failed file${e.length===4?``:`s`}.`:``)}function kf(){let e,t,n=!1,r=()=>{clearTimeout(e),e=void 0,t=void 0};return{cancel:r,start(i,a,o){r(),n=!1,t={x:i,y:a},e=setTimeout(()=>{e=void 0,n=!0,o()},500)},move(e,n){t&&Math.hypot(e-t.x,n-t.y)>10&&r()},consumeClick(){let e=n;return n=!1,e},contextMenu(){let e=n;return t&&(n=!0),r(),e},reset(){r(),n=!1}}}function Af(){let[e]=(0,X.useState)(kf);return(0,X.useEffect)(()=>e.cancel,[e]),{onPointerDown:t=>{if(e.reset(),t.pointerType!==`touch`||!t.isPrimary)return;let n=t.target;if(!t.currentTarget.contains(n)||n.closest(`button, input, textarea, select, a, [contenteditable="true"], [role="dialog"]`))return;let{clientX:r,clientY:i}=t;e.start(r,i,()=>{n.dispatchEvent(new window.MouseEvent(`contextmenu`,{bubbles:!0,cancelable:!0,clientX:r,clientY:i}))})},onPointerMove:t=>e.move(t.clientX,t.clientY),onPointerUp:e.cancel,onPointerCancel:e.cancel,onPointerLeave:e.cancel,onDragStartCapture:t=>{e.cancel(),e.consumeClick()&&t.preventDefault()},onContextMenuCapture:t=>{t.isTrusted&&e.contextMenu()&&(t.preventDefault(),t.stopPropagation())},onClickCapture:t=>{e.consumeClick()&&(t.preventDefault(),t.stopPropagation())}}}function jf(e,t,n,r,i=!1){let a=e.indexOf(n);if(a<0)return new Set(r);let o=t===null?-1:e.indexOf(t),s=o<0?a:o,c=i?new Set(r):new Set;for(let t of e.slice(Math.min(s,a),Math.max(s,a)+1))c.add(t);return c}var Mf=n(a(),1),Nf=[];function Pf(e){if(e.key!==`Escape`||e.isComposing||e.defaultPrevented)return;let t=Nf[Nf.length-1];t&&(e.preventDefault(),t())}function Ff(e,t=!0){let n=(0,X.useRef)(e);(0,X.useEffect)(()=>{n.current=e});let r=t&&!!e;(0,X.useEffect)(()=>{if(!r)return;let e=()=>n.current?.();return Nf.push(e),Nf.length===1&&window.addEventListener(`keydown`,Pf),()=>{let t=Nf.indexOf(e);t>=0&&Nf.splice(t,1),Nf.length===0&&window.removeEventListener(`keydown`,Pf)}},[r])}function If({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,X.useRef)(null),[o,s]=(0,X.useState)({x:e,y:t});return Ff(n),(0,X.useLayoutEffect)(()=>{let n=a.current;if(!n)return;let{width:r,height:i}=n.getBoundingClientRect();s({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})},[e,t]),(0,Mf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,Z.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:K(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r),children:i})]}),document.body)}var Lf=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),Rf={Delete:`Del`,Backspace:`⌫`,Enter:`↵`,ArrowUp:`↑`,ArrowDown:`↓`};function zf(e){let t=e.split(`+`),n=t.pop()||``,r=Rf[n]||(n.length===1?n.toUpperCase():n);if(Lf){let e={Mod:`⌘`,Shift:`⇧`,Alt:`⌥`,Ctrl:`⌃`};return[...[`Ctrl`,`Alt`,`Shift`,`Mod`].filter(e=>t.includes(e)).map(t=>e[t]),r].join(``)}return[...t.map(e=>e===`Mod`?`Ctrl`:e),r].join(`+`)}function Bf(e,t){let n=t.split(`+`),r=n.pop()||``;return(Lf?e.metaKey:e.ctrlKey)!==n.includes(`Mod`)||e.shiftKey!==n.includes(`Shift`)||e.altKey!==n.includes(`Alt`)||Lf&&e.ctrlKey!==n.includes(`Ctrl`)?!1:r.length===1?e.key.toLowerCase()===r.toLowerCase():e.key===r}function Vf(e){if(e?.closest?.(`input, textarea, select, [contenteditable="true"], [role="dialog"], [role="menu"]`))return!0;let t=typeof window<`u`?window.getSelection():null;return!!t&&!t.isCollapsed&&t.toString().length>0}function Hf(e,t){if(e.defaultPrevented||e.nativeEvent.isComposing||Vf(e.target))return!1;let n=t.find(t=>t.shortcut&&!t.disabled&&Bf(e,t.shortcut));return n?(e.preventDefault(),e.stopPropagation(),n.run(),!0):!1}function Uf(e){return e.key===`ContextMenu`||e.key===`F10`&&e.shiftKey}function Wf(){return typeof window<`u`&&window.matchMedia(`(max-width: 767px)`).matches}function Gf(e,t=`below`){let n=e.getBoundingClientRect();return t===`below`?{x:n.left,y:n.bottom+4}:{x:n.left+Math.min(24,n.width/2),y:n.top+Math.min(24,n.height/2)}}function Kf(e){let t=[];for(let n of e){let e=t[t.length-1];e&&(e[0].group??``)===(n.group??``)?e.push(n):t.push([n])}return t}function qf(e,t){t(),setTimeout(()=>{e.run()},0)}function Jf({anchor:e,items:t,onClose:n,label:r}){let i=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let e=document.activeElement;return i.current?.querySelector(`[role="menuitem"]:not([aria-disabled="true"])`)?.focus(),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[]),(0,Z.jsx)(If,{x:e.x,y:e.y,onClose:n,className:`min-w-[200px] rounded-lg border bg-background py-1 shadow-elevation-3`,children:(0,Z.jsx)(`div`,{ref:i,role:`menu`,"aria-label":r,onKeyDown:e=>{let t=Array.from(i.current?.querySelectorAll(`[role="menuitem"]:not([aria-disabled="true"])`)??[]);if(t.length===0)return;let r=t.indexOf(document.activeElement),a=e=>t[(e+t.length)%t.length]?.focus();switch(e.key){case`ArrowDown`:e.preventDefault(),a(r+1);return;case`ArrowUp`:e.preventDefault(),a(r<0?-1:r-1);return;case`Home`:e.preventDefault(),a(0);return;case`End`:e.preventDefault(),a(-1);return;case`Tab`:e.preventDefault(),n();return}if(e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let n=e.key.toLowerCase(),i=[...t.slice(r+1),...t.slice(0,r+1)].find(e=>e.textContent?.trim().toLowerCase().startsWith(n));i&&(e.preventDefault(),i.focus())}},onContextMenu:e=>e.preventDefault(),children:Kf(t).map((e,t)=>(0,Z.jsxs)(X.Fragment,{children:[t>0&&(0,Z.jsx)(`div`,{role:`separator`,className:`my-1 h-px bg-border`}),e[0].groupLabel&&(0,Z.jsx)(`div`,{className:`px-3 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let t=e.icon;return(0,Z.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,"aria-disabled":e.disabled||void 0,title:e.hint,onClick:()=>{e.disabled||qf(e,n)},className:K(`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm outline-none`,e.disabled?`cursor-default opacity-50`:e.destructive?`text-destructive hover:bg-destructive hover:text-destructive-foreground focus:bg-destructive focus:text-destructive-foreground`:`hover:bg-muted focus:bg-muted`),children:[t?(0,Z.jsx)(t,{className:`h-3.5 w-3.5 shrink-0`}):(0,Z.jsx)(`span`,{className:`w-3.5 shrink-0`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.shortcut&&(0,Z.jsx)(`kbd`,{className:`ml-4 shrink-0 font-sans text-[11px] text-muted-foreground`,children:zf(e.shortcut)})]},e.id)})]},`${e[0].group??``}:${t}`))})})}function Yf({items:e,onClose:t,header:n}){Ff(t);let r=`flex w-full items-center gap-3 rounded-xl border bg-card px-4 py-3.5 text-base font-medium transition-transform active:scale-[.98]`;return(0,Mf.createPortal)((0,Z.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-background animate-in slide-in-from-bottom-10 fade-in duration-200`,onClick:t,onContextMenu:e=>e.preventDefault(),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:n}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,Z.jsx)(Me,{className:`h-5 w-5`})})]}),(0,Z.jsx)(`div`,{className:`min-h-4 flex-1`}),(0,Z.jsxs)(`div`,{className:`max-h-[75vh] shrink-0 space-y-2 overflow-y-auto px-4 pt-2`,style:{paddingBottom:`calc(var(--safe-bottom) + 1.25rem)`},onClick:e=>e.stopPropagation(),children:[Kf(e).map((e,n)=>(0,Z.jsxs)(`div`,{className:K(`space-y-2`,n>0&&`pt-2`),children:[e[0].groupLabel&&(0,Z.jsx)(`div`,{className:`px-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,children:e[0].groupLabel}),e.map(e=>{let n=e.icon;return(0,Z.jsxs)(`button`,{type:`button`,disabled:e.disabled,onClick:()=>qf(e,t),className:K(r,e.destructive&&`border-destructive/30 text-destructive`,e.disabled&&`opacity-50`),children:[n&&(0,Z.jsx)(n,{className:K(`h-5 w-5 shrink-0`,!e.destructive&&`text-muted-foreground`)}),e.label]},e.id)})]},`${e[0].group??``}:${n}`)),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`${r} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function Xf({anchor:e,items:t,onClose:n,label:r,header:i}){return t.length===0?null:Wf()?(0,Z.jsx)(Yf,{items:t,onClose:n,header:i??(r&&(0,Z.jsx)(`div`,{className:`truncate text-base font-semibold`,children:r}))}):(0,Z.jsx)(Jf,{anchor:e,items:t,onClose:n,label:r})}var Zf=null;function Qf(){return Zf||=fetch(`https://api.iconify.design/collection?prefix=ph`).then(e=>e.json()).then(e=>[...e.uncategorized??[],...Object.values(e.categories??{}).flat()].filter(e=>e.endsWith(`-fill`)).map(e=>`ph:${e}`)).catch(()=>(Zf=null,[])),Zf}async function $f(e,t=120){let n=e.trim();if(!n)return[];try{let e=await(await fetch(`https://api.iconify.design/search?query=${encodeURIComponent(n)}&limit=${t}`)).json();return Array.isArray(e.icons)?e.icons:[]}catch{return[]}}var ep=[`#ef4444`,`#f97316`,`#f59e0b`,`#eab308`,`#84cc16`,`#22c55e`,`#14b8a6`,`#06b6d4`,`#3b82f6`,`#6366f1`,`#8b5cf6`,`#a855f7`,`#ec4899`,`#f43f5e`,`#64748b`,`#78716c`],tp={home:{icon:`ph:house-fill`,color:`#3b82f6`},travel:{icon:`ph:airplane-tilt-fill`,color:`#06b6d4`},work:{icon:`ph:briefcase-fill`,color:`#64748b`},books:{icon:`ph:books-fill`,color:`#a855f7`},workouts:{icon:`ph:barbell-fill`,color:`#22c55e`},sport:{icon:`ph:barbell-fill`,color:`#22c55e`},sports:{icon:`ph:barbell-fill`,color:`#22c55e`},fitness:{icon:`ph:barbell-fill`,color:`#22c55e`},beauty:{icon:`ph:flower-lotus-fill`,color:`#ec4899`},recipes:{icon:`ph:cooking-pot-fill`,color:`#f97316`},"to watch":{icon:`ph:monitor-play-fill`,color:`#f43f5e`},"to read":{icon:`ph:book-open-text-fill`,color:`#8b5cf6`},learning:{icon:`ph:graduation-cap-fill`,color:`#6366f1`},tech:{icon:`ph:cpu-fill`,color:`#14b8a6`},music:{icon:`ph:music-notes-fill`,color:`#eab308`},finance:{icon:`ph:piggy-bank-fill`,color:`#84cc16`},shopping:{icon:`ph:shopping-cart-fill`,color:`#f59e0b`},ideas:{icon:`ph:lightbulb-filament-fill`,color:`#facc15`},data:{icon:`ph:database-fill`,color:`#14b8a6`}},np={"workspace:home":{icon:`ph:house-fill`,color:`#3b82f6`},"workspace:data":{icon:`ph:database-fill`,color:`#14b8a6`}},rp={file:{icon:`ph:folder-fill`,color:`#64748b`},cacache:{icon:`ph:database-fill`,color:`#14b8a6`},s3:{icon:`ph:cloud-fill`,color:`#0ea5e9`},gdrive:{icon:`mdi:google-drive`,color:`#fbbc04`},http:{icon:`ph:globe-fill`,color:`#0ea5e9`},imap:{icon:`ph:envelope-fill`,color:`#a855f7`}},ip={icon:`ph:hard-drive-fill`,color:`#64748b`};function ap(e){let t=e.config?.ui??{},n=e.address&&np[e.address]||e.driver&&rp[e.driver]||ip;return{icon:typeof t.icon==`string`?t.icon:n.icon??ip.icon,color:typeof t.color==`string`?t.color:n.color??ip.color}}function op(e){let t=e.metadata?.ui??{},n=tp[String(e.label??e.name??``).trim().toLowerCase()];return{icon:typeof t.icon==`string`?t.icon:n?.icon,color:typeof t.color==`string`?t.color:e.color??n?.color}}function sp(e){let t=tp[(e.split(`/`).filter(Boolean).pop()??``).trim().toLowerCase()];return t?{metadata:cp(void 0,t)}:null}function cp(e,t){let n={...e??{}},r={...n.ui??{}};return`icon`in t&&(t.icon?r.icon=t.icon:delete r.icon),`color`in t&&(t.color?r.color=t.color:delete r.color),n.ui=r,n}var lp=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,up=()=>({h:lp(0,360),s:lp(42,98),l:lp(40,90)}),dp=(e,t,n)=>{t/=100,n/=100;let r=(1-Math.abs(2*n-1))*t,i=r*(1-Math.abs(e/60%2-1)),a=n-r/2,o=0,s=0,c=0;0<=e&&e<60?(o=r,s=i):60<=e&&e<120?(o=i,s=r):120<=e&&e<180?(s=r,c=i):180<=e&&e<240?(s=i,c=r):240<=e&&e<300?(o=i,c=r):300<=e&&e<360&&(o=r,c=i),o=Math.round((o+a)*255),s=Math.round((s+a)*255),c=Math.round((c+a)*255);let l=e=>e.toString(16).padStart(2,`0`);return`#${l(o)}${l(s)}${l(c)}`},fp=()=>{let{h:e,s:t,l:n}=up();return dp(e,t,n)},pp=e=>{let t=e.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!t)return null;let n=t[1];n.length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=e=>{let t=parseInt(n.slice(e*2,e*2+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(1)+.0722*r(2)},mp=(e,t=.82)=>{let n=pp(e);return n===null||n>t},hp=e=>e&&!mp(e)?e:void 0,gp=e=>{if(!e)return`text-muted-foreground/70`;let t=pp(e);return t!==null&&t>.5?`text-black/45`:`text-white/80`},_p=e=>{let t=pp(e);return t!==null&&t>.45?`text-black`:`text-white`},vp=[{color:`text-data-1`,chip:`bg-data-1/15`},{color:`text-data-2`,chip:`bg-data-2/15`},{color:`text-data-3`,chip:`bg-data-3/15`},{color:`text-data-4`,chip:`bg-data-4/15`},{color:`text-data-5`,chip:`bg-data-5/15`},{color:`text-data-6`,chip:`bg-data-6/15`},{color:`text-data-7`,chip:`bg-data-7/15`},{color:`text-data-8`,chip:`bg-data-8/15`},{color:`text-data-9`,chip:`bg-data-9/15`},{color:`text-data-10`,chip:`bg-data-10/15`},{color:`text-data-11`,chip:`bg-data-11/15`},{color:`text-data-12`,chip:`bg-data-12/15`}];function yp(e,t){return{Icon:e,...vp[t-1]}}var bp={tab:yp(ae,7),link:yp(ae,7),email:yp(Cn,3),note:yp(xn,3),task:yp(Tn,5),message:yp(je,6),identity:yp(Ze,2),contact:yp(Ze,2),device:yp(fe,10),application:yp(et,11),dotfile:yp(qt,4),document:yp(wn,9)},xp=[{test:/^image\//,spec:yp(y,5)},{test:/^video\//,spec:yp(tn,11)},{test:/^audio\//,spec:yp(re,10)},{test:/pdf$/,spec:yp(wn,1)},{test:/zip|tar|gzip|7z|rar|compressed/,spec:yp(Nt,12)},{test:/json|javascript|typescript|xml|html|css|x-sh|python/,spec:yp(Yn,6)},{test:/^text\//,spec:yp(wn,12)}],Sp=yp(bt,6),Cp=yp(bt,9);function wp(e){let t=(e.schema||``).split(`/`).pop()||``;if(t===`file`){let t=String(e.metadata?.contentType||``).toLowerCase();return xp.find(({test:e})=>e.test(t))?.spec||Sp}return bp[t]||Cp}var Tp={3.5:`h-3.5 w-3.5`,4:`h-4 w-4`,5:`h-5 w-5`,10:`h-10 w-10`};function Ep(e){let t=[],n=typeof e?.favIconUrl==`string`?e.favIconUrl:``;/^https?:\/\//i.test(n)&&t.push(n);let r=typeof e?.url==`string`?e.url:``;try{let e=new URL(r).origin;if(/^https?:/i.test(e)){let n=`${e}/favicon.ico`;t.includes(n)||t.push(n)}}catch{}return t}function Dp({document:e,size:t=4,chip:n=!1,className:r}){let i=wp(e),a=e.schema===`data/schema/tab`?Ep(e.data):[],[o,s]=(0,X.useState)(0),c=a[o]??null,l=c?(0,Z.jsx)(`img`,{src:c,alt:``,loading:`lazy`,onError:()=>s(e=>e+1),className:K(Tp[t],`rounded-xs object-contain`,!n&&`shrink-0`,!n&&r)}):(0,Z.jsx)(i.Icon,{className:K(Tp[t],i.color,!n&&`shrink-0`,!n&&r)});return n?(0,Z.jsx)(`span`,{className:K(`inline-flex shrink-0 items-center justify-center rounded-md`,t>=10?`p-3`:`p-1`,i.chip,r),children:l}):l}function Op({items:e,onNavigate:t,disabled:n,className:r,label:i=`Tree path`}){let a=(0,X.useRef)(null),o=e[e.length-1]?.path;return(0,X.useEffect)(()=>{let e=a.current;e&&(e.scrollLeft=e.scrollWidth)},[o]),(0,Z.jsx)(`nav`,{"aria-label":i,className:K(`min-w-0 flex-1`,r),children:(0,Z.jsx)(`ol`,{ref:a,className:`flex min-w-0 items-center gap-1 overflow-x-auto py-0.5 text-sm`,children:e.map((r,i)=>{let a=i===e.length-1,o=K(`block max-w-56 truncate rounded px-1.5 py-1`,a?`font-medium text-foreground`:`text-muted-foreground`);return(0,Z.jsxs)(`li`,{className:`flex shrink-0 items-center gap-1`,children:[i>0&&(0,Z.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/60`,children:`/`}),t&&!a?(0,Z.jsx)(`button`,{type:`button`,title:r.path===`/`?`${r.label} (root)`:r.path,disabled:n,onClick:()=>t(r.path),className:K(o,`hover:bg-accent hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50`),children:r.label}):(0,Z.jsx)(`span`,{title:r.path===`/`?r.label:r.path,"aria-current":a?`location`:void 0,className:o,children:r.label})]},r.path)})})})}function kp(e,t){let n=e.split(`/`).filter(Boolean);return[{label:t,path:`/`},...n.map((e,t)=>({label:e,path:`/${n.slice(0,t+1).join(`/`)}`}))]}var Ap={context:(0,Z.jsx)(We,{className:`h-3.5 w-3.5`}),directory:(0,Z.jsx)(Mn,{className:`h-3.5 w-3.5`}),backends:(0,Z.jsx)(hr,{className:`h-3.5 w-3.5`}),relations:(0,Z.jsx)(_n,{className:`h-3.5 w-3.5`})},jp={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function Mp(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function Np(e,t){let n=(0,X.useRef)(null),r=(0,X.useRef)(!1),i=()=>{n.current&&=(clearTimeout(n.current),null)},a=e=>()=>{if(r.current){r.current=!1;return}e()};return t?{guardClick:a,handlers:{onContextMenu:n=>{n.preventDefault(),n.stopPropagation(),t({clientX:n.clientX,clientY:n.clientY,path:e})},onPointerDown:a=>{if(a.pointerType!==`touch`)return;let{clientX:o,clientY:s}=a;i(),n.current=setTimeout(()=>{r.current=!0,t({clientX:o,clientY:s,path:e})},500)},onPointerUp:i,onPointerLeave:i,onPointerMove:i}}:{handlers:{},guardClick:a}}function Pp(e,t,n){let r=Mp(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>Pp(e,r,n))??!1}var Fp=200;function Ip({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,X.useState)(``);return(0,Z.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-md bg-card px-3 py-2.5 text-sm shadow-elevation-1`,children:[(0,Z.jsx)(ir,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,value:r,onChange:e=>i(e.target.value),onKeyDown:n=>{n.key===`Enter`&&r.trim()&&e(r.trim()),n.key===`Escape`&&t()},onBlur:()=>{n||t()},placeholder:`New folder name…`,autoFocus:!0,disabled:n,className:`w-full flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),n&&(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function Lp({node:e,parentPath:t,query:n,selected:r,onToggle:i,onActivate:a,onRowMenu:o,createParent:s,onCreateConfirm:l,onCreateCancel:u,creating:d}){let f=Mp(t,e.name),p=!!e.children?.length,[m,h]=(0,X.useState)(!1),{handlers:g,guardClick:_}=Np(f,o);if(n&&!Pp(e,t,n))return null;let v=s===f,y=m||n.length>0||v,b=r.has(f),x=e.type===`canvas`,S=op(e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,b?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:_(()=>i(f)),onDoubleClick:a?()=>a(f):void 0,title:f,...g,children:[(0,Z.jsx)(`button`,{type:`button`,className:K(`shrink-0 text-muted-foreground hover:text-foreground`,!p&&`invisible`),onClick:e=>{e.stopPropagation(),h(e=>!e)},children:y?(0,Z.jsx)(Ge,{className:`w-4 h-4`}):(0,Z.jsx)(Ye,{className:`w-4 h-4`})}),(0,Z.jsx)(c,{icon:S.icon||(x?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:hp(S.color),className:K(`shrink-0`,!hp(S.color)&&(x?`text-primary`:`text-muted-foreground`))}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),y&&p||v?(0,Z.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[v&&l&&u&&(0,Z.jsx)(Ip,{busy:d,onConfirm:e=>{h(!0),l(f,e)},onCancel:u}),y&&e.children?.map(e=>(0,Z.jsx)(Lp,{node:e,parentPath:f,query:n,selected:r,onToggle:i,onActivate:a,onRowMenu:o,createParent:s,onCreateConfirm:l,onCreateCancel:u,creating:d},e.id||e.name))]}):null]})}function Rp({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=hp(e.color);return(0,Z.jsxs)(`div`,{onClick:()=>n(e.name),className:`group relative flex cursor-pointer items-center gap-2 rounded-md bg-card px-3 py-2.5 shadow-elevation-1 transition-all hover:bg-accent/50 hover:shadow`,style:{borderRight:`6px solid ${t||`transparent`}`,borderRadius:t?`6px 0 0 6px`:void 0},children:[(0,Z.jsx)(c,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:K(`shrink-0`,!t&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,Z.jsx)(Ye,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function zp({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:a,excludeDocumentIds:o}){let[s,c]=(0,X.useState)(`folder`),[l,u]=(0,X.useState)(``),d=l.trim().toLowerCase(),[f,p]=(0,X.useState)(`/`),[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)([]),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(``),[E,D]=(0,X.useState)(t),O=n?t:E,k=e=>{p(`/`),c(`folder`),C(``),T(``),a?.(`/`),n?n(e):D(e)},[A,j]=(0,X.useState)(O);O!==A&&(j(O),p(`/`),c(`folder`)),(0,X.useEffect)(()=>{let e=setTimeout(()=>T(S.trim()),300);return()=>clearTimeout(e)},[S]),(0,X.useEffect)(()=>{let t=!1;async function n(){_(!0);try{let n=await Gi(e,O);t||h(n)}catch{t||h(null)}finally{t||_(!1)}}return n(),()=>{t=!0}},[e,O]),(0,X.useEffect)(()=>{if(s!==`documents`)return;let t=!1,n=O===`directory`?`directory`:ao,r=O===`context`?`context`:`directory`;async function i(){x(!0);try{let i=w?await so(e,f,[],{treeName:n,treeType:r,q:w,limit:Fp}):await Yi(e,f,n,{limit:Fp});t||y(i.payload||[])}catch{t||y([])}finally{t||x(!1)}}return i(),()=>{t=!0}},[e,O,f,s,w]);let M=e=>{p(e),a?.(e)},N=o?.size?v.filter(e=>!o.has(e.id)):v;return s===`folder`?(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,Z.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>k(e),className:K(`flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors`,O===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Browse the ${jp[e].toLowerCase()}`,children:[Ap[e],(0,Z.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>c(`documents`),className:`inline-flex items-center gap-1 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90`,children:[`Next `,(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5`})]})]}),(0,Z.jsx)(Op,{items:kp(f,e),onNavigate:M,label:`Folder path`}),(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Filter folders…`,value:l,onChange:e=>u(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-3 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:g?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,f===`/`?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:()=>M(`/`),onDoubleClick:()=>{M(`/`),c(`documents`)},title:`/`,children:[(0,Z.jsx)(Ge,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Z.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:m?.children?.length?m.children.map(e=>(0,Z.jsx)(Lp,{node:e,parentPath:`/`,query:d,selected:new Set([f]),onToggle:M,onActivate:e=>{M(e),c(`documents`)}},e.id||e.name)):(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>c(`folder`),className:`inline-flex min-w-0 items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Back to folders`,children:[(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,Z.jsx)(`span`,{children:`Folders`})]}),(0,Z.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground`,children:[`[`,O,`]`]}),(0,Z.jsx)(Op,{items:kp(f,e),onNavigate:M,label:`Document folder path`})]}),(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Search documents in this folder…`,value:S,onChange:e=>C(e.target.value),className:`w-full rounded-md border border-input bg-background py-1.5 pl-8 pr-7 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`}),S&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>C(``),className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear document search`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:b?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):N.length===0?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:w?`No documents match “${w}” here.`:`No documents in this folder.`}):N.map(e=>{let t=Ui(e),n=r.has(e.id);return(0,Z.jsxs)(`div`,{onClick:()=>i(e.id),className:K(`flex min-h-9 items-center gap-2 rounded-md px-3 py-1.5 cursor-pointer transition-all select-none text-sm`,n?`bg-primary/[0.08] hover:bg-primary/[0.12]`:`hover:bg-primary/[0.04]`),children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,Z.jsx)(Dp,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function Bp({onClose:e,onConfirm:t,documentCount:n,fixedWorkspaceName:r,excludeWorkspace:i,multiple:a=!0,saving:o=!1,savingContent:s,sizeClassName:c,tabs:l=[`context`,`directory`],title:u,confirmLabel:d,backendFolderCreation:f,onConfirmRelation:p,relationWorkspaceName:m,relationPredicates:h,relationExcludeIds:g}){let[_,v]=(0,X.useState)(r?`tree`:`workspace`),[y,b]=(0,X.useState)([]),[x,S]=(0,X.useState)(!r),[C,w]=(0,X.useState)(r??null),[T,E]=(0,X.useState)(l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`),D=h?.length?h:[...$a],[O,k]=(0,X.useState)(D[0]??`references`),[A,j]=(0,X.useState)(`out`),[M,N]=(0,X.useState)(new Set),[P,ee]=(0,X.useState)(null),[F,I]=(0,X.useState)(`context`),[L,te]=(0,X.useState)(!1),ne=T===`pins`?F:T;(0,X.useEffect)(()=>{if(!C)return;let e=!1;return _o(C).then(t=>{e||ee(t)}).catch(()=>{e||te(!0)}),()=>{e=!0}},[C]);let z=T===`relations`,[re,ie]=(0,X.useState)(null),[ae,oe]=(0,X.useState)(!1),[se,B]=(0,X.useState)(new Set),[ce,V]=(0,X.useState)(``),le=ce.trim().toLowerCase(),{showErrorToast:ue}=Wr(),[de,fe]=(0,X.useState)(null),[pe,me]=(0,X.useState)(null),[he,ge]=(0,X.useState)(!1);Ff(e,!o&&!he);let _e=Np(`/`,e=>fe(e)),ve=e=>!o&&(T===`backends`?f?.canCreate(e)===!0:T!==`pins`&&T!==`relations`),ye=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!C||he||!ve(e))){ge(!0);try{let t=`${e===`/`?``:e}/${n}`,r=T===`context`?ao:T;T===`backends`?await f.create(e,n):await _a(C,t,!0,r),Sa(C,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:C,treeName:r,cacheInvalidated:!0}}));let i=await Gi(C,T);ie(i),B(e=>a?new Set([...e,t]):new Set([t])),V(``),me(null)}catch(e){ue(e instanceof Error?e.message:`Failed to create folder`)}finally{ge(!1)}}},[H,be]=(0,X.useState)(r);r!==H&&(be(r),r||S(!0)),(0,X.useEffect)(()=>{r||Xr().then(e=>b(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>b([])).finally(()=>S(!1))},[r,i]),(0,X.useEffect)(()=>{if(!C||T===`relations`||T===`pins`)return;let e=!1,t=0;async function n(n=!1){let r=++t;n||oe(!0);try{let n=await Gi(C,T);!e&&r===t&&ie(n)}catch{!e&&r===t&&!n&&ie(null)}finally{!e&&r===t&&oe(!1)}}let r=e=>{let t=e.detail;t?.workspaceName&&t.workspaceName!==C||t?.treeName&&t.treeName!==T||(t?.cacheInvalidated||Sa(C,T),n(!0))};return window.addEventListener(`workspace:tree:refresh`,r),n(),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,r)}},[C,T]);let U=e=>{e!==C&&(ee(null),te(!1)),E(l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`),w(e),B(new Set),N(new Set),v(`tree`)},xe=e=>{N(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Se=e=>{if(!a){B(new Set([e]));return}B(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ce=z?M.size>0&&!!p:se.size>0,W=async()=>{if(!(!C||o||!Ce)){if(z){await p?.({predicate:O,direction:A,targetIds:Array.from(M)},{workspaceName:m??C});return}await t(Array.from(se),{workspaceName:C,treeName:ne===`context`?ao:ne,treeType:ne===`context`?`context`:`directory`})}},G=n??1;return o&&s?(0,Z.jsx)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:s}):(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,c||`h-viewport-card max-h-full w-[min(380px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Gt,{className:`h-4 w-4`}),u??(_===`workspace`?`Link to…`:z?`Relate ${G} document${G===1?``:`s`} to…`:`Link ${G} document${G===1?``:`s`} to…`)]}),(0,Z.jsx)(`button`,{type:`button`,onClick:e,disabled:o||he,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Z.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-200`,style:{transform:_===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Z.jsx)(Rp,{workspaces:y,loading:x,onPick:U})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,Z.jsx)(`button`,{type:`button`,disabled:he,onClick:()=>v(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4 rotate-180`})}),(l.includes(`context`)||l.includes(`directory`))&&(0,Z.jsxs)(`button`,{type:`button`,disabled:he,onClick:()=>{E(`pins`),B(new Set),me(null)},className:K(`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2 text-xs`,T===`pins`?`border-primary`:`border-transparent text-muted-foreground`),children:[(0,Z.jsx)(R,{className:`h-3.5 w-3.5`}),`Pins`]}),l.map(e=>(0,Z.jsxs)(`button`,{type:`button`,disabled:he,onClick:()=>{E(e),B(new Set),me(null)},className:K(`flex shrink-0 items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,T===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[Ap[e],jp[e]]},e))]}),!z&&(0,Z.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:ce,onChange:e=>V(e.target.value),className:`w-full rounded-md border border-input bg-background py-2 pl-9 pr-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring`})]})}),z&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,Z.jsx)(`select`,{id:`relation-predicate`,value:O,onChange:e=>k(e.target.value),className:`min-w-0 flex-1 rounded-md border border-input bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-ring`,children:D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]}),(0,Z.jsx)(`div`,{className:`flex items-center gap-1`,children:[{dir:`out`,label:`This → picked`,hint:`the ${G===1?`document`:`documents`} you started from ${O} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${O} the ${G===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,Z.jsx)(`button`,{type:`button`,title:n,onClick:()=>j(e),className:K(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,A===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!z&&a&&se.size>0&&(0,Z.jsx)(`div`,{className:`flex shrink-0 flex-wrap gap-1.5 border-b bg-primary/[0.04] px-3 py-2`,children:Array.from(se).map(e=>(0,Z.jsxs)(`span`,{className:`inline-flex max-w-full items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>Se(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,Z.jsx)(Me,{className:`h-3 w-3`})})]},e))}),z&&(m??C)&&(0,Z.jsx)(zp,{workspaceName:m??C,treeTab:`context`,selectedDocIds:M,onToggleDoc:xe,excludeDocumentIds:g}),T===`pins`&&(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!P&&!L&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),L&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!L&&P?.length===0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),P?.filter(e=>e.resolvable!==!1&&l.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(le)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,Z.jsxs)(`button`,{type:`button`,"aria-pressed":F===t&&se.has(e.path),className:K(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,F===t&&se.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{F===t?Se(e.path):(I(t),B(new Set([e.path])))},children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(R,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,Z.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,Z.jsx)(`div`,{className:K(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(z||T===`pins`)&&`hidden`),children:ae?(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none text-sm shadow-elevation-1 hover:shadow`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,se.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:_e.guardClick(()=>Se(`/`)),title:`/`,...ve(`/`)?_e.handlers:{},children:[(0,Z.jsx)(Ge,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Z.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[pe===`/`&&(0,Z.jsx)(Ip,{busy:he,onConfirm:e=>ye(`/`,e),onCancel:()=>me(null)}),re?.children?.length?re.children.map(e=>(0,Z.jsx)(Lp,{node:e,parentPath:`/`,query:le,selected:se,onToggle:Se,onRowMenu:e=>{ve(e.path)&&fe(e)},createParent:pe,onCreateConfirm:ye,onCreateCancel:()=>me(null),creating:he},e.id||e.name)):pe===`/`?null:(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),_===`tree`&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:z?`${M.size} document${M.size===1?``:`s`} selected`:`${se.size} path${se.size===1?``:`s`} selected`}),(0,Z.jsx)(Y,{size:`sm`,onClick:W,disabled:!Ce||o||he,children:o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(xd,{className:`mr-1.5 h-3.5 w-3.5`}),z?`Relating…`:`Linking…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Gt,{className:`mr-1 h-3.5 w-3.5`}),z?`Relate`:d??`Link`]})})]}),de&&(0,Z.jsx)(Jf,{anchor:{x:de.clientX,y:de.clientY},onClose:()=>fe(null),items:[{id:`new-folder`,label:`New folder in ${de.path}`,icon:ut,run:()=>me(de.path)}]})]})}var Vp=`h-full w-[380px] max-w-[90vw] max-md:w-full`;function Hp({onClose:e,children:t}){return(0,Mf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-stretch justify-end bg-scrim animate-fade-in`,onClick:e,children:(0,Z.jsx)(`div`,{className:`h-full p-2 max-md:w-full max-md:p-1`,onClick:e=>e.stopPropagation(),children:t})}),window.document.body)}function Up(e){let t=2166136261;for(let e of localStorage.getItem(`authToken`)||``)t=Math.imul(t^e.charCodeAt(0),16777619);return`canvas:workspace-copy:${t>>>0}:${e}`}function Wp({workspaceId:e,ids:t,onClose:n}){let[r]=(0,X.useState)(()=>{try{return Up(e)}catch{return``}}),[i,a]=(0,X.useState)(()=>{try{let e=JSON.parse(localStorage.getItem(r)||`null`);return e&&Array.isArray(e.ids)&&e.target&&e.index<e.ids.length?e:null}catch{return null}}),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(``),u=(0,X.useRef)(!1),d=(0,X.useRef)(!1);(0,X.useEffect)(()=>(u.current=!1,()=>{u.current=!0}),[]);let f=e=>{try{e.index>=e.ids.length?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(e))}catch{}u.current||a(e)},p=async t=>{if(d.current)return;d.current=!0,s(!0),l(``);let n=t;f(n);try{for(;n.index<n.ids.length&&!u.current;){if(!navigator.onLine)throw Error(`Offline. Your copy is saved; resume when connected.`);await Ja(e,n.ids[n.index],{destination:n.target.workspaceName,context:n.paths,treeType:n.target.treeType,treeNameOrTreeId:n.target.treeName,operationId:`${n.id}:${n.index}`}),n={...n,index:n.index+1},f(n)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}catch(e){u.current||l(`Document ${n.ids[n.index]}: ${e instanceof Error?e.message:`Copy failed`}. Resume to retry.`)}finally{d.current=!1,u.current||s(!1)}},m=()=>{u.current=!0,n()},h=i!=null&&i.index>=i.ids.length;return(0,Z.jsx)(Hp,{onClose:m,children:i?(0,Z.jsxs)(`section`,{role:`dialog`,"aria-label":`Copy to workspace`,className:`${Vp} flex flex-col rounded-2xl border bg-card p-4 shadow-elevation-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,Z.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[i.target.workspaceName,`: `,i.paths.join(`, `)]}),(0,Z.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[i.index,` of `,i.ids.length,` copied`,h?`.`:o?`…`:` — paused.`]}),c&&(0,Z.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:c}),(0,Z.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:`Files go to workspace:data. Destination rules handle storage placement. Relationships and sharing permissions are not copied. Source documents stay unchanged.`}),!h&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Closing lets the current item finish and pauses the rest. Reopen Copy to workspace to resume, including after reconnecting.`}),(0,Z.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!h&&!o&&(0,Z.jsx)(Y,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(r)}catch{}a(null),l(``)},children:`Discard remaining`}),!h&&!o&&(0,Z.jsx)(Y,{onClick:()=>void p(i),children:`Resume copy`}),(0,Z.jsx)(Y,{variant:h?`default`:`outline`,onClick:m,children:h?`Done`:o?`Pause & close`:`Close`})]})]}):(0,Z.jsx)(Bp,{title:`Copy to workspace…`,confirmLabel:`Copy documents`,excludeWorkspace:e,documentCount:t.length,sizeClassName:Vp,onClose:m,onConfirm:(e,n)=>p({ids:t,target:n,paths:e,index:0,id:crypto.randomUUID()})})})}function Gp({tags:e,onChange:t,placeholder:n=`Add tag, press Enter`,suggestions:r=[]}){let[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),c=i.trim().toLowerCase(),l=(c?r.filter(t=>t.toLowerCase().includes(c)&&!e.includes(t)):o?r.filter(t=>!e.includes(t)):[]).slice(0,8),u=()=>{let n=i.trim();n&&!e.includes(n)&&t([...e,n]),a(``)};return(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent px-2 py-1.5 focus-within:ring-1 focus-within:ring-ring`,children:[e.map(n=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs`,children:[n,(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e.filter(e=>e!==n)),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${n}`,children:(0,Z.jsx)(Me,{className:`h-3 w-3`})})]},n)),(0,Z.jsxs)(`div`,{className:`relative flex-1 min-w-[8ch]`,children:[(0,Z.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:n=>{n.key===`Enter`||n.key===`,`?(n.preventDefault(),u()):n.key===`Backspace`&&!i&&e.length&&t(e.slice(0,-1))},onFocus:()=>s(!0),onBlur:()=>{setTimeout(u,150),s(!1)},placeholder:e.length?``:n,className:`w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),l.length>0&&(0,Z.jsx)(`div`,{className:`absolute left-0 top-full z-50 mt-1 max-h-48 w-56 overflow-auto rounded-md border bg-popover p-1 text-sm shadow-elevation-2`,children:l.map(n=>(0,Z.jsx)(`button`,{type:`button`,onMouseDown:r=>{r.preventDefault(),e.includes(n)||t([...e,n]),a(``)},className:`block w-full rounded px-2 py-1 text-left hover:bg-accent`,children:n},n))})]})]})}function Kp(e){let t=new Set;for(let n of e){let e=n.trim();e&&t.add(`tag/${e}`)}return Array.from(t)}function qp(e){return(e||[]).filter(e=>e.startsWith(`tag/`)).map(e=>e.slice(4))}function Jp(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...Kp(e.data?.tags??[]),...Kp(t)])]}:{},...n?{geo:n}:{}}}function Yp(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:Jp(e,t,n),...r===void 0?{}:{comment:r.trim()}}}var Xp=n(Eo(),1),Zp=`#8b5cf6`,Qp=`https://nominatim.openstreetmap.org`,$p=700,em=e=>Math.round(e*1e6)/1e6;function tm(){let e=`<div style="display:flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:9999px 9999px 9999px 2px;transform:rotate(-45deg);background:${Zp};border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.45)"><div style="width:8px;height:8px;border-radius:9999px;background:#fff"></div></div>`;return Xp.default.divIcon({html:e,className:`canvas-map-pick`,iconSize:[28,28],iconAnchor:[14,28]})}function nm({initial:e,onPick:t,onClose:n}){let r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.useRef)(null),o=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>o.current?.abort(),[]);let[s,c]=(0,X.useState)(e?{lat:e.lat,lon:e.lon}:null),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)([]),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(!1),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1);(0,X.useEffect)(()=>{let e=requestAnimationFrame(()=>S(!0));return()=>cancelAnimationFrame(e)},[]),Ff(n);let C=(0,X.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let o=Xp.default.latLng(e,t);a.current?a.current.setLatLng(o):(a.current=Xp.default.marker(o,{icon:tm(),draggable:!0,autoPan:!0}).addTo(r),a.current.on(`dragend`,()=>{let e=a.current.getLatLng();c({lat:em(e.lat),lon:em(e.lng)})})),c({lat:em(e),lon:em(t),...n?{label:n}:{}})},[]);(0,X.useEffect)(()=>{let t=r.current;if(!t||i.current)return;let n=Xp.default.map(t,{center:e?[e.lat,e.lon]:[20,0],zoom:e?13:2,worldCopyJump:!0,zoomControl:!0});Xp.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(n),i.current=n,e&&C(e.lat,e.lon),n.on(`click`,e=>C(e.latlng.lat,e.latlng.lng));let o=new ResizeObserver(()=>n.invalidateSize());o.observe(t);let s=setTimeout(()=>n.invalidateSize(),260);return()=>{clearTimeout(s),o.disconnect(),n.remove(),i.current=null,a.current=null}},[]),(0,X.useEffect)(()=>{if(!s||s.label)return;let{lat:e,lon:t}=s,n=new AbortController,r=setTimeout(()=>{v(!0),fetch(`${Qp}/reverse?format=jsonv2&zoom=16&lat=${e}&lon=${t}`,{signal:n.signal,headers:{Accept:`application/json`}}).then(e=>e.ok?e.json():null).then(n=>{let r=n?.display_name;typeof r==`string`&&r&&c(n=>n&&n.lat===e&&n.lon===t?{...n,label:r}:n)}).catch(()=>{}).finally(()=>v(!1))},$p);return()=>{clearTimeout(r),n.abort()}},[s]);let w=(0,X.useCallback)(async()=>{let e=l.trim();if(e.length<2)return;o.current?.abort();let t=new AbortController;o.current=t;let n=!1,r=window.setTimeout(()=>{n=!0,t.abort()},12e3);m(!0),f([]),g(null);try{let n=await fetch(`${Qp}/search?format=jsonv2&limit=6&q=${encodeURIComponent(e)}`,{signal:t.signal,headers:{Accept:`application/json`}});if(n.status===429)throw Error(`Place search is busy. Wait a moment and try again, or click the map`);if(!n.ok)throw Error(`Place search is unavailable (${n.status}). Try again, or click the map`);let r=await n.json();if(!Array.isArray(r))throw Error(`Place search returned an invalid response. Try again, or click the map`);if(t.signal.aborted||o.current!==t)return;f(r),r.length||g(`No match. Try a different spelling, or just click the map`)}catch(e){if(o.current!==t||t.signal.aborted&&!n)return;g(n?`Place search timed out. Try again, or click the map`:e instanceof TypeError?`Could not reach place search. Check your connection, or click the map`:e instanceof Error?e.message:`Search is unavailable right now. Click the map to place a pin`)}finally{window.clearTimeout(r),o.current===t&&(!t.signal.aborted||n)&&m(!1)}},[l]),T=(0,X.useCallback)(()=>{if(!navigator.geolocation){g(`This browser has no geolocation`);return}b(!0),g(null),navigator.geolocation.getCurrentPosition(e=>{b(!1),i.current?.setView([e.coords.latitude,e.coords.longitude],16),C(e.coords.latitude,e.coords.longitude)},()=>{b(!1),g(`Could not read your location. Search or click the map instead`)},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})},[C]),E=(0,X.useCallback)(e=>{let t=i.current,n=Number(e.lat),r=Number(e.lon);if(!t||!Number.isFinite(n)||!Number.isFinite(r))return;let a=e.boundingbox?.map(Number);a&&a.length===4&&a.every(Number.isFinite)?t.fitBounds(Xp.default.latLngBounds([a[0],a[2]],[a[1],a[3]]),{maxZoom:16}):t.setView([n,r],15),C(n,r,e.display_name),f([])},[C]);return(0,Mf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:K(`fixed inset-0 z-[60] bg-black/40 transition-opacity duration-200`,x?`opacity-100`:`opacity-0`),onClick:n}),(0,Z.jsxs)(`div`,{role:`dialog`,"aria-label":`Pick a location on the map`,className:K(`fixed inset-y-0 right-0 z-[61] flex w-[min(560px,100vw)] flex-col bg-background shadow-elevation-4 transition-transform duration-200 ease-out`,x?`translate-x-0`:`translate-x-full`),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(yt,{className:`h-4 w-4 text-info`}),`Custom geotag`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,"aria-label":`Close map`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`relative z-10 shrink-0 border-b px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:l,autoFocus:!0,onChange:e=>{o.current?.abort(),o.current=null,m(!1),f([]),u(e.target.value),g(null)},"aria-label":`Search for a place or address`,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),w())},placeholder:`Search a place, e.g. Slavkovský štít`,spellCheck:!1,className:`h-8 w-full rounded-md border border-input bg-transparent pl-7 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:T,disabled:y,title:`Use my current location`,"aria-label":`Use my current location`,className:`inline-flex h-8 w-8 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50`,children:y?(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(Jn,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:w,disabled:p||l.trim().length<2,className:`inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs text-primary-foreground disabled:opacity-50`,children:[p?(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(pr,{className:`h-3.5 w-3.5`}),`Search`]})]}),h&&(0,Z.jsx)(`p`,{role:`status`,className:`mt-1 text-xs text-warning`,children:h}),d.length>0&&(0,Z.jsx)(`div`,{className:`absolute inset-x-3 top-full z-10 mt-1 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-elevation-4`,children:d.map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>E(e),className:`block w-full border-b border-border/60 px-3 py-2 text-left text-xs last:border-0 hover:bg-muted`,children:e.display_name},`${e.lat},${e.lon},${e.display_name}`))})]}),(0,Z.jsxs)(`div`,{className:`relative isolate z-0 min-h-0 flex-1`,children:[(0,Z.jsx)(`div`,{ref:r,className:`h-full w-full`}),!s&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-3 z-[1000] flex justify-center`,children:(0,Z.jsx)(`span`,{className:`rounded-full bg-background/90 px-3 py-1 text-xs text-muted-foreground shadow-elevation-2`,children:`Click the map to drop a pin, or drag it to fine-tune`})})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 text-xs`,children:s?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 tabular-nums text-foreground`,children:[(0,Z.jsx)(cr,{className:`h-3 w-3 shrink-0 text-muted-foreground`}),s.lat.toFixed(5),`, `,s.lon.toFixed(5),_&&(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin text-muted-foreground`})]}),s.label&&(0,Z.jsx)(`div`,{className:`truncate text-muted-foreground`,children:s.label})]}):(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`No point selected`})}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`rounded-md border border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:`Cancel`}),(0,Z.jsxs)(`button`,{type:`button`,disabled:!s,onClick:()=>{s&&(t(s),n())},className:`inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-50`,children:[(0,Z.jsx)($e,{className:`h-3.5 w-3.5`}),`Use this point`]})]})]})]})]}),document.body)}var rm={exif:`from the photo's EXIF`,device:`from the device at capture`,manual:`placed by hand`};function im(e){let t=`${e.lat.toFixed(5)}, ${e.lon.toFixed(5)}`,n=e.source?rm[e.source]:null;return[t,e.accuracy==null?null:`±${e.accuracy} m`,n].filter(Boolean).join(` · `)}function am({value:e,onChange:t,idPrefix:n=`edit-geo`}){let[r,i]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${n}-action`,children:`Location`}),(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 text-xs`,children:[(0,Z.jsx)(yt,{className:e?`h-4 w-4 shrink-0 text-info`:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:e?`truncate tabular-nums`:`truncate text-muted-foreground`,children:e?im(e):`No location on this document`})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.jsxs)(`button`,{id:`${n}-action`,type:`button`,onClick:()=>i(!0),className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(en,{className:`h-3.5 w-3.5`}),e?`Move pin`:`Set on map`]}),e&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(null),"aria-label":`Remove location`,title:`Remove location`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),r&&(0,Z.jsx)(nm,{initial:e,onPick:e=>t({lat:e.lat,lon:e.lon,source:`manual`}),onClose:()=>i(!1)})]})}function om({workspaceId:e,documentIds:t,onClose:n}){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(`keep`),[l,u]=(0,X.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,X.useState)(t),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(``);return Ff(n,!m),(0,Mf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-scrim p-4`,children:(0,Z.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`bulk-edit-title`,className:`max-h-viewport-modal overflow-y-auto w-full max-w-md space-y-4 rounded-xl border bg-background p-5 shadow-elevation-4`,children:[(0,Z.jsxs)(`h2`,{id:`bulk-edit-title`,className:`font-semibold`,children:[`Bulk Edit · `,f.length,` documents`]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Add tags to all selected documents. Choosing a location replaces their existing geotags; leaving it unset keeps them.`}),(0,Z.jsxs)(`fieldset`,{disabled:m,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:`Add tags`}),(0,Z.jsx)(Gp,{tags:r,onChange:i,suggestions:[]})]}),(0,Z.jsx)(am,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,Z.jsxs)(`select`,{id:`bulk-comment-mode`,value:s,onChange:e=>c(e.target.value),className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm`,children:[(0,Z.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,Z.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,Z.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,Z.jsx)(`textarea`,{id:`bulk-comment`,rows:3,value:l,onChange:e=>u(e.target.value),placeholder:`Comment for all selected documents…`,className:`w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,Z.jsx)(Y,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await qr(e,n);await Da(e,Yp(t,r,a,s===`keep`?void 0:s===`clear`?``:l))}catch{t.push(n)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),h(!1),t.length?(p(t),_(`${f.length-t.length} saved; ${t.length} could not be updated. Retry applies only to those documents.`)):n()},disabled:m||!d,children:m?`Saving…`:g?`Retry failed`:`Apply to all`})]})]})}),window.document.body)}var sm=[{mode:`copy`,label:`Copy to`,icon:(0,Z.jsx)(Ve,{className:`h-3.5 w-3.5`})},{mode:`move`,label:`Move to`,icon:(0,Z.jsx)(qn,{className:`h-3.5 w-3.5`})},{mode:`delete`,label:`Delete from`,icon:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}],cm=[{value:`rename`,label:`Rename mine (file-1.ext)`},{value:`overwrite`,label:`Overwrite the existing file`},{value:`error`,label:`Skip the document`}],lm=`h-9 w-full rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`;function um(e){return e.driver===`cacache`?wt:e.config?.remote===!0?G:hr}function dm({workspaceId:e,documentCount:t,initialMode:n=`copy`,defaultFilename:r=``,onConfirm:i,onClose:a,saving:o=!1,sizeClassName:s}){let{showErrorToast:c}=Wr(),[l,u]=(0,X.useState)(!1);Ff(a,!o&&!l);let[d,f]=(0,X.useState)(n),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(``),[C,w]=(0,X.useState)(r),[T,E]=(0,X.useState)(`rename`);(0,X.useEffect)(()=>{let t=!1;return Ta(e).then(e=>{t||m(e.filter(e=>e.kind===`storage`))}).catch(e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let D=d===`move`,O=e=>d===`delete`?null:e.enabled===!1?`disabled`:e.config?.readOnly===!0?`read-only`:e.config?.supported===!1?`unsupported`:null,k=(0,X.useMemo)(()=>(p||[]).filter(e=>!O(e)).map(e=>e.address),[p,d]),A=e=>{f(e),v(t=>{let n=(p||[]).filter(t=>e===`delete`||t.enabled!==!1&&t.config?.readOnly!==!0&&t.config?.supported!==!1).map(e=>e.address),r=[...t].filter(e=>n.includes(e));return new Set(e===`move`?r.slice(0,1):r)})},j=e=>{v(t=>{if(D)return t.has(e)?new Set:new Set([e]);let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},M=(0,X.useMemo)(()=>(p||[]).filter(e=>_.has(e.address)&&Ia(e)),[p,_]),N=d!==`delete`&&M.length>0,P=e=>{let t=fa(e,p||[]),n=t&&p?.find(e=>e.address===t.address);return!!n&&!O(n)&&d!==`delete`&&!o},ee=async(t,n)=>{let r=fa(t,p||[]);if(!r||!P(t))throw Error(`Choose a writable file backend folder`);await oa(e,r.driver,r.address,[[r.key,n].filter(Boolean).join(`/`)])},F=e=>{u(!1);let t=co(e[0]||``,p||[]),n=t?(p||[]).find(e=>e.address===t.address):null;if(!t||!n){c(`Pick a folder inside a storage backend`);return}if(O(n)){c(`${n.address} is ${O(n)}`);return}if(!Ia(n)){c(`${n.address} does not keep folders — objects are stored by content`);return}S(t.key),v(e=>D?new Set([t.address]):new Set([...e,t.address]))},I=async()=>{_.size===0||o||await i([..._],d,{keepDocument:y,folder:N?x.trim():``,filename:N&&t===1?C.trim():``,onConflict:T})},L=t,R=L===1?``:`s`,te=d===`delete`?`Delete ${L} document${R} from…`:`${d===`move`?`Move`:`Copy`} ${L} document${R} to…`,ne=d===`delete`?`Delete from`:d===`move`?`Move to`:`Copy to`,z=_.size===0?ne.split(` `)[0]:`${ne} ${_.size} backend${_.size===1?``:`s`}`;return(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,s||`max-h-viewport-card w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(hr,{className:`h-4 w-4`}),te]}),(0,Z.jsx)(`button`,{type:`button`,onClick:a,disabled:o,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:sm.map(({mode:e,label:t,icon:n})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>A(e),disabled:o,className:K(`flex items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors disabled:opacity-50`,d===e?e===`delete`?`border-destructive text-destructive`:`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[n,t]},e))}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:[h&&(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-destructive`,children:h}),!p&&!h&&(0,Z.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading backends…`}),p?.length===0&&(0,Z.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`No storage backends configured.`}),p?.map(e=>{let t=um(e),n=O(e),r=_.has(e.address),i=e.config?.remote===!0;return(0,Z.jsxs)(`div`,{onClick:()=>!n&&!o&&j(e.address),className:K(`group relative flex min-h-10 items-center gap-2 rounded-md px-3 py-2 text-sm shadow-elevation-1 transition-all select-none`,`before:absolute before:left-0 before:top-0 before:bottom-0 before:w-1.5 before:transition-colors`,n?`cursor-not-allowed bg-muted/40 opacity-60 before:bg-transparent`:`cursor-pointer hover:shadow`,!n&&r?d===`delete`?`bg-destructive/[0.08] hover:bg-destructive/[0.12] before:bg-destructive`:`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:n?``:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),title:e.address,children:[(0,Z.jsx)(`input`,{type:D?`radio`:`checkbox`,checked:r,disabled:!!n||o,onChange:()=>j(e.address),onClick:e=>e.stopPropagation(),className:`h-4 w-4 shrink-0 accent-primary`,"aria-label":e.address}),(0,Z.jsx)(t,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.config?.label||e.address}),(0,Z.jsxs)(`span`,{className:`block truncate font-mono text-[10px] text-muted-foreground`,children:[e.driver,` · `,e.address]})]}),i&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-info-subtle px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,title:`Network mount${e.config?.transport?` (${e.config.transport})`:``} — transfers cross the network`,children:e.config?.transport||`remote`}),n&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:n})]},`${e.driver}/${e.address}`)}),d===`delete`&&(0,Z.jsxs)(`label`,{className:`mt-3 flex cursor-pointer items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:y,onChange:e=>b(e.target.checked),className:`mt-0.5 h-3.5 w-3.5 accent-destructive`}),(0,Z.jsxs)(`span`,{children:[`Keep the index entry when its `,(0,Z.jsx)(`strong`,{children:`last`}),` copy is deleted.`,(0,Z.jsx)(`span`,{className:`block text-muted-foreground`,children:`Otherwise the document is removed from the index once no locations remain.`})]})]}),N&&(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-md border px-3 py-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs font-medium`,children:[`Destination on `,M.map(e=>e.config?.label||e.address).join(`, `)]}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-folder`,className:`text-[11px] text-muted-foreground`,children:`Folder (relative to the backend root)`}),(0,Z.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,Z.jsx)(q,{id:`backend-transfer-folder`,value:x,onChange:e=>S(e.target.value),placeholder:`/`,disabled:o,className:`h-9 font-mono text-xs`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`icon`,className:`h-9 w-9 shrink-0`,onClick:()=>u(!0),disabled:o,"aria-label":`Browse backend folders`,title:`Browse…`,children:(0,Z.jsx)(Mn,{className:`h-4 w-4`})})]})]}),t===1?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-filename`,className:`text-[11px] text-muted-foreground`,children:`File name`}),(0,Z.jsx)(q,{id:`backend-transfer-filename`,value:C,onChange:e=>w(e.target.value),placeholder:r||`keeps the document's own name`,disabled:o,className:`h-9 font-mono text-xs`})]}):(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Each document keeps its own file name and extension.`}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`label`,{htmlFor:`backend-transfer-conflict`,className:`text-[11px] text-muted-foreground`,children:`If a different file already has that name`}),(0,Z.jsx)(`select`,{id:`backend-transfer-conflict`,className:lm,value:T,onChange:e=>E(e.target.value),disabled:o,children:cm.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),d===`move`&&k.length>0&&(0,Z.jsx)(`p`,{className:`px-1 pt-2 text-[11px] text-muted-foreground`,children:`The source copy is released only once the destination write is durable.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-t px-4 py-3`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[_.size,` backend`,_.size===1?``:`s`,` selected`]}),(0,Z.jsx)(Y,{size:`sm`,variant:d===`delete`?`destructive`:`default`,onClick:I,disabled:_.size===0||o,children:o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(xd,{className:`mr-1.5 h-3.5 w-3.5`}),`Working…`]}):(0,Z.jsxs)(Z.Fragment,{children:[d===`delete`?(0,Z.jsx)(lt,{className:`mr-1 h-3.5 w-3.5`}):d===`move`?(0,Z.jsx)(qn,{className:`mr-1 h-3.5 w-3.5`}):(0,Z.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),z]})})]}),d===`delete`&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 border-t bg-destructive/5 px-4 py-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,Z.jsx)(`span`,{children:`Deletes the file data from the selected backends. Copies on other backends are untouched.`})]}),l&&(0,Z.jsx)(Hp,{onClose:()=>u(!1),children:(0,Z.jsx)(Bp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`backends`],fixedWorkspaceName:e,title:`Pick a destination folder…`,confirmLabel:`Use folder`,backendFolderCreation:{canCreate:P,create:ee},onConfirm:F,onClose:()=>u(!1)})})]})}function fm({onClose:e,onConfirm:t,fixedWorkspaceName:n,saving:r=!1,sizeClassName:i}){let[a,o]=(0,X.useState)(n?`browse`:`workspace`),[s,c]=(0,X.useState)([]),[l,u]=(0,X.useState)(!n),[d,f]=(0,X.useState)(n??null),[p,m]=(0,X.useState)(`context`),[h,g]=(0,X.useState)(new Set),[_,v]=(0,X.useState)(n);return n!==_&&(v(n),n||u(!0)),(0,X.useEffect)(()=>{n||Xr().then(c).catch(()=>c([])).finally(()=>u(!1))},[n]),(0,Z.jsxs)(`div`,{className:K(`flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,i||`h-viewport-card max-h-full w-[min(420px,90vw)] max-md:h-full max-md:w-full max-md:shadow-elevation-5`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Ot,{className:`h-4 w-4`}),a===`workspace`?`Add existing documents…`:`Pick documents…`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:e,disabled:r,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Z.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-200`,style:{transform:a===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Z.jsx)(Rp,{workspaces:s,loading:l,onPick:e=>{f(e),g(new Set),o(`browse`)}})}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:[!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>o(`workspace`),className:`mr-1 rounded p-1.5 text-muted-foreground hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Back to workspaces`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4 rotate-180`})}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{m(e),g(new Set)},className:K(`flex items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,p===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[Ap[e],jp[e]]},e))]}),d&&(0,Z.jsx)(zp,{workspaceName:d,treeTab:p,onTreeTabChange:m,selectedDocIds:h,onToggleDoc:e=>{g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},onNavigate:()=>g(new Set)})]})]})}),a===`browse`&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[h.size,` document`,h.size===1?``:`s`,` selected`]}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{!d||h.size===0||r||await t(Array.from(h),{workspaceName:d,treeName:p===`directory`?`directory`:ao,treeType:p})},disabled:h.size===0||r,children:r?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(xd,{className:`mr-1.5 h-3.5 w-3.5`}),`Adding…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Ot,{className:`mr-1 h-3.5 w-3.5`}),`Add`]})})]})]})}var pm=(0,X.createContext)(null),mm={entry:null,open:()=>{},close:()=>{}};function hm(){return(0,X.useContext)(pm)??mm}var gm=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`div`,{className:`relative w-full overflow-auto`,children:(0,Z.jsx)(`table`,{ref:n,className:K(`w-full caption-bottom text-sm`,e),...t})}));gm.displayName=`Table`;var _m=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`thead`,{ref:n,className:K(`[&_tr]:border-b`,e),...t}));_m.displayName=`TableHeader`;var vm=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tbody`,{ref:n,className:K(`[&_tr:last-child]:border-0`,e),...t}));vm.displayName=`TableBody`;var ym=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tfoot`,{ref:n,className:K(`border-t bg-muted/50 font-medium [&>tr]:last:border-b-0`,e),...t}));ym.displayName=`TableFooter`;var bm=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`tr`,{ref:n,className:K(`border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted`,e),...t}));bm.displayName=`TableRow`;var xm=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`th`,{ref:n,className:K(`h-12 px-2 md:px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0`,e),...t}));xm.displayName=`TableHead`;var Sm=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`td`,{ref:n,className:K(`p-2 md:p-4 align-middle [&:has([role=checkbox])]:pr-0`,e),...t}));Sm.displayName=`TableCell`;var Cm=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(`caption`,{ref:n,className:K(`mt-4 text-sm text-muted-foreground`,e),...t}));Cm.displayName=`TableCaption`;var wm=({label:e,sortKey:t,sort:n,onSort:r,className:i})=>{let a=n.key===t;return(0,Z.jsx)(xm,{"aria-sort":a?n.dir===`asc`?`ascending`:`descending`:`none`,className:K(`cursor-pointer select-none hover:text-foreground transition-colors`,i),onClick:()=>r(t),children:(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,a?n.dir===`asc`?(0,Z.jsx)(Sn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Dn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Pe,{className:`h-3.5 w-3.5 opacity-40`})]})})};wm.displayName=`SortableTableHead`;function Tm(e,t,n={key:null,dir:`asc`}){let[r,i]=X.useState(n);return{sorted:X.useMemo(()=>{let n=r.key?t[r.key]:null;if(!n)return e;let i=r.dir===`asc`?1:-1;return[...e].sort((e,t)=>{let r=n(e)??``,a=n(t)??``;return typeof r==`number`&&typeof a==`number`?(r-a)*i:String(r).localeCompare(String(a),void 0,{numeric:!0})*i})},[e,r,t]),sort:r,toggleSort:X.useCallback(e=>{i(t=>t.key===e?{key:e,dir:t.dir===`asc`?`desc`:`asc`}:{key:e,dir:`asc`})},[])}}var Em=`workspace:relations:refresh`;function Dm(){window.dispatchEvent(new CustomEvent(Em))}var Om=(0,X.createContext)(null),km=`canvas:documentOpenMode`;function Am(){try{return localStorage.getItem(km)===`modal`?`modal`:`side`}catch{return`side`}}var jm=Am(),Mm=new Set;function Nm(){return jm}function Pm(e){try{localStorage.setItem(km,e)}catch{}jm=e;for(let e of Mm)e()}function Fm(e){Mm.add(e);let t=t=>{(t.key===km||t.key===null)&&(jm=Am(),e())};return window.addEventListener(`storage`,t),()=>{Mm.delete(e),window.removeEventListener(`storage`,t)}}function Im(){return(0,X.useSyncExternalStore)(Fm,Nm,()=>`side`)}function Lm({tabs:e,active:t,onChange:n,className:r=``,iconOnly:i=!1}){return(0,Z.jsx)(`div`,{className:`flex gap-1 border-b overflow-x-auto ${r}`,children:e.map(e=>{let r=e.icon;return(0,Z.jsxs)(`button`,{onClick:()=>n(e.id),title:e.label,className:`${i&&r?`px-3`:`px-4`} py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap inline-flex items-center gap-1.5 ${t===e.id?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:[r&&(0,Z.jsx)(r,{className:`h-3.5 w-3.5`}),(!i||!r)&&e.label]},e.id)})})}var Rm=1,zm=8,Bm=320,Vm=28,Hm=2.5,Um={scale:1,x:0,y:0};function Wm({src:e,alt:t,className:n=``,onZoomChange:r}){let i=(0,X.useRef)(null),a=(0,X.useRef)(null),[o,s]=(0,X.useState)(Um),c=(0,X.useRef)(new Map),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(!1),f=(0,X.useRef)(null),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(e);h!==e&&(g(e),s(Um)),(0,X.useEffect)(()=>{r?.(o.scale>1.001)},[o.scale,r]);let _=(0,X.useCallback)(e=>{let t=i.current,n=a.current;if(!t||!n)return e;let r=Math.min(zm,Math.max(Rm,e.scale)),o=Math.max(0,(n.offsetWidth*r-t.clientWidth)/2),s=Math.max(0,(n.offsetHeight*r-t.clientHeight)/2);return{scale:r,x:Math.min(o,Math.max(-o,e.x)),y:Math.min(s,Math.max(-s,e.y))}},[]),v=(0,X.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let a=r.getBoundingClientRect(),o=t-a.left-a.width/2,c=n-a.top-a.height/2;s(t=>{let n=e/t.scale;return _({scale:e,x:o-(o-t.x)*n,y:c-(c-t.y)*n})})},[_]),y=(0,X.useCallback)(()=>{let e=i.current,t=a.current;if(!e||!t||!t.offsetWidth||!t.offsetHeight)return Hm;let n=Math.max(e.clientWidth/t.offsetWidth,e.clientHeight/t.offsetHeight),r=Math.max(t.naturalWidth/t.offsetWidth,t.naturalHeight/t.offsetHeight)||zm;return Math.min(zm,Math.max(Hm,Math.min(Math.max(n,Hm),r)))},[]),b=(0,X.useCallback)((e,t)=>{o.scale>1.001?s(Um):v(y(),e,t)},[o.scale,v,y]),x=e=>{if(c.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),d.current=!1,c.current.size===2){let[e,t]=[...c.current.values()];l.current={dist:Math.hypot(e.x-t.x,e.y-t.y),scale:o.scale,cx:(e.x+t.x)/2,cy:(e.y+t.y)/2}}e.currentTarget.setPointerCapture(e.pointerId)},S=e=>{let t=c.current.get(e.pointerId);if(!t)return;if(c.current.set(e.pointerId,{x:e.clientX,y:e.clientY}),c.current.size>=2&&l.current){let[e,t]=[...c.current.values()],n=Math.hypot(e.x-t.x,e.y-t.y);l.current.dist>0&&(d.current=!0,m(!0),v(l.current.scale*(n/l.current.dist),l.current.cx,l.current.cy));return}if(o.scale<=1.001)return;let n=e.clientX-t.x,r=e.clientY-t.y;(Math.abs(n)>1||Math.abs(r)>1)&&(d.current=!0,m(!0)),s(e=>_({...e,x:e.x+n,y:e.y+r}))},C=e=>{if(c.current.delete(e.pointerId),c.current.size<2&&(l.current=null),c.current.size===0&&m(!1),d.current){u.current=null;return}let t=e.timeStamp,n=u.current;if(n&&t-n.t<Bm&&Math.hypot(e.clientX-n.x,e.clientY-n.y)<Vm){u.current=null,f.current=t,b(e.clientX,e.clientY);return}u.current={t,x:e.clientX,y:e.clientY}},w=e=>{e.preventDefault();let t=o.scale*(e.deltaY<0?1.15:1/1.15);t<=Rm?s(Um):v(Math.min(zm,t),e.clientX,e.clientY)},T=o.scale>1.001;return(0,Z.jsx)(`div`,{ref:i,className:`relative flex h-full w-full items-center justify-center overflow-hidden`,style:{touchAction:`none`,cursor:T?`grab`:`zoom-in`},onPointerDown:x,onPointerMove:S,onPointerUp:C,onPointerCancel:e=>{c.current.delete(e.pointerId),l.current=null,u.current=null,d.current=!0,c.current.size===0&&m(!1)},onWheel:w,onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),!(f.current!==null&&e.timeStamp-f.current<Bm)&&b(e.clientX,e.clientY)},children:(0,Z.jsx)(`img`,{ref:a,src:e,alt:t,draggable:!1,className:n,style:{transform:`translate3d(${o.x}px, ${o.y}px, 0) scale(${o.scale})`,transformOrigin:`center center`,transition:p?`none`:`transform 160ms ease-out`,willChange:`transform`}})})}var Gm=`(max-width: 767px)`,Km=new Map;function qm(e){let t=Km.get(e);if(!t){let n=()=>typeof window<`u`&&typeof window.matchMedia==`function`;t={subscribe:t=>{if(!n())return()=>{};let r=window.matchMedia(e);return r.addEventListener(`change`,t),()=>r.removeEventListener(`change`,t)},getSnapshot:()=>n()?window.matchMedia(e).matches:!1},Km.set(e,t)}return t}function Jm(){let e=qm(Gm);return(0,X.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>!1)}function Ym(){return Xm(`(max-width: 1023px)`)}function Xm(e){let t=qm(e);return(0,X.useSyncExternalStore)(t.subscribe,t.getSnapshot,()=>!1)}function Zm(){return!/android|iphone|ipad|mobile/i.test(navigator.userAgent)&&navigator.pdfViewerEnabled!==!1}var Qm=40,$m=1600;function eh({blob:e,filename:t}){let n=(0,X.useRef)(null),[r,i]=(0,X.useState)({error:null,pages:0,truncated:!1});return(0,X.useEffect)(()=>{let r=n.current;if(!r)return;let a=!1,o=null;return(async()=>{let n=await m(()=>import(`./pdf-Ciz5_WNq.js`),__vite__mapDeps([0,1])),s=(await m(async()=>{let{default:e}=await import(`./pdf.worker.min-C8Ts8bNu.js`);return{default:e}},[])).default;n.GlobalWorkerOptions.workerSrc=s;let c=await e.arrayBuffer();if(a)return;let l=n.getDocument({data:c});o=()=>{l.destroy()};let u=await l.promise;if(a)return;let d=Math.min(u.numPages,Qm),f=r.clientWidth||600,p=window.devicePixelRatio||1;for(let e=1;e<=d;e++){if(a)return;let n=await u.getPage(e),o=n.getViewport({scale:1}),s=Math.min(f*p,$m*p)/o.width,c=n.getViewport({scale:s}),l=document.createElement(`canvas`);if(l.width=c.width,l.height=c.height,l.style.width=`100%`,l.style.height=`auto`,l.className=`rounded border bg-white`,l.setAttribute(`aria-label`,`${t}, page ${e}`),await n.render({canvas:l,viewport:c}).promise,n.cleanup(),a)return;r.appendChild(l),i({error:null,pages:e,truncated:u.numPages>Qm})}})().catch(e=>{a||i(t=>({...t,error:e instanceof Error?e.message:String(e)}))}),()=>{a=!0,o?.(),r.replaceChildren()}},[e,t]),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[r.error&&(0,Z.jsxs)(`p`,{className:`text-sm text-destructive`,children:[`Could not render PDF: `,r.error]}),!r.error&&r.pages===0&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering PDF…`}),(0,Z.jsx)(`div`,{ref:n,className:`space-y-2`}),r.truncated&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,Qm,` pages. Download the file for the full document.`]})]})}function th({blob:e,blobUrl:t,filename:n,className:r=``}){let i=(0,X.useMemo)(()=>e&&e.type!==`application/pdf`?URL.createObjectURL(e.slice(0,e.size,`application/pdf`)):null,[e]);return(0,X.useEffect)(()=>()=>{i&&URL.revokeObjectURL(i)},[i]),Zm()||!e?(0,Z.jsx)(`div`,{className:`min-h-[300px] ${r}`,children:(0,Z.jsx)(`iframe`,{src:i??t,className:`h-full min-h-[300px] w-full rounded border`,title:n})}):(0,Z.jsx)(`div`,{className:`max-h-viewport-pane overflow-y-auto ${r}`,children:(0,Z.jsx)(eh,{blob:e,filename:n})})}function nh(e,t,n=256,{enabled:r=!0,blobFallback:i=!0,version:a=null}={}){let{isPublic:o,fetchBlob:s,fetchThumbnail:c}=Mo(e),l=`${o?`pub`:`ws`}:${e}:${t}:${n}:${r}:${a??``}`,[u,d]=(0,X.useState)({blobUrl:null,error:null,loading:r}),[f,p]=(0,X.useState)(l);return l!==f&&(p(l),d({blobUrl:null,error:null,loading:r})),(0,X.useEffect)(()=>{if(!r)return;let e=!1,o=null;return c(t,n,a).catch(e=>{if(!i)throw e;return s(t)}).then(({blob:t})=>{e||(o=URL.createObjectURL(t),d({blobUrl:o,error:null,loading:!1}))}).catch(t=>{e||d({blobUrl:null,error:String(t instanceof Error?t.message:t),loading:!1})}),()=>{e=!0,o&&URL.revokeObjectURL(o)}},[l]),u}function rh({workspaceId:e,document:t}){let{download:n}=Mo(e),[r,i]=(0,X.useState)(!1),a=ri(t)||`document-${t.id}`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{i(!0);try{await n(t.id,a)}finally{i(!1)}},disabled:r,className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,Z.jsx)(er,{className:`h-3.5 w-3.5`}),r?`Preparing…`:`Download`]})}var ih=1600;function ah({error:e,loading:t,children:n}){return e?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:e}):t?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading preview...`}):(0,Z.jsx)(Z.Fragment,{children:n})}function oh({workspaceId:e,document:t,className:n=``}){let r=(0,X.useContext)(Om),i=Jm(),a=Xm(`(pointer: coarse)`),{blobUrl:o,error:s,loading:c}=nh(e,t.id,ih,{version:t.checksumArray?.[0]??null}),{fetchBlob:l}=Mo(e),u=ri(t)||`document-${t.id}`,[d,f]=(0,X.useState)(!1);return(0,Z.jsx)(ah,{error:s,loading:c,children:o&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[i||a?(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(Wm,{src:o,alt:u,className:`max-h-full max-w-full object-contain`})}):(0,Z.jsx)(`img`,{src:o,alt:u,draggable:!1,onDoubleClick:r?e=>{e.preventDefault(),e.stopPropagation(),r()}:void 0,title:r?`Double-click to maximize or restore`:void 0,className:`min-h-0 w-full flex-1 object-contain ${r?`cursor-zoom-in`:``}`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:async()=>{f(!0);try{let{blob:e}=await l(t.id),n=URL.createObjectURL(e),r=window.document.createElement(`a`);r.href=n,r.download=u,window.document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),3e4)}finally{f(!1)}},disabled:d,className:`inline-flex shrink-0 self-start items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50`,children:[(0,Z.jsx)(er,{className:`h-3.5 w-3.5`}),d?`Preparing…`:`Download original`]})]})})}function sh({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Po(e,t.id);return(0,Z.jsx)(ah,{error:i,loading:a,children:r&&(0,Z.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Z.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`,className:`w-full`}),(0,Z.jsx)(rh,{workspaceId:e,document:t})]})})}function ch({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Po(e,t.id),[o,s]=(0,X.useState)(!1);return(0,Z.jsx)(ah,{error:i,loading:a,children:r&&(0,Z.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Z.jsx)(`video`,{src:r,controls:!0,playsInline:!0,preload:`metadata`,onError:()=>s(!0),className:`max-h-viewport-pane w-full rounded border`}),o&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This video can’t be played inline in your browser. Download it to view.`}),(0,Z.jsx)(rh,{workspaceId:e,document:t})]})})}function lh({workspaceId:e,document:t,className:n=``}){let{blobUrl:r,blob:i,error:a,loading:o}=Ao(e,t.id,{typeHint:`application/pdf`}),s=ri(t)||`document-${t.id}`;return(0,Z.jsx)(ah,{error:a,loading:o,children:r&&(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[(0,Z.jsx)(th,{blob:i,blobUrl:r,filename:s,className:`min-h-0 flex-1`}),(0,Z.jsx)(`div`,{children:(0,Z.jsx)(rh,{workspaceId:e,document:t})})]})})}var uh=(0,X.lazy)(()=>m(()=>import(`./markdown-html-B0qjhx3p.js`),__vite__mapDeps([2,3,4,5,6,7,8])));function dh({content:e,className:t=``,preview:n=!1}){return(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`whitespace-pre-wrap break-words ${t}`,children:e}),children:(0,Z.jsx)(uh,{content:e,className:t,preview:n})})}function fh({workspaceId:e,document:t,className:n=``}){let{text:r,error:i,loading:a}=Ao(e,t.id,{mode:`text`});return i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):a||r==null?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Z.jsx)(`pre`,{className:`bg-muted p-3 rounded text-xs overflow-auto max-h-viewport-pane whitespace-pre-wrap ${n}`,children:r})}function ph({workspaceId:e,document:t,className:n=``}){let r=t.schema===Mi,{text:i,error:a,loading:o}=Ao(e,t.id,{mode:`text`,enabled:!r});return r?(0,Z.jsxs)(`div`,{className:`markdown-note space-y-3 ${n}`,children:[t.data?.title?(0,Z.jsx)(`h3`,{className:`text-lg font-semibold`,children:String(t.data.title)}):null,(0,Z.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent`,children:(0,Z.jsx)(dh,{content:String(t.data?.content??``),className:`markdown-doc px-4 py-3`})})]}):a?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:a}):o||i==null?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Z.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent overflow-auto max-h-viewport-pane ${n}`,children:(0,Z.jsx)(dh,{content:i,className:`markdown-doc px-4 py-3`})})}function mh({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),r=wo(n);return r?(0,Z.jsx)(`div`,{className:`aspect-video w-full ${t}`,children:(0,Z.jsx)(`iframe`,{src:`https://www.youtube-nocookie.com/embed/${encodeURIComponent(r)}`,title:String(e.data?.title??e.data?.label??`YouTube video`),className:`h-full w-full rounded border`,allow:`accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture`,allowFullScreen:!0})}):null}function hh({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),[r,i]=(0,X.useState)({blobUrl:null,blob:null,failed:!1,loading:!0}),[a,o]=(0,X.useState)(n);n!==a&&(o(n),i({blobUrl:null,blob:null,failed:!1,loading:!0})),(0,X.useEffect)(()=>{let e=!1,t=null,r=async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.blob();return new Blob([t],{type:`application/pdf`})},a=()=>{let e=localStorage.getItem(`authToken`);return fetch(`${Rr}/proxy/pdf?url=${encodeURIComponent(n)}`,{headers:e?{Authorization:`Bearer ${e}`}:{}})};return fetch(n).then(r).catch(()=>a().then(r)).then(n=>{e||(t=URL.createObjectURL(n),i({blobUrl:t,blob:n,failed:!1,loading:!1}))}).catch(()=>{e||i({blobUrl:null,blob:null,failed:!0,loading:!1})}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[n]);let{blobUrl:s,blob:c,failed:l,loading:u}=r,d=(()=>{try{let e=decodeURIComponent(new URL(n).pathname.split(`/`).filter(Boolean).pop()??``)||`document`;return/\.pdf$/i.test(e)?e:`${e}.pdf`}catch{return`document.pdf`}})();return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${t}`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3`,children:[(0,Z.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Z.jsx)(gn,{className:`h-3 w-3`}),` `,n]}),c&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{if(!c)return;let e=URL.createObjectURL(c),t=window.document.createElement(`a`);t.href=e,t.download=d,window.document.body.appendChild(t),t.click(),t.remove(),setTimeout(()=>URL.revokeObjectURL(e),3e4)},className:`inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:[(0,Z.jsx)(er,{className:`h-3.5 w-3.5`}),` Download`]})]}),u&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading PDF…`}),l&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Inline preview unavailable (direct fetch and server proxy both failed). Use the link above.`}),s&&(0,Z.jsx)(th,{blob:c,blobUrl:s,filename:d,className:`min-h-[300px] flex-1`})]})}function gh(e){if(!e)return!1;try{let t=new URL(e);return!!(/\.pdf$/i.test(t.pathname)||t.hostname.endsWith(`arxiv.org`)&&t.pathname.startsWith(`/pdf/`))}catch{return!1}}function _h(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function vh({document:e,className:t=``}){let n=e.data||{},r=String(n.url??n.uri??``),i=String(n.title??n.label??``)||_h(r),a=typeof n.favIconUrl==`string`?n.favIconUrl:``,o=n.pinned===!0,s=typeof n.timestamp==`string`?n.timestamp:null,[c,l]=(0,X.useState)(!1);return(0,Z.jsxs)(`div`,{className:`space-y-3 ${t}`,children:[(0,Z.jsxs)(`a`,{href:r,target:`_blank`,rel:`noopener noreferrer`,className:`group flex items-start gap-3 rounded-lg border bg-card p-3 transition-colors hover:bg-accent/40`,children:[(0,Z.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded bg-muted`,children:a&&!c?(0,Z.jsx)(`img`,{src:a,alt:``,className:`h-5 w-5`,onError:()=>l(!0)}):(0,Z.jsx)(ae,{className:`h-4 w-4 text-muted-foreground`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:i}),o&&(0,Z.jsx)(R,{className:`h-3 w-3 shrink-0 fill-warning text-warning`})]}),(0,Z.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-muted-foreground`,children:_h(r)}),(0,Z.jsx)(`div`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground/70`,children:r})]}),(0,Z.jsx)(gn,{className:`mt-1 h-4 w-4 shrink-0 text-muted-foreground reveal-on-hover`})]}),s&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Saved `,new Date(s).toLocaleString()]})]})}var yh={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4};function bh(e){let t=e.coords,n={lat:t.latitude,lon:t.longitude,source:`device`};return t.altitude!=null&&Number.isFinite(t.altitude)&&(n.alt=t.altitude),Number.isFinite(t.accuracy)&&(n.accuracy=Math.round(t.accuracy)),n}function xh(){return new Promise((e,t)=>navigator.geolocation.getCurrentPosition(e,t,yh))}function Sh(e){let t=e?.code;return t===1?`Location permission denied`:t===2?`Location unavailable; no fix right now`:t===3?`Timed out waiting for a location fix`:`Could not read your location`}function Ch(){let e=typeof navigator<`u`&&`geolocation`in navigator&&typeof window<`u`&&window.isSecureContext,[t,n]=(0,X.useState)(e?`prompt`:`unsupported`),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),h=(0,X.useRef)(!1),g=(0,X.useRef)(null),_=(0,X.useRef)(null);(0,X.useEffect)(()=>{if(!e||!navigator.permissions?.query)return;let t=!1,r=null;return navigator.permissions.query({name:`geolocation`}).then(e=>{t||(r=e,n(e.state),e.onchange=()=>n(e.state))}).catch(()=>{}),()=>{t=!0,r&&(r.onchange=null)}},[e]);let v=(0,X.useCallback)(e=>{if(c(null),!e){_.current=null,f(null),m(null),h.current||i(!1);return}let t={lat:e.lat,lon:e.lon,source:`manual`};_.current=t,f(t),m(e.label??null),i(!0)},[]);return{supported:e,permission:t,enabled:r,busy:a,error:s,fix:l,setEnabled:(0,X.useCallback)(t=>{if(c(null),!t){h.current=!1,_.current=null,f(null),m(null),i(!1);return}_.current||e&&(h.current=!0,i(!0),o(!0),xh().then(e=>{let t=bh(e);g.current=t,u(t),n(`granted`)}).catch(e=>{c(Sh(e)),e?.code===1&&(n(`denied`),h.current=!1,i(!1))}).finally(()=>o(!1)))},[e]),manual:d,manualLabel:p,setManual:v,capture:(0,X.useCallback)(async()=>{if(_.current)return _.current;if(!h.current||!e)return null;try{return bh(await xh())}catch{return g.current}},[e])}}var wh=`2.1`,Th=[`pending`,`in-progress`,`completed`,`cancelled`],Eh={pending:`Pending`,"in-progress":`In progress`,completed:`Completed`,cancelled:`Cancelled`};function Dh(e){return String(e).padStart(2,`0`)}function Oh(e){return`${e.getFullYear()}-${Dh(e.getMonth()+1)}-${Dh(e.getDate())}T${Dh(e.getHours())}:${Dh(e.getMinutes())}`}function kh(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:Oh(t)}function Ah(e){if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function jh(){let e=new Date;return e.setHours(23,59,0,0),Oh(e)}function Mh(e){let t=Ah(e.due);return{title:e.title.trim(),...e.description.trim()?{description:e.description.trim()}:{},status:e.status,completed:e.status===`completed`,...t?{dueDate:t}:{},...e.priority===``?{}:{priority:Number(e.priority)}}}function Nh(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(`pending`),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(jh()),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)(``),[m,h]=(0,X.useState)(!1),g=Ch(),_=e.trim().length>0&&!m;async function v(t){h(!0);try{let r=await g.capture(),a=f.trim(),s={schema:hi,schemaVersion:wh,data:Mh({title:e,description:n,status:i,priority:o,due:c}),...a?{comment:a}:{},metadata:{features:Kp(u),...r?{geo:r}:{}}};return await cs(t,[s])}finally{h(!1)}}return{title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,tags:u,setTags:d,comment:f,setComment:p,saving:m,canSave:_,save:v,geotag:g}}function Ph(e){return e.data||{}}var Fh={pending:`bg-muted text-muted-foreground`,"in-progress":`bg-info/15 text-info dark:text-info`,completed:`bg-success/15 text-success dark:text-success`,cancelled:`bg-muted text-muted-foreground line-through`};function Ih(e){if(!e.dueDate||e.status===`completed`||e.status===`cancelled`)return!1;let t=new Date(e.dueDate).getTime();return Number.isFinite(t)&&t<Date.now()}function Lh(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}async function Rh(e,t,n){let r=n===`completed`,i={...t.data||{},status:n,completed:r};r?i.completedAt=new Date().toISOString():delete i.completedAt,await Da(e,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:i}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}function zh({document:e,workspaceId:t,className:n=``}){let r=Ph(e),i=Lo()!=null,[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=xo(e),l=r.status===`completed`,u=r.status??`pending`,d=Ih(r);return(0,Z.jsx)(`div`,{className:`space-y-3 ${n}`,children:(0,Z.jsxs)(`div`,{className:`relative flex items-start gap-3 rounded-lg border bg-card p-3 transition-opacity ${s?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(i||a)){o(!0);try{await Rh(t,e,l?`pending`:`completed`)}catch{}finally{o(!1)}}},disabled:i||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${i?`cursor-default opacity-70`:``}`,children:a?(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}):l&&(0,Z.jsx)($e,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`font-medium leading-tight ${l?`text-muted-foreground line-through`:``}`,children:r.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-2 text-xs`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-2 py-0.5 ${Fh[u]}`,children:Eh[u]}),r.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(de,{className:`h-3 w-3`}),Lh(r.dueDate),d?` · overdue`:``]}),typeof r.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,children:[(0,Z.jsx)(bn,{className:`h-3 w-3`}),`P`,r.priority]})]}),r.description&&(0,Z.jsx)(dh,{content:String(r.description),className:`mt-2 text-sm text-muted-foreground`}),s&&(0,Z.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),c]})]})]})})}function Bh(e){return e?typeof e==`string`?e:e.name&&e.address?`${e.name} <${e.address}>`:e.address||e.name||``:``}function Vh(e){return e?(Array.isArray(e)?e:[e]).map(e=>Bh(e)).filter(Boolean).join(`, `):``}function Hh(e){if(!Number.isFinite(e))return``;let t=Number(e);return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}function Uh(e,t,n){let r=0;ks.addHook(`afterSanitizeAttributes`,e=>{if(e.tagName===`IMG`){let i=e.getAttribute(`src`)||``,a=i.toLowerCase();if(a.startsWith(`cid:`)){let n=i.slice(4).replace(/^<|>$/g,``),r=t.get(n)||t.get(`<${n}>`);r?e.setAttribute(`src`,r):e.removeAttribute(`src`)}else(a.startsWith(`http:`)||a.startsWith(`https:`)||a.startsWith(`//`))&&(r++,n?e.setAttribute(`src`,i.replace(/^http:/i,`https:`).replace(/^\/\//,`https://`)):e.removeAttribute(`src`))}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`))});try{let t=ks.sanitize(e,{FORBID_TAGS:[`script`,`iframe`,`object`,`embed`,`form`,`base`,`link`,`meta`],FORBID_ATTR:[`srcset`]}),i=`<!doctype html><html><head>
|
|
@@ -12,7 +12,7 @@ Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}
|
|
|
12
12
|
</head><body>${t}</body></html>`;return{url:URL.createObjectURL(new Blob([i],{type:`text/html;charset=utf-8`})),remoteCount:r}}finally{ks.removeHook(`afterSanitizeAttributes`)}}function Wh(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function Gh({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=Mo(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],s=typeof a.bodyHtml==`string`&&a.bodyHtml.trim()?a.bodyHtml:null,c=typeof a.body==`string`?a.body:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!s),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(0),[_,v]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!s||d)return;let e=!1,n=[],i=o.filter(e=>e.contentId&&e.url);return Promise.all(i.slice(0,20).map(async e=>{try{let{blob:n}=await r(t.id,{url:e.url}),i=await Wh(n);return[String(e.contentId).replace(/^<|>$/g,``),i]}catch{return null}})).then(t=>{if(e)return;let r=new Map(t.filter(Boolean)),{url:i,remoteCount:a}=Uh(s,r,p);n.push(i),u(i),g(a)}).catch(t=>{e||v(String(t instanceof Error?t.message:t))}),()=>{e=!0,n.forEach(e=>URL.revokeObjectURL(e)),u(null)}},[e,t.id,s,d,p]);let b=typeof a.date==`string`?new Date(a.date).toLocaleString():null,x=o.filter(e=>!e.isInline||!e.contentId),S=async e=>{if(e.url)try{await i(t.id,e.filename||`attachment`,{url:e.url})}catch(e){v(e instanceof Error?e.message:String(e))}};return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 ${n}`,children:[(0,Z.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-2 text-sm sm:p-3`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col items-start justify-between gap-2 sm:flex-row sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 w-full space-y-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,Z.jsxs)(`details`,{className:`sm:hidden`,children:[(0,Z.jsxs)(`summary`,{className:`cursor-pointer text-xs`,children:[(0,Z.jsx)(`span`,{className:`inline-block max-w-[85%] truncate align-bottom`,children:typeof a.from==`object`&&a.from?a.from.name||a.from.address:String(a.from||`Unknown sender`)}),(0,Z.jsx)(`span`,{className:`ml-2 text-muted-foreground`,children:`Details`})]}),(0,Z.jsxs)(`div`,{className:`mt-2 space-y-1 break-words text-xs`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Bh(a.from)]}),Vh(a.to)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Vh(a.to)]}),Vh(a.cc)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Vh(a.cc)]}),b&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:b})]})]}),(0,Z.jsxs)(`div`,{className:`hidden space-y-1 break-words sm:block`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Bh(a.from)]}),Vh(a.to)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Vh(a.to)]}),Vh(a.cc)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Vh(a.cc)]}),b&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:b})]})]}),s&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2 sm:justify-end`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>f(!d),children:[d?(0,Z.jsx)(j,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(wn,{className:`mr-1.5 h-3.5 w-3.5`}),d?`HTML`:`Plain text`]}),!d&&h>0&&(0,Z.jsxs)(Y,{size:`sm`,variant:p?`secondary`:`outline`,onClick:()=>m(!p),title:`Remote images can reveal your IP/read status to the sender`,children:[p?(0,Z.jsx)(H,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Z.jsx)(y,{className:`mr-1.5 h-3.5 w-3.5`}),p?`Hide remote images`:`Show remote images (${h})`]})]})]})}),_&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:_}),!d&&s?l?(0,Z.jsx)(`iframe`,{src:l,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,Z.jsx)(`pre`,{className:`min-h-[12rem] flex-1 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-sm`,children:c||`(empty body)`}),x.length>0&&(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,x.length,`)`]}),x.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(wn,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:Hh(e.size)})]}),e.url&&(0,Z.jsxs)(`button`,{onClick:()=>S(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Z.jsx)(er,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}function Kh({attachment:e,workspaceId:t,document:n}){let{download:r}=Mo(t),i=e.mimeType||e.contentType||``,a=e.name||e.filename||`Attachment`,o=i.startsWith(`audio/`)||i.startsWith(`video/`),{blobUrl:s,error:c,loading:l}=Ao(t,n.id,{url:e.url,typeHint:i,enabled:!o&&!!e.url}),{src:u,error:d,loading:f}=Po(t,n.id,{url:e.url,enabled:o&&!!e.url}),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(``),_=o?d:c;return(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border p-2`,children:[_&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:_}),(o?f:l)&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading attachment…`}),!o&&s&&i.startsWith(`image/`)&&(0,Z.jsx)(`img`,{src:s,alt:a,className:`max-h-96 max-w-full rounded object-contain`}),o&&u&&(i.startsWith(`video/`)?(0,Z.jsx)(`video`,{controls:!0,playsInline:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`max-h-96 w-full rounded`},u):(0,Z.jsx)(`audio`,{controls:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`w-full`},u)),p&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:`This media could not be played in your browser. Download it to play in another app.`}),h&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:h}),e.url&&(0,Z.jsxs)(`button`,{className:`text-sm text-primary underline`,onClick:()=>{r(n.id,a,{url:e.url}).catch(()=>g(`Attachment could not be downloaded.`))},children:[`Download `,a]})]})}function qh(e){let t=e.document.data,n=t.sender,r=t.channel,i=Array.isArray(t.attachments)?t.attachments:[],a=t.timestamp?new Date(String(t.timestamp)):null;return(0,Z.jsxs)(`article`,{className:`space-y-4 p-3 ${e.className||``}`,children:[(0,Z.jsxs)(`header`,{className:`space-y-1 border-b pb-3`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:n?.name||n?.displayName||n?.username||n?.id||`Unknown sender`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:[r?.name||r?.id,String(t.platform||``),a&&!Number.isNaN(a.getTime())?a.toLocaleString():``].filter(Boolean).join(` · `)})]}),(0,Z.jsx)(`p`,{className:`whitespace-pre-wrap break-words text-sm`,children:String(t.text||`(No text)`)}),!!t.mediaError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:String(t.mediaError)}),i.map((t,n)=>(0,Z.jsx)(Kh,{...e,attachment:t},t.url||n))]})}var Jh={email:Cn,phone:ye,sms:je,chat:je,slack:je,matrix:je,web:ae,url:ae},Yh={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Xh=e=>Array.isArray(e)?e:[];function Zh(e,t){return t?e===`email`?`mailto:${t}`:e===`phone`||e===`sms`?`tel:${t.replace(/[^\d+]/g,``)}`:/^https?:\/\//i.test(t)?t:null:null}function Qh({title:e,count:t,children:n}){return t===0?null:(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`space-y-1`,children:n})]})}function $h({icon:e,primary:t,children:n,title:r}){return(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 rounded-md border bg-card px-2.5 py-1.5 text-sm`,title:r,children:[(0,Z.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,Z.jsx)(Ln,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function eg({document:e,className:t}){let n=e.data??{},r=Xh(n.identifiers),i=Xh(n.channels),a=Xh(n.organizations),o=Xh(n.links),s=Xh(n.tags),c=String(n.displayName||``).trim(),l=Li(e.schema,wi),u=String(n.primaryEmail||``).trim(),d=n.name&&typeof n.name==`object`?n.name:{},f=[d.prefix,d.given,d.middle,d.family,d.suffix].map(e=>String(e||``).trim()).filter(Boolean).join(` `),p=i.some(e=>e.kind===`email`&&e.value===u);return(0,Z.jsxs)(`div`,{className:K(`space-y-4`,t),children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:Yh[l]||l}),f&&f!==c&&(0,Z.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,Z.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,Z.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,Z.jsx)(Qh,{title:`Primary email`,count:1,children:(0,Z.jsx)($h,{icon:Cn,primary:!0,children:(0,Z.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,Z.jsx)(Qh,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=Zh(n,r),a=Jh[n]||je;return(0,Z.jsxs)($h,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,Z.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,Z.jsx)(Qh,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,Z.jsxs)($h,{icon:In,primary:e.primary,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,Z.jsx)(Qh,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,Z.jsxs)($h,{icon:st,children:[e.name,e.role&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,Z.jsx)(Qh,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,Z.jsxs)($h,{icon:Xt,children:[(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,Z.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function tg({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,Z.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function ng(e){let t=e.schema;if(t===`data/schema/note`)return ph;if(t===`data/schema/drawing`)return oh;if(t===`data/schema/task`)return zh;if(t===`data/schema/message/email`)return Gh;if(t===`data/schema/message`)return qh;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return eg;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return wo(t)?mh:gh(t)?hh:vh}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(xi(n,ri(e))){case`image`:return oh;case`audio`:return sh;case`video`:return ch;case`pdf`:return lh;case`markdown`:return ph;case`text`:return fh;default:return tg}}function rg({workspaceId:e,document:t,className:n}){let r=ng(t);return r?(0,Z.jsx)(r,{workspaceId:e,document:t,className:n}):(0,Z.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var ig=e=>`${Sr.workspaces}/${encodeURIComponent(e)}/messages`,ag=e=>J.get(`${ig(e)}/accounts`),og=(e,t)=>J.get(`${ig(e)}/reply-target/${t}`),sg=(e,t)=>J.post(`${ig(e)}/send`,t),cg=(e,t)=>J.get(`${ig(e)}/whatsapp/${encodeURIComponent(t)}/connection`),lg=(e,t)=>J.get(`${ig(e)}/outbox/${encodeURIComponent(t)}`),ug=(e,t)=>J.delete(`${ig(e)}/whatsapp/${encodeURIComponent(t)}/connection`),dg=(e,t)=>J.get(`${ig(e)}/thread/${t}`),fg=new As({html:!1});function pg(e){let t=e=>{let n=[];return e.map(e=>{if(e.children)return t(e.children);switch(e.type){case`strong_open`:case`strong_close`:return`*`;case`em_open`:case`em_close`:return`_`;case`s_open`:case`s_close`:return`~`;case`code_inline`:return`\`${e.content}\``;case`fence`:case`code_block`:return`\`\`\`\n${e.content}\`\`\`\n`;case`text`:return e.content;case`softbreak`:case`hardbreak`:return`
|
|
13
13
|
`;case`paragraph_close`:case`heading_close`:return`
|
|
14
14
|
|
|
15
|
-
`;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(fg.parse(e,{})).trim()}function mg(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 hg={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function gg({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${mg(e)}:smtp-test:${i?.address}`:mg(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,X.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,X.useState)(null),[m,h]=(0,X.useState)([]),[g,_]=(0,X.useState)(navigator.onLine);(0,X.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,X.useRef)(!1),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1),[C,w]=(0,X.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(null);(0,X.useEffect)(()=>{let n=!0;return Promise.all([ag(e),t?og(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,X.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})),ee=async()=>{S(!0),E(``),w(!0);let t=A?N?u:{...u,html:void 0}:{...u,text:j?pg(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await lg(e,u.requestId).catch(n=>{if(n.statusCode===404)return sg(e,t);throw n}):await sg(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)}},F=async e=>{if(L||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)}}},I=u.replyAll?f?.allRecipients:f?.recipients,L=x||C||y,R=a?`Send test email`:t?s?hg.forward:hg[u.replyAll?`replyAll`:`reply`]:`New message`,te=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Z.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(),F(t))},className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${R} to message`:`New message`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Z.jsx)(`strong`,{className:`text-sm`,children:R}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,Z.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:k?`${k.driver}:${k.address}`:``,disabled:L||!!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,Z.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,Z.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,Z.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,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,Z.jsx)(q,{"aria-label":`To`,disabled:L,value:u.to?.join(`, `)||``,onChange:e=>P({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&I&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,I.to.join(`, `),I.cc.length?` · Cc: ${I.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Z.jsx)(q,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:L,value:u[e]?.join(`, `)||``,onChange:t=>P({[e]:[t.target.value]})})]},e)),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Z.jsx)(q,{"aria-label":`Subject`,disabled:L,value:u.subject||``,placeholder:te,onChange:e=>P({subject:e.target.value||void 0})})]}),t&&!s&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:L,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,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:L,checked:u.quote||!1,onChange:e=>P({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,Z.jsx)(zo,{format:`html`,editable:!L,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>P({html:e,text:t.slice(0,32e3)})})]}):(0,Z.jsxs)(Z.Fragment,{children:[!t&&(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,Z.jsx)(q,{"aria-label":`Conversation`,disabled:L,value:u.target||``,onChange:e=>P({target:e.target.value})})]}),j?(0,Z.jsx)(zo,{format:`markdown`,editable:!L,value:u.text,placeholder:`Write a message…`,onChange:e=>P({text:e.slice(0,32e3)})}):(0,Z.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:L,value:u.text,onChange:e=>P({text:e.target.value}),placeholder:`Write a message…`})]}),(A||j)&&(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,Z.jsx)(`input`,{"aria-label":`Attach pictures`,className:`block`,type:`file`,accept:`image/png,image/jpeg,image/webp,image/gif`,multiple:!j,disabled:L,onChange:e=>{F(Array.from(e.target.files||[])),e.target.value=``}})]}),u.images?.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,Z.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,disabled:L,onClick:()=>P({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),j&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,Z.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,Z.jsx)(Y,{size:`sm`,disabled:x||y||!C&&(!k||!N&&!M&&!(A&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void ee(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,Z.jsx)(Y,{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,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Do not start another send until you have checked the conversation. The same request will not be delivered twice by Canvas.`})]})}function _g(e){let t=(0,X.useRef)(null),n=(0,X.useRef)(e.onClose);return(0,X.useEffect)(()=>{n.current=e.onClose}),(0,X.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,Z.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-lg 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,Z.jsx)(gg,{...e})})}function vg({workspaceId:e,documentId:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)({}),[c,l]=(0,X.useState)(null),u=(0,X.useCallback)(async()=>{try{let n=await dg(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,X.useEffect)(()=>{let n=!0;dg(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(Em,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(Em,i)}},[e,t,u]),i?(0,Z.jsxs)(`div`,{className:`p-3`,children:[(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,Z.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,Z.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,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Showing up to 200 linked messages.`}),n.documents.map(r=>{let i=Ui(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?[Ui(t).title]:[]}),p=o[Number(r.id)]??Number(r.id)===t;return(0,Z.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,Z.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,Z.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,Z.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,Z.jsx)(rg,{workspaceId:e,document:r})]},r.id)}),c&&(0,Z.jsx)(_g,{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 yg=15,bg=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function xg(e){return String(e).padStart(2,`0`)}function Sg(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 Cg(e){return`${e.getFullYear()}-${xg(e.getMonth()+1)}-${xg(e.getDate())}`}function wg(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function Tg(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/yg)*yg),`${xg(e.getHours())}:${xg(e.getMinutes())}`}function Eg(){let e=[];for(let t=0;t<1440;t+=yg)e.push(`${xg(Math.floor(t/60))}:${xg(t%60)}`);return e}var Dg=Eg();function Og(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 kg(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 Ag(e){let t=Sg(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 jg({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,X.useState)(!1),u=(0,X.useRef)(null),d=Sg(e),f=d?Ag(e):``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:K(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,Z.jsx)(de,{className:K(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Z.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Me,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Z.jsx)(Mg,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Mg({anchorRef:e,value:t,onChange:n,onClose:r}){let i=Sg(t),a=i?.date??Cg(new Date),o=i?.time??null,[s,c]=(0,X.useState)(()=>{let e=wg(a);return new Date(e.getFullYear(),e.getMonth(),1)}),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(null);(0,X.useLayoutEffect)(()=>{let t=l.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));f({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,X.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let p=(0,X.useMemo)(()=>!o||Dg.includes(o)?Dg:[...Dg,o].sort(),[o]);(0,X.useEffect)(()=>{let e=u.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let m=(e,t)=>n(`${e}T${t}`),h=e=>{let t=o??Tg();m(Cg(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??Tg();m(Cg(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},v=Cg(new Date),y=Og(s);return(0,Mf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Z.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},children:[(0,Z.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(oe,{className:`h-4 w-4`})}),(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:bg.map(e=>(0,Z.jsx)(`span`,{children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:y.map(e=>{let t=Cg(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>h(e),"aria-pressed":r,className:K(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===v&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,Z.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,Z.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Z.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&m(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,Z.jsx)(`div`,{ref:u,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:p.map(e=>{let t=e===o;return(0,Z.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>g(e),"aria-pressed":t,className:K(`block w-full rounded px-2 py-1 text-left text-xs tabular-nums transition-colors`,t?`bg-primary text-primary-foreground`:`hover:bg-muted`),children:kg(e)},e)})})]})]})]}),document.body)}var Ng={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Pg=`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`,Fg=`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 Ig({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-title`,children:`Title`}),(0,Z.jsx)(q,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-desc`,children:`Description`}),(0,Z.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:Fg})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-due`,children:`Due`}),(0,Z.jsx)(jg,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Z.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Pg,children:[(0,Z.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Z.jsx)(`option`,{value:e,children:Ng[e]},e))]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-status`,children:`Status`}),(0,Z.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Pg,children:Th.map(e=>(0,Z.jsx)(`option`,{value:e,children:Eh[e]},e))})]})]})}var Lg=`3.0`,Rg=[`person`,`organization`,`service`,`bot`],zg={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Bg=[`email`,`phone`,`sms`,`chat`,`web`],Vg=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function Hg(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 Ug(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Li(String(e?.schema||``),wi);return{displayName:String(t.displayName||``),type:Rg.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 Wg(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await Ca(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function Gg(e){let[t,n]=(0,X.useState)(e?.displayName??``),[r,i]=(0,X.useState)(e?.type??`person`),[a,o]=(0,X.useState)(e?.primaryEmail??``),[s,c]=(0,X.useState)(e?.given??``),[l,u]=(0,X.useState)(e?.family??``),[d,f]=(0,X.useState)(e?.channels??[]),[p,m]=(0,X.useState)(e?.identifiers??[]),[h,g]=(0,X.useState)(e?.organizations??[]),[_,v]=(0,X.useState)([]),[y,b]=(0,X.useState)(``),[x,S]=(0,X.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${wi}/${C.type}`,schemaVersion:Lg,data:Hg(C),...t?{comment:t}:{},metadata:{features:Kp(_)}},r=await cs(e,[n]);return await Wg(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 Kg=`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 qg({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(Pu,{children:e}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(U,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},i))})]})}function Jg(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 Yg(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await yo(e,`organization`);t||n(r.map(e=>({id:e.id,name:Ui(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function Xg({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=Yg(t);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Z.jsx)(q,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-type`,children:`Type`}),(0,Z.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:K(Kg,`w-full`),children:Rg.map(e=>(0,Z.jsx)(`option`,{value:e,children:zg[e]},e))})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Z.jsx)(q,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-given`,children:`Given name`}),(0,Z.jsx)(q,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-family`,children:`Family name`}),(0,Z.jsx)(q,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Z.jsx)(qg,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:K(Kg,`w-24`),children:[Bg.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!Bg.includes(e.kind)&&(0,Z.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Z.jsx)(q,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Jg(f,f.indexOf(e))),className:K(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,Z.jsx)(Ln,{className:K(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Z.jsx)(qg,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:K(Kg,`w-24`),children:[Vg.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!Vg.includes(e.type)&&(0,Z.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Z.jsx)(q,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,Z.jsx)(qg,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[y.length>0?(0,Z.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:K(Kg,`min-w-0 flex-1`),children:[(0,Z.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Z.jsx)(q,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(q,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function Zg(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 Qg(e){return Zg(e.schema)||No(e)}function $g(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function e_(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await Za(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 Ca(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await Qr(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function t_({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),a=Zg(e.schema),o=e.schema===Mi,s=No(e),c=Ro(e)??`markdown`,l=s&&ko(e),u=e.schema===hi,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=$g(e.schema),[m,h]=(0,X.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,X.useState)(String(e.data?.[p]??``)),[v,y]=(0,X.useState)(String(e.data?.content??``)),[b,x]=(0,X.useState)(String(e.data?.description??``)),[S,C]=(0,X.useState)(e.data?.status??`pending`),[w,T]=(0,X.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,X.useState)(e.data?.dueDate?kh(String(e.data.dueDate)):jh()),O=Gg(Ug(e)),[k,A]=(0,X.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[M,N]=(0,X.useState)(j),P=JSON.stringify(M??null)!==JSON.stringify(j??null),ee=e.features??e.metadata?.features,[F,I]=(0,X.useState)(qp(ee).length?qp(ee):e.data?.tags??[]),L=Ao(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Fo,version:e.checksumArray?.[0]??null}),[R,te]=(0,X.useState)(null),ne=`${e.id}:${e.checksumArray?.[0]??``}`;s&&L.text!=null&&R!==ne&&(te(ne),y(L.text));let[z,re]=(0,X.useState)([]),[ie,ae]=(0,X.useState)(!1),{replicating:oe,mirror:se}=xo(e);(0,X.useEffect)(()=>{let e=!1;return si(t).then(t=>{e||re(t)}).catch(()=>{}),()=>{e=!0}},[t]);let B=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),ce=!ie&&(s?!l&&L.text!=null&&!L.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?g.trim().length>0:o?v.trim().length>0:B:!0),V=async()=>{ae(!0);try{if(s){await Bo(t,e,v,{comment:k.trim(),...P?{metadata:{geo:M}}:{}}),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n();return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:k.trim()};if(d){let{type:t,...n}=e.data??{};i.schema=`${wi}/${O.values.type}`,i.data={...n,...Hg(O.values)},i.metadata={features:Kp(F)}}else if(u)i.data={...e.data,...Mh({title:g,description:b,status:S,priority:w,due:E})},i.metadata={features:Kp(F)};else if(a){let t=F.map(e=>e.trim()).filter(Boolean),n;o?n={...g.trim()?{title:g.trim()}:{},content:v}:(n={...e.data},f&&(n[f]=m.trim()),g.trim()?n[p]=g.trim():delete n[p],n.tags=t),i.data=n,i.metadata={features:Kp(F)}}P&&(i.metadata={...i.metadata??{},geo:M}),await Da(t,i),d&&(await e_(t,e.id,O.values.organizations),Dm()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{ae(!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-url`,children:`URL`}),(0,Z.jsx)(q,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!B&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Z.jsx)(Xg,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Z.jsx)(Ig,{idPrefix:`edit-todo`,title:g,setTitle:_,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-title`,value:g,onChange:e=>_(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Body`}),l?(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&L.error?(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:L.error}):s&&L.text==null?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Z.jsx)(Io,{kind:o?`markdown`:c,value:v,onChange:y,placeholder:o?`Write your note…`:void 0})]}),a&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:F,onChange:I,suggestions:z})]}),(0,Z.jsx)(am,{value:M,onChange:N}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`edit-comment`,value:k,onChange:e=>A(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:ie,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:V,disabled:!ce,children:ie?oe?`Replicating to ${se.label}…`:`Saving…`:`Save changes`})]})]})}var n_=(0,X.createContext)(null),r_={open:()=>{},close:()=>{}};function i_(){return(0,X.useContext)(n_)??r_}var a_=`main`,o_=(0,X.createContext)(null);function s_(){return(0,X.useContext)(o_)}var c_=50;function l_({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=i_(),o=hm(),s=s_(),c=n===`out`?e.to:e.from,l=e.document??null,[u,d]=(0,X.useState)(!1),{showErrorToast:f}=Wr(),p=async()=>{if(!(c==null||!l)){d(!0);try{let n=e.preview?await qr(t,c):l;s?o.open(n,t):a(n,t)}catch(e){f(e instanceof Error?e.message:`Failed to open document`)}finally{d(!1)}}},m=!e.meta||e.meta.src===`doc`;return(0,Z.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,Z.jsx)(qn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Z.jsx)(Bt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Z.jsx)(Dp,{document:l,size:3.5}):null,l?(0,Z.jsx)(`button`,{type:`button`,onClick:()=>void p(),disabled:u,className:`min-w-0 flex-1 truncate text-left hover:underline`,title:`Open document ${c}`,children:Ui(l).title}):(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Z.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!m&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),m&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function u_({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(0),[g,_]=(0,X.useState)(1),v=(0,X.useRef)(0),y=(0,X.useCallback)(()=>{v.current++},[]),b=(0,X.useCallback)(async()=>{let n=++v.current;try{let r=await Za(t,e.id,{offset:m*c_,limit:c_,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)/c_)-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,X.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,X.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(Em,e),()=>{y(),window.removeEventListener(Em,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 Qr(t,e.id,i.p,o,a),n(`Relation removed`),Dm()}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,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Z.jsx)(U,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Z.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,Z.jsx)(l_,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,Z.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,Z.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,Z.jsx)(Hp,{onClose:()=>{u||l(!1)},children:(0,Z.jsx)(Bp,{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 Ca(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),Dm()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var d_=(0,X.lazy)(()=>m(()=>import(`./SketchEditor-QHhsUFje.js`),__vite__mapDeps([9,3,4,1,10,11,12,13,14,15,16,17,18,19,20,21,22]))),f_=(0,X.lazy)(()=>m(()=>import(`./TextDocumentEditor-DokHJlgX.js`),__vite__mapDeps([23,3,4,10,12,11,13,14,15,24,1,21]))),p_={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},m_={reply:ee,replyAll:M,forward:ne};function h_({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Lo()!=null,{showErrorToast:a}=Wr(),[o,s]=(0,X.useState)(!1),c=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[l,u]=(0,X.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,X.useState)(n&&Qg(e)),v=e.schema===Pa,[y,b]=(0,X.useState)(!1),x=e.schema===`data/schema/note`||No(e),[S,C]=(0,X.useState)(!1),w=`${e.id}:${n}`,[E,D]=(0,X.useState)(w);return w!==E&&(D(w),_(n&&Qg(e)),u(null),s(!1)),g&&h?(0,Z.jsx)(t_,{document:e,workspaceId:t,onClose:()=>{_(!1),r?.()}}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[h&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[c&&(0,Z.jsx)(Y,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=m_[e];return(0,Z.jsxs)(Y,{size:`sm`,variant:l===e?`secondary`:`outline`,onClick:()=>m(e),children:[(0,Z.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),p_[e]]},e)}),e.schema===`data/schema/file`&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>Ci(t,e.id,ri(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Z.jsx)(er,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Z.jsx)(rt,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>C(!0),children:[(0,Z.jsx)(T,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Z.jsx)(Fe,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),y&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(d_,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),_(!0)}})}),S&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Z.jsx)(f_,{doc:e,workspaceName:t,onSaved:()=>{C(!1),r?.()},onClose:()=>C(!1),onDetails:()=>{C(!1),_(!0)}})}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:[o&&!i?(0,Z.jsx)(vg,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,Z.jsx)(rg,{workspaceId:t,document:e}),l&&f&&(0,Z.jsx)(_g,{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,Z.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Z.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var g_=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,__=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function v_({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Z.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,__(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`,g_(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Z.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function y_({document:e}){let t=e.metadata;return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:g_(e.createdAt)})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:g_(e.updatedAt)})]})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Z.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Z.jsx)(v_,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=C_(e.url);return(0,Z.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Z.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),r&&(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Z.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function b_({document:e}){let{showSuccessToast:t,showErrorToast:n}=Wr(),r=JSON.stringify(e,null,2);return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Z.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function x_({document:e,workspaceId:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,X.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,X.useEffect)(()=>{let n=!1;return vi(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Z.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Z.jsx)(u_,{document:e,workspaceId:t})]}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function S_(e){return e===`stored`?wt:e===`workspace-file`?hr:e===`imap`?Cn:e===`readonly`?ae:fn}function C_(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 w_({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(!1),_=`${t}:${e.id}`,[v,y]=(0,X.useState)(_);_!==v&&(y(_),o(null),c(null),f(null));let b=()=>{ui(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,X.useEffect)(()=>{let n=!1;return ui(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 ni(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 La(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(Of(i.failed,new Map([[e.id,ri(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,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let w=a.length===0,T=ri(e);return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(wt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Z.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),w?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>m(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>m(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,Z.jsx)(qn,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=S_(n.kind),{backend:a,key:o}=C_(n.url),s=l===n.url;return(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,Z.jsx)(`button`,{onClick:()=>Ci(t,e.id,T||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,Z.jsx)(er,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{onClick:()=>C(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),d===n.url&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Z.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(Y,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!1),children:`Also remove index entry`}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>f(null),children:`Cancel`})]})]})]},n.url)}),p&&(0,Mf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(dm,{workspaceId:t,documentCount:1,initialMode:p,defaultFilename:T,saving:h,onConfirm:S,onClose:()=>{h||m(null)}})}),window.document.body)]})}function T_(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 E_(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 D_(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&&E_(e,t,n.points)}function O_(e,t,n=!1){let r=T_(e);return r?D_(r.lat,r.lon,t):n}var k_=(0,X.lazy)(()=>m(()=>import(`./LocationTab-ARqmeXmv.js`),__vite__mapDeps([25,3,4,26,27]))),A_=[{id:`view`,label:`View`,icon:Vt},{id:`location`,label:`Location`,icon:yt},{id:`metadata`,label:`Metadata`,icon:A},{id:`json`,label:`JSON`,icon:Ae},{id:`synapses`,label:`Synapses`,icon:_n},{id:`backends`,label:`Backends`,icon:wt}];function j_({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1}){let s=Lo()!=null,c=T_(e),l=A_.filter(e=>(e.id!==`location`||c!==null)&&(!s||![`synapses`,`backends`].includes(e.id))),[u,d]=(0,X.useState)(n),f=`${e.id}:${n}`,[p,m]=(0,X.useState)(f);f!==p&&(m(f),d(n));let h=l.some(e=>e.id===u)?u:`view`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[(0,Z.jsx)(Lm,{tabs:l,active:h,onChange:d,className:`shrink-0 px-2`,iconOnly:o}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-4`,children:[h===`view`&&(0,Z.jsx)(h_,{document:e,workspaceId:t,initialEdit:r&&!s,onChanged:i}),h===`location`&&c&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Z.jsx)(k_,{lat:c.lat,lon:c.lon})}),h===`metadata`&&(0,Z.jsx)(y_,{document:e,workspaceId:t}),h===`json`&&(0,Z.jsx)(b_,{document:e,workspaceId:t}),h===`synapses`&&!s&&(0,Z.jsx)(x_,{document:e,workspaceId:t}),h===`backends`&&!s&&(0,Z.jsx)(w_,{document:e,workspaceId:t,onChanged:i})]})]})}function M_(e,t){let[n,r]=(0,X.useState)(null),i=t?.id??null,[a,o]=(0,X.useState)(i);i!==a&&(o(i),r(null));let s=(0,X.useRef)(i);(0,X.useEffect)(()=>{s.current=i},[i]);let c=(0,X.useCallback)(()=>{!e||i==null||qr(e,i).then(e=>{s.current===i&&e&&r(e)}).catch(()=>{})},[e,i]);return{document:n??t,refresh:c}}function N_(e){let t=Im(),n=(0,X.useContext)(pm),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,X.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Z.jsx)(P_,{...e})}function P_({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,X.useState)(!1),c=Uo(),{document:l,refresh:u}=M_(r,e);if(Ff(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,Mf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:K(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,Z.jsxs)(`div`,{className:K(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-lg md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-lg`),onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:Ui(l).title}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=oi(l);return e?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,Z.jsx)(gn,{className:`h-4 w-4`})}):null})(),(0,Z.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(Om.Provider,{value:()=>s(e=>!e),children:(0,Z.jsx)(j_,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var F_={sortBy:`alphabetical`,order:`asc`};function I_(e){return e?.sortBy===`crud:deleted`?{...F_}:{sortBy:e?.sortBy??F_.sortBy,order:e?.order??F_.order}}var L_={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:{...F_}};function R_(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function z_(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 B_(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function V_(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=B_(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 H_(e,t,n=[]){return{features:e.features,filters:[...V_(e.timeline),...R_(e.geo),...z_(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 U_=F_,W_={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function G_(e){return W_[e]??e}function K_(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{let t=!1;return ii(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,X.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:G_(e)})),[t])}function q_({workspaceId:e,value:t,onChange:n}){let r=K_(e);return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Z.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value,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,Z.jsx)(`option`,{value:t.sortBy,children:G_(t.sortBy)}),r.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending`:`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,Z.jsx)(Rn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(hn,{className:`h-3.5 w-3.5`})})]})}var J_={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},Y_=e=>e*1e6;function X_(){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 Z_(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Q_(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=Z_(e);return r.setDate(r.getDate()-n),r}var $_=864e5;function ev(e){let t=X_(),n=Z_(e),r=Q_(e,t);return{today:n.getTime(),yesterday:n.getTime()-$_,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*$_,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function tv(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:Y_(J_.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:Y_(J_.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:Y_(J_.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:Y_(J_.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:Y_(J_.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:Y_(J_.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:Y_(J_.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:Y_(J_.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:Y_(J_.year)+i}}function nv(e,t,n=`desc`,r=new Date){let i=ev(r),a=new Map;for(let n of e){let e=tv(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 rv(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 iv(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function av(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 ov=(e,t)=>`${Sr.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function sv(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await J.get(`${ov(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 cv(e,t,n){return uv(e,t,n,`restore`)}function lv(e,t,n){return uv(e,t,n,`discard`)}async function uv(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await J.post(`${ov(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{Sa(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 dv(e,t){let n=rv(`backends`,t);if(!n?.backend)return;let{items:r}=await sv(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 cv(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 fv(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
|
|
15
|
+
`;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(fg.parse(e,{})).trim()}function mg(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 hg={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function gg({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${mg(e)}:smtp-test:${i?.address}`:mg(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,X.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,X.useState)(null),[m,h]=(0,X.useState)([]),[g,_]=(0,X.useState)(navigator.onLine);(0,X.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,X.useRef)(!1),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1),[C,w]=(0,X.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(null);(0,X.useEffect)(()=>{let n=!0;return Promise.all([ag(e),t?og(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,X.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})),ee=async()=>{S(!0),E(``),w(!0);let t=A?N?u:{...u,html:void 0}:{...u,text:j?pg(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await lg(e,u.requestId).catch(n=>{if(n.statusCode===404)return sg(e,t);throw n}):await sg(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)}},F=async e=>{if(L||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)}}},I=u.replyAll?f?.allRecipients:f?.recipients,L=x||C||y,R=a?`Send test email`:t?s?hg.forward:hg[u.replyAll?`replyAll`:`reply`]:`New message`,te=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Z.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(),F(t))},className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${R} to message`:`New message`,children:[(0,Z.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Z.jsx)(`strong`,{className:`text-sm`,children:R}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,Z.jsxs)(`select`,{"aria-label":`Sending account`,className:`w-full rounded border bg-background p-2`,value:k?`${k.driver}:${k.address}`:``,disabled:L||!!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,Z.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,Z.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,Z.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,Z.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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,Z.jsx)(q,{"aria-label":`To`,disabled:L,value:u.to?.join(`, `)||``,onChange:e=>P({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&I&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,I.to.join(`, `),I.cc.length?` · Cc: ${I.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Z.jsx)(q,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:L,value:u[e]?.join(`, `)||``,onChange:t=>P({[e]:[t.target.value]})})]},e)),(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Z.jsx)(q,{"aria-label":`Subject`,disabled:L,value:u.subject||``,placeholder:te,onChange:e=>P({subject:e.target.value||void 0})})]}),t&&!s&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:L,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,Z.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:L,checked:u.quote||!1,onChange:e=>P({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,Z.jsx)(zo,{format:`html`,editable:!L,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>P({html:e,text:t.slice(0,32e3)})})]}):(0,Z.jsxs)(Z.Fragment,{children:[!t&&(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,Z.jsx)(q,{"aria-label":`Conversation`,disabled:L,value:u.target||``,onChange:e=>P({target:e.target.value})})]}),j?(0,Z.jsx)(zo,{format:`markdown`,editable:!L,value:u.text,placeholder:`Write a message…`,onChange:e=>P({text:e.slice(0,32e3)})}):(0,Z.jsx)(`textarea`,{"aria-label":`Message text`,className:`w-full rounded border bg-background p-2 text-sm`,rows:5,maxLength:32e3,disabled:L,value:u.text,onChange:e=>P({text:e.target.value}),placeholder:`Write a message…`})]}),(A||j)&&(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,Z.jsx)(`input`,{"aria-label":`Attach pictures`,className:`block`,type:`file`,accept:`image/png,image/jpeg,image/webp,image/gif`,multiple:!j,disabled:L,onChange:e=>{F(Array.from(e.target.files||[])),e.target.value=``}})]}),u.images?.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,Z.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,disabled:L,onClick:()=>P({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),j&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,Z.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,Z.jsx)(Y,{size:`sm`,disabled:x||y||!C&&(!k||!N&&!M&&!(A&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void ee(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,Z.jsx)(Y,{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,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Do not start another send until you have checked the conversation. The same request will not be delivered twice by Canvas.`})]})}function _g(e){let t=(0,X.useRef)(null),n=(0,X.useRef)(e.onClose);return(0,X.useEffect)(()=>{n.current=e.onClose}),(0,X.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,Z.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-lg 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,Z.jsx)(gg,{...e})})}function vg({workspaceId:e,documentId:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)({}),[c,l]=(0,X.useState)(null),u=(0,X.useCallback)(async()=>{try{let n=await dg(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,X.useEffect)(()=>{let n=!0;dg(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(Em,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(Em,i)}},[e,t,u]),i?(0,Z.jsxs)(`div`,{className:`p-3`,children:[(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,Z.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,Z.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,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Showing up to 200 linked messages.`}),n.documents.map(r=>{let i=Ui(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?[Ui(t).title]:[]}),p=o[Number(r.id)]??Number(r.id)===t;return(0,Z.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,Z.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,Z.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,Z.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,Z.jsx)(rg,{workspaceId:e,document:r})]},r.id)}),c&&(0,Z.jsx)(_g,{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 yg=15,bg=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function xg(e){return String(e).padStart(2,`0`)}function Sg(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 Cg(e){return`${e.getFullYear()}-${xg(e.getMonth()+1)}-${xg(e.getDate())}`}function wg(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function Tg(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/yg)*yg),`${xg(e.getHours())}:${xg(e.getMinutes())}`}function Eg(){let e=[];for(let t=0;t<1440;t+=yg)e.push(`${xg(Math.floor(t/60))}:${xg(t%60)}`);return e}var Dg=Eg();function Og(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 kg(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 Ag(e){let t=Sg(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 jg({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,X.useState)(!1),u=(0,X.useRef)(null),d=Sg(e),f=d?Ag(e):``;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:K(`inline-flex w-full items-center gap-2 rounded-md border border-input bg-transparent text-left shadow-elevation-1 transition-colors`,`focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`,o?`h-6 px-1.5 text-[11px]`:`h-9 px-3 py-1 text-sm`,!d&&`text-muted-foreground`,s),children:[(0,Z.jsx)(de,{className:K(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Z.jsx)(`span`,{role:`button`,tabIndex:-1,"aria-label":`Clear date`,title:`Clear`,onClick:e=>{e.stopPropagation(),t(``)},className:`shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Me,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Z.jsx)(Mg,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Mg({anchorRef:e,value:t,onChange:n,onClose:r}){let i=Sg(t),a=i?.date??Cg(new Date),o=i?.time??null,[s,c]=(0,X.useState)(()=>{let e=wg(a);return new Date(e.getFullYear(),e.getMonth(),1)}),l=(0,X.useRef)(null),u=(0,X.useRef)(null),[d,f]=(0,X.useState)(null);(0,X.useLayoutEffect)(()=>{let t=l.current,n=e.current;if(!t||!n)return;let r=()=>{let e=n.getBoundingClientRect(),{width:r,height:i}=t.getBoundingClientRect(),a=e.bottom+4,o=a+i+8>window.innerHeight?Math.max(8,e.top-i-4):a,s=Math.max(8,Math.min(e.left,window.innerWidth-r-8));f({x:s,y:o})};r();let i=new ResizeObserver(r);return i.observe(t),window.addEventListener(`resize`,r),window.addEventListener(`scroll`,r,!0),()=>{i.disconnect(),window.removeEventListener(`resize`,r),window.removeEventListener(`scroll`,r,!0)}},[e]),(0,X.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let p=(0,X.useMemo)(()=>!o||Dg.includes(o)?Dg:[...Dg,o].sort(),[o]);(0,X.useEffect)(()=>{let e=u.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let m=(e,t)=>n(`${e}T${t}`),h=e=>{let t=o??Tg();m(Cg(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??Tg();m(Cg(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},v=Cg(new Date),y=Og(s);return(0,Mf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Z.jsxs)(`div`,{ref:l,role:`dialog`,"aria-label":`Choose date and time`,className:`fixed z-50 flex max-w-[95vw] gap-2 rounded-md border bg-popover p-2 text-popover-foreground shadow-elevation-4`,style:{left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},children:[(0,Z.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()-1,1)),"aria-label":`Previous month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(oe,{className:`h-4 w-4`})}),(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(new Date(s.getFullYear(),s.getMonth()+1,1)),"aria-label":`Next month`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5 px-0.5 pb-1 text-center text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:bg.map(e=>(0,Z.jsx)(`span`,{children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:y.map(e=>{let t=Cg(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>h(e),"aria-pressed":r,className:K(`h-7 rounded text-xs tabular-nums transition-colors`,n?`text-muted-foreground/40`:`text-foreground`,r?`bg-primary text-primary-foreground`:`hover:bg-muted`,!r&&t===v&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,Z.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(t),className:`flex-1 rounded border border-border px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:e},e))})]}),(0,Z.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Z.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&m(a,e.target.value.slice(0,5))},"aria-label":`Time`,className:`mb-1 h-7 w-full rounded border border-input bg-transparent px-1.5 text-xs tabular-nums focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`}),(0,Z.jsx)(`div`,{ref:u,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:p.map(e=>{let t=e===o;return(0,Z.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>g(e),"aria-pressed":t,className:K(`block w-full rounded px-2 py-1 text-left text-xs tabular-nums transition-colors`,t?`bg-primary text-primary-foreground`:`hover:bg-muted`),children:kg(e)},e)})})]})]})]}),document.body)}var Ng={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Pg=`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`,Fg=`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 Ig({title:e,setTitle:t,description:n,setDescription:r,status:i,setStatus:a,priority:o,setPriority:s,due:c,setDue:l,idPrefix:u=`todo`}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-title`,children:`Title`}),(0,Z.jsx)(q,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-desc`,children:`Description`}),(0,Z.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:Fg})]}),(0,Z.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-due`,children:`Due`}),(0,Z.jsx)(jg,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Z.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Pg,children:[(0,Z.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Z.jsx)(`option`,{value:e,children:Ng[e]},e))]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${u}-status`,children:`Status`}),(0,Z.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Pg,children:Th.map(e=>(0,Z.jsx)(`option`,{value:e,children:Eh[e]},e))})]})]})}var Lg=`3.0`,Rg=[`person`,`organization`,`service`,`bot`],zg={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Bg=[`email`,`phone`,`sms`,`chat`,`web`],Vg=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function Hg(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 Ug(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Li(String(e?.schema||``),wi);return{displayName:String(t.displayName||``),type:Rg.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 Wg(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await Ca(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function Gg(e){let[t,n]=(0,X.useState)(e?.displayName??``),[r,i]=(0,X.useState)(e?.type??`person`),[a,o]=(0,X.useState)(e?.primaryEmail??``),[s,c]=(0,X.useState)(e?.given??``),[l,u]=(0,X.useState)(e?.family??``),[d,f]=(0,X.useState)(e?.channels??[]),[p,m]=(0,X.useState)(e?.identifiers??[]),[h,g]=(0,X.useState)(e?.organizations??[]),[_,v]=(0,X.useState)([]),[y,b]=(0,X.useState)(``),[x,S]=(0,X.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${wi}/${C.type}`,schemaVersion:Lg,data:Hg(C),...t?{comment:t}:{},metadata:{features:Kp(_)}},r=await cs(e,[n]);return await Wg(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 Kg=`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 qg({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(Pu,{children:e}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n([...t,r()]),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(U,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Z.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(t.filter((e,t)=>t!==i)),className:`shrink-0 rounded p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive`,"aria-label":`Remove ${e.toLowerCase()} row`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},i))})]})}function Jg(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 Yg(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await yo(e,`organization`);t||n(r.map(e=>({id:e.id,name:Ui(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function Xg({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=Yg(t);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Z.jsx)(q,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-type`,children:`Type`}),(0,Z.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:K(Kg,`w-full`),children:Rg.map(e=>(0,Z.jsx)(`option`,{value:e,children:zg[e]},e))})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Z.jsx)(q,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-given`,children:`Given name`}),(0,Z.jsx)(q,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${e}-family`,children:`Family name`}),(0,Z.jsx)(q,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Z.jsx)(qg,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:K(Kg,`w-24`),children:[Bg.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!Bg.includes(e.kind)&&(0,Z.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Z.jsx)(q,{value:e.value,onChange:e=>t({value:e.target.value}),placeholder:e.kind===`phone`?`+421…`:`address or handle`,className:`min-w-0 flex-1`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Jg(f,f.indexOf(e))),className:K(`shrink-0 rounded p-1.5 transition-colors hover:bg-muted`,e.primary?`text-data-5`:`text-muted-foreground`),title:e.primary?`Primary for this kind`:`Make primary for this kind`,"aria-pressed":!!e.primary,children:(0,Z.jsx)(Ln,{className:K(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Z.jsx)(qg,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:K(Kg,`w-24`),children:[Vg.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),!Vg.includes(e.type)&&(0,Z.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Z.jsx)(q,{value:e.identifier,onChange:e=>t({identifier:e.target.value}),placeholder:`octocat, U024BE7LH, 0xABCD…`,className:`min-w-0 flex-1 font-mono text-xs`})]})}),(0,Z.jsx)(qg,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Z.jsxs)(Z.Fragment,{children:[y.length>0?(0,Z.jsxs)(`select`,{value:e.identityId?String(e.identityId):``,onChange:e=>{let n=y.find(t=>String(t.id)===e.target.value);t(n?{identityId:n.id,name:n.name}:{identityId:void 0})},className:K(Kg,`min-w-0 flex-1`),children:[(0,Z.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Z.jsx)(q,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(q,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function Zg(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 Qg(e){return Zg(e.schema)||No(e)}function $g(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function e_(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await Za(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 Ca(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await Qr(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function t_({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),a=Zg(e.schema),o=e.schema===Mi,s=No(e),c=Ro(e)??`markdown`,l=s&&ko(e),u=e.schema===hi,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=$g(e.schema),[m,h]=(0,X.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,X.useState)(String(e.data?.[p]??``)),[v,y]=(0,X.useState)(String(e.data?.content??``)),[b,x]=(0,X.useState)(String(e.data?.description??``)),[S,C]=(0,X.useState)(e.data?.status??`pending`),[w,T]=(0,X.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,X.useState)(e.data?.dueDate?kh(String(e.data.dueDate)):jh()),O=Gg(Ug(e)),[k,A]=(0,X.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[M,N]=(0,X.useState)(j),P=JSON.stringify(M??null)!==JSON.stringify(j??null),ee=e.features??e.metadata?.features,[F,I]=(0,X.useState)(qp(ee).length?qp(ee):e.data?.tags??[]),L=Ao(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Fo,version:e.checksumArray?.[0]??null}),[R,te]=(0,X.useState)(null),ne=`${e.id}:${e.checksumArray?.[0]??``}`;s&&L.text!=null&&R!==ne&&(te(ne),y(L.text));let[z,re]=(0,X.useState)([]),[ie,ae]=(0,X.useState)(!1),{replicating:oe,mirror:se}=xo(e);(0,X.useEffect)(()=>{let e=!1;return si(t).then(t=>{e||re(t)}).catch(()=>{}),()=>{e=!0}},[t]);let B=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),ce=!ie&&(s?!l&&L.text!=null&&!L.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?g.trim().length>0:o?v.trim().length>0:B:!0),V=async()=>{ae(!0);try{if(s){await Bo(t,e,v,{comment:k.trim(),...P?{metadata:{geo:M}}:{}}),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n();return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:k.trim()};if(d){let{type:t,...n}=e.data??{};i.schema=`${wi}/${O.values.type}`,i.data={...n,...Hg(O.values)},i.metadata={features:Kp(F)}}else if(u)i.data={...e.data,...Mh({title:g,description:b,status:S,priority:w,due:E})},i.metadata={features:Kp(F)};else if(a){let t=F.map(e=>e.trim()).filter(Boolean),n;o?n={...g.trim()?{title:g.trim()}:{},content:v}:(n={...e.data},f&&(n[f]=m.trim()),g.trim()?n[p]=g.trim():delete n[p],n.tags=t),i.data=n,i.metadata={features:Kp(F)}}P&&(i.metadata={...i.metadata??{},geo:M}),await Da(t,i),d&&(await e_(t,e.id,O.values.organizations),Dm()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{ae(!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-url`,children:`URL`}),(0,Z.jsx)(q,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!B&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Z.jsx)(Xg,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Z.jsx)(Ig,{idPrefix:`edit-todo`,title:g,setTitle:_,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-title`,value:g,onChange:e=>_(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Body`}),l?(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&L.error?(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:L.error}):s&&L.text==null?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Z.jsx)(Io,{kind:o?`markdown`:c,value:v,onChange:y,placeholder:o?`Write your note…`:void 0})]}),a&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:F,onChange:I,suggestions:z})]}),(0,Z.jsx)(am,{value:M,onChange:N}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`edit-comment`,value:k,onChange:e=>A(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:ie,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:V,disabled:!ce,children:ie?oe?`Replicating to ${se.label}…`:`Saving…`:`Save changes`})]})]})}var n_=(0,X.createContext)(null),r_={open:()=>{},close:()=>{}};function i_(){return(0,X.useContext)(n_)??r_}var a_=`main`,o_=(0,X.createContext)(null);function s_(){return(0,X.useContext)(o_)}var c_=50;function l_({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=i_(),o=hm(),s=s_(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?Ui(l).title:``,[d,f]=(0,X.useState)(!1),{showErrorToast:p}=Wr(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await qr(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,Z.jsxs)(`div`,{className:`group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-muted/60`,children:[n===`out`?(0,Z.jsx)(qn,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Z.jsx)(Bt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Z.jsx)(Dp,{document:l,size:3.5}):null,l?(0,Z.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,Z.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Z.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!h&&(0,Z.jsx)(`span`,{className:`shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,title:`Derived by ${e.meta?.src}`,children:e.meta?.src}),h&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,disabled:i,className:`shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 disabled:opacity-40`,title:`Remove relation`,"aria-label":`Remove relation`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function u_({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(0),[g,_]=(0,X.useState)(1),v=(0,X.useRef)(0),y=(0,X.useCallback)(()=>{v.current++},[]),b=(0,X.useCallback)(async()=>{let n=++v.current;try{let r=await Za(t,e.id,{offset:m*c_,limit:c_,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)/c_)-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,X.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,X.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(Em,e),()=>{y(),window.removeEventListener(Em,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 Qr(t,e.id,i.p,o,a),n(`Relation removed`),Dm()}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,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Z.jsx)(U,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Z.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-1 text-xs font-medium text-muted-foreground`,title:r,children:n}),Array.from(new Set(i.map(e=>e.p))).map(n=>(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 font-mono text-[11px] text-muted-foreground`,children:n}),i.filter(e=>e.p===n).map(n=>{let r=e===`out`?n.to:n.from,i=`${e}:${n.p}:${r}`;return(0,Z.jsx)(l_,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,Z.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,Z.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,Z.jsx)(Hp,{onClose:()=>{u||l(!1)},children:(0,Z.jsx)(Bp,{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 Ca(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),Dm()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var d_=(0,X.lazy)(()=>m(()=>import(`./SketchEditor-K3h9uQVw.js`),__vite__mapDeps([9,3,4,1,10,11,12,13,14,15,16,17,18,19,20,21,22]))),f_=(0,X.lazy)(()=>m(()=>import(`./TextDocumentEditor-CB5pebVj.js`),__vite__mapDeps([23,3,4,10,12,11,13,14,15,24,1,21]))),p_={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},m_={reply:ee,replyAll:M,forward:ne};function h_({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Lo()!=null,{showErrorToast:a}=Wr(),[o,s]=(0,X.useState)(!1),c=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[l,u]=(0,X.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,X.useState)(n&&Qg(e)),v=e.schema===Pa,[y,b]=(0,X.useState)(!1),x=e.schema===`data/schema/note`||No(e),[S,C]=(0,X.useState)(!1),w=`${e.id}:${n}`,[E,D]=(0,X.useState)(w);return w!==E&&(D(w),_(n&&Qg(e)),u(null),s(!1)),g&&h?(0,Z.jsx)(t_,{document:e,workspaceId:t,onClose:()=>{_(!1),r?.()}}):(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[h&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[c&&(0,Z.jsx)(Y,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=m_[e];return(0,Z.jsxs)(Y,{size:`sm`,variant:l===e?`secondary`:`outline`,onClick:()=>m(e),children:[(0,Z.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),p_[e]]},e)}),e.schema===`data/schema/file`&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>Ci(t,e.id,ri(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Z.jsx)(er,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Z.jsx)(rt,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>C(!0),children:[(0,Z.jsx)(T,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Z.jsx)(Fe,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),y&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(d_,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),_(!0)}})}),S&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Z.jsx)(f_,{doc:e,workspaceName:t,onSaved:()=>{C(!1),r?.()},onClose:()=>C(!1),onDetails:()=>{C(!1),_(!0)}})}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:[o&&!i?(0,Z.jsx)(vg,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,Z.jsx)(rg,{workspaceId:t,document:e}),l&&f&&(0,Z.jsx)(_g,{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,Z.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Z.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Z.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var g_=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,__=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function v_({meta:e}){let{geo:t,exif:n,dimensions:r}=e;if(!t&&!n&&!r)return null;let i=(e,t)=>t==null||t===``?null:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Z.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[r&&i(`Dimensions`,r.width&&r.height?`${r.width} × ${r.height}`:null),n&&i(`Camera`,[n.make,n.model].filter(Boolean).join(` `)),n&&i(`Lens`,n.lensModel),n&&i(`Aperture`,Number.isFinite(n.fNumber)?`ƒ/${n.fNumber}`:null),n&&i(`Shutter`,__(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`,g_(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Z.jsxs)(`a`,{href:`https://www.openstreetmap.org/?mlat=${t.lat}&mlon=${t.lon}#map=15/${t.lat}/${t.lon}`,target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline underline-offset-2`,children:[t.lat.toFixed(5),`, `,t.lon.toFixed(5),Number.isFinite(t.alt)?` · ${Math.round(t.alt)} m`:``]}))]})]})}function y_({document:e}){let t=e.metadata;return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Z.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:g_(e.createdAt)})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:g_(e.updatedAt)})]})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Z.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Z.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Z.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Z.jsx)(v_,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=C_(e.url);return(0,Z.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Z.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),r&&(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Z.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Z.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Z.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Z.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Z.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function b_({document:e}){let{showSuccessToast:t,showErrorToast:n}=Wr(),r=JSON.stringify(e,null,2);return(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`div`,{className:`flex justify-end`,children:(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Z.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function x_({document:e,workspaceId:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,X.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,X.useEffect)(()=>{let n=!1;return vi(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[[{title:`Context tree`,type:`context`},{title:`Directory tree`,type:`directory`}].map(({title:e,type:t})=>{let r=n.filter(e=>e.type===t),i=r.flatMap(e=>e.paths.map(t=>({tree:e.tree,path:t})));return(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Z.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Z.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Z.jsx)(u_,{document:e,workspaceId:t})]}):(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function S_(e){return e===`stored`?wt:e===`workspace-file`?hr:e===`imap`?Cn:e===`readonly`?ae:fn}function C_(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 w_({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(!1),_=`${t}:${e.id}`,[v,y]=(0,X.useState)(_);_!==v&&(y(_),o(null),c(null),f(null));let b=()=>{ui(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,X.useEffect)(()=>{let n=!1;return ui(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 ni(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 La(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(Of(i.failed,new Map([[e.id,ri(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,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let w=a.length===0,T=ri(e);return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(wt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Z.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Z.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),w?(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No byte locations; this object lives only in the workspace database, so there is no file data to copy or move.`}):(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>m(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Z.jsx)(Ve,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>m(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,Z.jsx)(qn,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=S_(n.kind),{backend:a,key:o}=C_(n.url),s=l===n.url;return(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`rounded px-1.5 py-0.5 text-[10px] uppercase ${n.deletable?`bg-muted text-muted-foreground`:`bg-warning/15 text-warning`}`,children:n.deletable?n.kind:`read-only`}),(0,Z.jsx)(`button`,{onClick:()=>Ci(t,e.id,T||`document-${e.id}`,{url:n.url}).catch(e=>i(e instanceof Error?e.message:String(e))),className:`text-muted-foreground hover:text-foreground`,title:`Download this copy`,children:(0,Z.jsx)(er,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{onClick:()=>C(n),disabled:s,className:`text-muted-foreground hover:text-destructive disabled:opacity-50`,title:n.deletable?`Remove from backend`:`Drop reference (bytes stay; backend is read-only)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),d===n.url&&(0,Z.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Z.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Z.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsx)(Y,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!1),children:`Also remove index entry`}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void x(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>f(null),children:`Cancel`})]})]})]},n.url)}),p&&(0,Mf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(dm,{workspaceId:t,documentCount:1,initialMode:p,defaultFilename:T,saving:h,onConfirm:S,onClose:()=>{h||m(null)}})}),window.document.body)]})}function T_(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 E_(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 D_(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&&E_(e,t,n.points)}function O_(e,t,n=!1){let r=T_(e);return r?D_(r.lat,r.lon,t):n}var k_=(0,X.lazy)(()=>m(()=>import(`./LocationTab-ARqmeXmv.js`),__vite__mapDeps([25,3,4,26,27]))),A_=[{id:`view`,label:`View`,icon:Vt},{id:`location`,label:`Location`,icon:yt},{id:`metadata`,label:`Metadata`,icon:A},{id:`json`,label:`JSON`,icon:Ae},{id:`synapses`,label:`Synapses`,icon:_n},{id:`backends`,label:`Backends`,icon:wt}];function j_({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1}){let s=Lo()!=null,c=T_(e),l=A_.filter(e=>(e.id!==`location`||c!==null)&&(!s||![`synapses`,`backends`].includes(e.id))),[u,d]=(0,X.useState)(n),f=`${e.id}:${n}`,[p,m]=(0,X.useState)(f);f!==p&&(m(f),d(n));let h=l.some(e=>e.id===u)?u:`view`;return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[(0,Z.jsx)(Lm,{tabs:l,active:h,onChange:d,className:`shrink-0 px-2`,iconOnly:o}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-4`,children:[h===`view`&&(0,Z.jsx)(h_,{document:e,workspaceId:t,initialEdit:r&&!s,onChanged:i}),h===`location`&&c&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Z.jsx)(k_,{lat:c.lat,lon:c.lon})}),h===`metadata`&&(0,Z.jsx)(y_,{document:e,workspaceId:t}),h===`json`&&(0,Z.jsx)(b_,{document:e,workspaceId:t}),h===`synapses`&&!s&&(0,Z.jsx)(x_,{document:e,workspaceId:t}),h===`backends`&&!s&&(0,Z.jsx)(w_,{document:e,workspaceId:t,onChanged:i})]})]})}function M_(e,t){let[n,r]=(0,X.useState)(null),i=t?.id??null,[a,o]=(0,X.useState)(i);i!==a&&(o(i),r(null));let s=(0,X.useRef)(i);(0,X.useEffect)(()=>{s.current=i},[i]);let c=(0,X.useCallback)(()=>{!e||i==null||qr(e,i).then(e=>{s.current===i&&e&&r(e)}).catch(()=>{})},[e,i]);return{document:n??t,refresh:c}}function N_(e){let t=Im(),n=(0,X.useContext)(pm),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,X.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Z.jsx)(P_,{...e})}function P_({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,X.useState)(!1),c=Uo(),{document:l,refresh:u}=M_(r,e);if(Ff(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,Mf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:K(`fixed inset-0 z-50 flex items-center justify-center bg-scrim`,o?`p-0`:`p-4 max-md:p-2`,o&&d&&`md:right-[min(436px,90vw)]`),onClick:n,children:(0,Z.jsxs)(`div`,{className:K(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-lg md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-lg`),onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:Ui(l).title}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=oi(l);return e?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,className:`rounded-sm p-2 text-muted-foreground hover:bg-muted hover:text-foreground`,title:`Open original: ${e}`,"aria-label":`Open original`,children:(0,Z.jsx)(gn,{className:`h-4 w-4`})}):null})(),(0,Z.jsx)(`button`,{onClick:()=>s(!o),className:`hidden rounded-sm p-2 hover:bg-muted md:block`,title:o?`Restore`:`Fullscreen`,"aria-label":o?`Restore`:`Fullscreen`,children:o?(0,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(Om.Provider,{value:()=>s(e=>!e),children:(0,Z.jsx)(j_,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var F_={sortBy:`alphabetical`,order:`asc`};function I_(e){return e?.sortBy===`crud:deleted`?{...F_}:{sortBy:e?.sortBy??F_.sortBy,order:e?.order??F_.order}}var L_={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:{...F_}};function R_(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function z_(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 B_(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function V_(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=B_(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 H_(e,t,n=[]){return{features:e.features,filters:[...V_(e.timeline),...R_(e.geo),...z_(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 U_=F_,W_={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function G_(e){return W_[e]??e}function K_(e){let[t,n]=(0,X.useState)([]);return(0,X.useEffect)(()=>{let t=!1;return ii(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,X.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:G_(e)})),[t])}function q_({workspaceId:e,value:t,onChange:n}){let r=K_(e);return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Z.jsxs)(`select`,{value:t.sortBy,onChange:e=>n({...t,sortBy:e.target.value,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,Z.jsx)(`option`,{value:t.sortBy,children:G_(t.sortBy)}),r.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n({...t,order:t.order===`asc`?`desc`:`asc`}),title:t.order===`asc`?`Ascending`:`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,Z.jsx)(Rn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(hn,{className:`h-3.5 w-3.5`})})]})}var J_={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},Y_=e=>e*1e6;function X_(){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 Z_(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Q_(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=Z_(e);return r.setDate(r.getDate()-n),r}var $_=864e5;function ev(e){let t=X_(),n=Z_(e),r=Q_(e,t);return{today:n.getTime(),yesterday:n.getTime()-$_,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*$_,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function tv(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:Y_(J_.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:Y_(J_.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:Y_(J_.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:Y_(J_.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:Y_(J_.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:Y_(J_.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:Y_(J_.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:Y_(J_.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:Y_(J_.year)+i}}function nv(e,t,n=`desc`,r=new Date){let i=ev(r),a=new Map;for(let n of e){let e=tv(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 rv(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 iv(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function av(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 ov=(e,t)=>`${Sr.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function sv(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await J.get(`${ov(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 cv(e,t,n){return uv(e,t,n,`restore`)}function lv(e,t,n){return uv(e,t,n,`discard`)}async function uv(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await J.post(`${ov(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{Sa(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 dv(e,t){let n=rv(`backends`,t);if(!n?.backend)return;let{items:r}=await sv(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 cv(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 fv(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
|
|
16
16
|
`)+(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 pv(e,t){let n=rv(`backends`,t);if(!n?.backend)return;let{items:r}=await sv(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!fv(n.backend,i))return;let a=await lv(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 mv({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=n||`context`,a=i===`directory`,o=(0,X.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),s=(0,X.useCallback)(async(n,r=!0)=>{let a;if(e)a=await ss(e,n,r);else if(t)a=await _a(t,n,r,i);else return!1;let s=sp(n);if(a&&s)try{e?await es(e,n,s):t&&await ia(t,n,s,i)}catch{}return o(),a},[e,t,i,o]),c=(0,X.useCallback)(async(n,r=!1,a=!1,s=!1)=>{try{return e?await $o(e,n,r):t?await Xi(t,n,r,i,a,s):!1}finally{o()}},[e,t,i,o]),l=(0,X.useCallback)(async(n,r)=>{let a;if(e){let t=n.split(`/`);t[t.length-1]=r,a=await rs(e,n,t.join(`/`),!1)}else if(t)a=await ia(t,n,{name:r},i);else return!1;return o(),a},[e,t,i,o]),u=(0,X.useCallback)(async(n,r,a=!1,s=i,c=i,l={})=>{let u;if(e)u=await rs(e,n,r,a,l);else if(t)u=await Ni(t,n,r,a,s,c,l);else return!1;return o(),u},[e,t,i,o]),d=(0,X.useCallback)(async n=>{let r;if(e)r=await Ts(e,n);else if(t)r=await Ti(t,n,i);else return null;return o(),r},[e,t,i,o]),f=(0,X.useCallback)(async n=>{let r;if(e)r=await Zo(e,n);else if(t)r=await Aa(t,n,i);else return null;return o(),r},[e,t,i,o]),p=(0,X.useCallback)(async(n,r,a=!1,s=i,c=i)=>{let l;if(e)l=await ls(e,n,r,a);else if(t)l=await za(t,n,r,a,s,c);else return!1;return o(),l},[e,t,i,o]),h=(0,X.useCallback)(async(n,r)=>e?await es(e,n,r):t?await ia(t,n,r,i):!1,[e,t,i]),g=(0,X.useCallback)(async(n,r)=>{let a;if(e)a=await Wo(e,n,r);else if(t)a=await Di(t,n,r,i);else return null;return o(),a},[e,t,i,o]),_=(0,X.useCallback)(async(n,r)=>{let a;if(e)a=await ms(e,n,r);else if(t)a=await sa(t,n,r,i);else return null;return o(),a},[e,t,i,o]),v=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await Ma(t,e,t,i);return o(300),n},[t,i,o]),y=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;try{await ga(t,e,n??t,i)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return o(300),!0},[t,i,o]),b=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await Oi(t,e,i);return o(),n},[t,i,o]),x=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await Ta(t).catch(()=>[]),r=no(e,n);return r?(await Ka(t,r.driver,r.address),o(300),!0):!1},[t,o]),S=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;let r=await Ta(t).catch(()=>[]),i=fa(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await oa(t,i.driver,i.address,[a]),o(200),!0},[t,o]),C=(0,X.useCallback)(async(e,n)=>{if(!t)return!1;let r=await Ta(t).catch(()=>[]),i=fa(e,r);return!i||!i.key?!1:(await di(t,i.driver,i.address,i.key,n),o(200),!0)},[t,o]),w=(0,X.useCallback)(async e=>{if(!t)return!1;let n=await Ta(t).catch(()=>[]),r=fa(e,n);return!r||!r.key?!1:(await To(t,r.driver,r.address,r.key),o(200),!0)},[t,o]),T=(0,X.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await m(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-9UozkUFv.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([28,3,4,10,12,11,13]));r({mode:e,path:n,workspaceId:t,treeName:i,onImported:o})},[t,i,o]);return{onInsertPath:s,onRemovePath:c,onRenamePath:l,onMovePath:u,onCopyPath:p,onExportSubtree:t?e=>T(`export`,e):void 0,onImportSubtree:t&&i!==`backends`?e=>T(`import`,e):void 0,onUpdateNode:h,onMergeLayer:g,onSubtractLayer:_,onMergeDown:a?void 0:d,onSubtractDown:a?void 0:f,onLockLayer:t?v:void 0,onUnlockLayer:t?y:void 0,onDestroyLayer:t&&!a?b:void 0,onResyncBackend:t?x:void 0,onCreateBackendFolder:t?S:void 0,onRenameBackendFolder:t?C:void 0,onDeleteBackendFolder:t?w:void 0}}function hv(e){return`/workspaces/${e}/hooks`}async function gv(e){return await J.get(hv(e))||[]}async function _v(e,t){return(await J.get(`${hv(e)}/${t}`))?.content??``}async function vv(e,t,n){await J.put(`${hv(e)}/${t}`,{content:n})}async function yv(e,t){await J.delete(`${hv(e)}/${t}`)}var bv=[`example-`,`disabled-`,`_`];function xv(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function Sv(e){return bv.find(t=>e.startsWith(t))??null}function Cv(e){return Sv(xv(e).base)===null}function wv(e){return xv(e).base.startsWith(`example-`)}function Tv(e){let{dir:t,base:n}=xv(e),r=Sv(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function Ev(e,t,n){if(Cv(t)===n)return t;let r=Tv(t);return await vv(e,r,await _v(e,t)),await yv(e,t),r}function Dv(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 Ov(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function kv(e){let t=e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function Av(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 jv(e){return`dir:/${Av(e)?.rel||``}`}function Mv(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 Nv(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}function Pv(e){let t=e.filter(e=>e.path.startsWith(`started/`)&&e.path.includes(`backend-tree-sync`));return t.find(e=>Cv(e.path))?.path??t[0]?.path??null}var Fv=`rules.json`;async function Iv(e){try{let t=await _v(e,Fv),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Lv(e,t){await vv(e,Fv,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
17
17
|
`)}async function Rv(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 J.get(`${hv(e)}/pending${r?`?${r}`:``}`)||[]}async function zv(e,t){return await J.post(`${hv(e)}/pending/decisions`,t)}async function Bv(e,t){return await J.get(`${hv(e)}/runs/${encodeURIComponent(t)}`)}async function Vv(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 J.get(`${hv(e)}/runs${r?`?${r}`:``}`)||[]}var Hv=1e4,Uv=`canvas.hooks.backfillLimit`;function Wv(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?100:Math.min(t,Hv)}function Gv(){try{let e=localStorage.getItem(Uv);return e?Wv(e):100}catch{return 100}}function Kv(e){let t=Wv(e);try{localStorage.setItem(Uv,String(t))}catch{}return t}function qv(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 Jv(e,t){return await J.post(`${hv(e)}/backfill`,t)}async function Yv(e,t){return await J.post(`${hv(e)}/run`,t)}async function Xv(e,t){return await J.post(`${hv(e)}/runs/${t}/replay`,{})}async function Zv(e){return await J.get(`${hv(e)}/meta`)}async function Qv(e,t){return await J.post(`${hv(e)}/generate`,t)}async function $v(e,t){let n=await _v(e,Fv),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 an Auto-Link.`);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 vv(e,Fv,JSON.stringify(o,null,2)+`
|
|
18
18
|
`)}function ey({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let u=al(),d=mv({workspaceId:n,treeName:r}),f=r===`backends`,p=f?fa(i):null,m=i.split(`/`).filter(Boolean).pop()||i,[h,g]=(0,X.useState)(void 0);(0,X.useEffect)(()=>{let e=!1;return _o(n).then(t=>{e||g(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||g(null)}),()=>{e=!0}},[n,r,i]);let _=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},v=(e,t,n,r=!1)=>(0,Z.jsxs)(`button`,{type:`button`,className:K(`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:()=>_(n),children:[e,t]}),y=(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),x=e=>{let t=f?(()=>{let t=Av(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:Nv(i)};u(`/workspaces/${n}/settings/hooks?${Mv(t).toString()}`)},S=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},C=rv(r,i);return C?(0,Z.jsxs)(If,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[v((0,Z.jsx)(lt,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),C.backend&&v((0,Z.jsx)(He,{className:`h-3 w-3`}),`Restore original paths`,()=>dv(n,i)),C.backend&&v((0,Z.jsx)(lt,{className:`h-3 w-3`}),`Empty Trash`,()=>pv(n,i),!0)]}):(0,Z.jsxs)(If,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[v((0,Z.jsx)(ke,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&v((0,Z.jsx)(Vt,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),y,f?p&&(0,Z.jsxs)(Z.Fragment,{children:[v((0,Z.jsx)(U,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=S(`New folder name:`);e&&await d.onCreateBackendFolder?.(i,e)}),p.key&&v((0,Z.jsx)(_r,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=S(`New folder name:`,m);e&&await d.onRenameBackendFolder?.(i,e)}),v((0,Z.jsx)(hr,{className:`w-3 h-3`}),`Create storage rule…`,()=>x(`store`))]}):(0,Z.jsxs)(Z.Fragment,{children:[v((0,Z.jsx)(U,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=S(`New folder name:`);e&&await d.onInsertPath(`${i===`/`?``:i}/${e}`)}),v((0,Z.jsx)(_r,{className:`w-3 h-3`}),`Rename`,async()=>{let e=S(`New name:`,m);e&&await d.onRenamePath(i,e)}),v((0,Z.jsx)(hr,{className:`w-3 h-3`}),`Create rule…`,()=>x(`store`)),v((0,Z.jsx)(er,{className:`w-3 h-3`}),`Create download rule…`,()=>x(`download`))]}),h!==void 0&&v(h?(0,Z.jsx)(V,{className:`w-3 h-3`}):(0,Z.jsx)(R,{className:`w-3 h-3`}),h?`Unpin`:`Pin`,async()=>{h?await xa(n,h.id):await gi(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),y,v((0,Z.jsx)(Ve,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!f&&l&&c&&c.length>0&&v((0,Z.jsx)(b,{className:`w-3 h-3`}),`Paste ${c.length} document(s)`,()=>l(i,c)),f?p?.key&&(0,Z.jsxs)(Z.Fragment,{children:[y,v((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Delete folder`,async()=>{confirm(`Delete folder "${m}" and its contents from the backend?`)&&await d.onDeleteBackendFolder?.(i)},!0)]}):(0,Z.jsxs)(Z.Fragment,{children:[y,v((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}"?`)&&await d.onRemovePath(i,!1)},!0),v((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${i}" and all children?`)&&await d.onRemovePath(i,!0)},!0)]})]})}function ty({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,X.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map(e=>({schema:e.schema,schemaVersion:e.schemaVersion,data:e.data,metadata:e.metadata})),l=JSON.stringify(c,null,2),u=async()=>{try{await navigator.clipboard.writeText(l),a(`copied`),setTimeout(()=>a(`idle`),2e3)}catch(e){console.error(`Failed to copy to clipboard:`,e),a(`error`),setTimeout(()=>a(`idle`),2e3)}};return(0,Mf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,Z.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,Z.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsx)(`div`,{className:`space-y-4`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,Z.jsxs)(Y,{onClick:u,size:`sm`,className:`flex items-center gap-2`,children:[(0,Z.jsx)(Ve,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,Z.jsx)(`textarea`,{className:`w-full h-96 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&u()}},onFocus:e=>e.target.select()})]})}),(0,Z.jsx)(`div`,{className:`mt-8 pt-4 border-t flex justify-end`,children:(0,Z.jsx)(Y,{onClick:o,children:`Close`})})]})})}),window.document.body)}function ny({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e.schema||!e.data){c(`Each document must have "schema" and "data" fields`);return}o(!0),await n(a)?(i(``),t()):c(`Failed to import documents`)}catch{c(`Invalid JSON format`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,Mf.createPortal)((0,Z.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 bg-scrim flex items-center justify-center z-50 p-4 max-md:p-2`,children:(0,Z.jsx)(`div`,{className:`bg-background border rounded-lg max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,Z.jsxs)(`div`,{className:`p-6`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data containing documents to import`})]}),(0,Z.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,Z.jsx)(`textarea`,{value:r,onChange:e=>i(e.target.value),className:`w-full h-64 p-3 border rounded-lg font-mono text-sm`,placeholder:`[{"schema": "data/schema/tab", "schemaVersion": "2.0", "data": {...}, "metadata": {...}}]`,disabled:a,autoFocus:!0})]}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,Z.jsxs)(`p`,{children:[(0,Z.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,Z.jsx)(Y,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,Z.jsx)(Y,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function ry({document:e}){let{replicating:t,label:n}=xo(e);return t?(0,Z.jsxs)(`span`,{role:`status`,className:`inline-flex shrink-0 items-center gap-1 rounded-full border bg-muted/60 px-2 py-0.5 text-[11px] font-normal text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),n]}):null}function iy(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Gf(e.currentTarget,`inside`)}function ay({documentId:e,onOpenActions:t,className:n}){return t?(0,Z.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,Z.jsx)(gt,{className:`h-4 w-4`})}):null}function oy(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function sy({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Af(),[c,l]=(0,X.useState)(!1),{replicating:u}=xo(e),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=Ui(e),m=ly(e),h=m||dy(e),{blobUrl:g}=nh(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(bm,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>oy(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,Z.jsx)(Sm,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:!!t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}})}),(0,Z.jsx)(Sm,{className:`w-12`,children:g?(0,Z.jsx)(`img`,{src:g,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,Z.jsx)(Dp,{document:e,chip:!0})}),(0,Z.jsx)(Sm,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),p.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(ry,{document:e})]}),p.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,Z.jsx)(Sm,{className:`hidden md:table-cell`,children:(0,Z.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:p.schemaLabel})}),(0,Z.jsx)(Sm,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,Z.jsx)(Sm,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:y&&(0,Z.jsx)(`span`,{className:`font-mono`,title:`${y.algo} checksum`,children:y.hash})}),(0,Z.jsx)(Sm,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,Z.jsx)(Sm,{className:`w-12 text-right`,children:(0,Z.jsx)(ay,{documentId:e.id,onOpenActions:a})})]}),(0,Z.jsx)(N_,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function cy({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Af(),[c,l]=(0,X.useState)(!1),u=e.schema===`data/schema/tab`,{replicating:d}=xo(e),f=u?e.data.url:null,p=Ui(e),m=ly(e),h=m||dy(e),{blobUrl:g,loading:_}=nh(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>oy(n,()=>u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`border rounded-lg 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,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[h&&(0,Z.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:g?(0,Z.jsx)(`img`,{src:g,alt:p.title,loading:`lazy`,className:`h-full w-full object-cover`}):_?(0,Z.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(Dp,{document:e})})}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,Z.jsx)(Dp,{document:e,chip:!0}),(0,Z.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:p.title,children:p.title}),p.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Z.jsx)(`span`,{className:`px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:p.schemaLabel}),(0,Z.jsx)(ry,{document:e})]}),p.subtitle&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:p.subtitle,children:p.subtitle}),p.preview&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:p.preview}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Z.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),b&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(Ne,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{className:`font-mono`,title:`${b.algo} checksum`,children:b.hash})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Z.jsx)(he,{className:`h-3 w-3`}),(0,Z.jsx)(`span`,{title:`Created: ${y(e.createdAt)}`,children:y(e.createdAt)})]})]})]}),(0,Z.jsx)(ay,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,Z.jsx)(N_,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function ly(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function uy(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function dy(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function fy({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Po(e,t),[a,o]=(0,X.useState)(!1);return i||a?(0,Z.jsx)(Z.Fragment,{children:n}):r?(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,Z.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,Z.jsx)(De,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function py({document:e,workspaceId:t,markdown:n}){let r=(0,X.useRef)(null),[i,a]=(0,X.useState)(()=>typeof IntersectionObserver>`u`);(0,X.useEffect)(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(a(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let{text:o,loading:s,error:c}=Ao(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,Z.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,Z.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,Z.jsx)(dh,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,Z.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,Z.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,Z.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,Z.jsx)(Dp,{document:e,size:10,chip:!0}),i&&s&&(0,Z.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function my({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let c=Af(),[l,u]=(0,X.useState)(!1),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=ly(e),m=uy(e),h=p||dy(e),g=Ui(e),_=xi(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||ri(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}=xo(e),{blobUrl:x,loading:S}=nh(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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>oy(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-lg 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,Z.jsx)(`input`,{type:`checkbox`,className:`absolute left-2 top-2 z-10 h-4 w-4 cursor-pointer accent-primary ${t?``:`reveal-on-hover`}`,checked:t,onClick:t=>{t.stopPropagation(),r?.(e.id,t.currentTarget.checked,!0,t.shiftKey)},onChange:()=>{}}),(0,Z.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${h&&x||y||v&&n||m&&n?``:`aspect-square`}`,children:[h&&S&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),h&&x?(0,Z.jsx)(`img`,{src:x,alt:g.title,loading:`lazy`,className:`block h-auto w-full`}):m&&n?(0,Z.jsx)(fy,{workspaceId:n,documentId:e.id,fallback:(0,Z.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,Z.jsx)(Dp,{document:e,size:10,chip:!0})})}):v&&n?(0,Z.jsx)(py,{document:e,workspaceId:n,markdown:_===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):y?(0,Z.jsxs)(`div`,{className:`flex min-h-28 w-full flex-col gap-1.5 overflow-hidden bg-card p-3 pt-7 text-left`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(Dp,{document:e}),(0,Z.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:g.schemaLabel})]}),(0,Z.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:g.title}),g.subtitle&&(0,Z.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:g.subtitle}),(0,Z.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:g.preview})]}):(0,Z.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Z.jsx)(Dp,{document:e,size:10,chip:!0})}),(0,Z.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,Z.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,Z.jsx)(se,{className:`h-3.5 w-3.5`})}),o&&(0,Z.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,Z.jsx)(gt,{className:`h-3.5 w-3.5`})})]})]}),!y&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:g.title,children:g.title}),g.isExternal&&(0,Z.jsx)(gn,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,Z.jsx)(N_,{document:e,isOpen:l,onClose:()=>u(!1),workspaceId:n})]})}function hy(e,t,n,r){let[i,a]=(0,X.useState)(!1),o=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:i,onDragOver:e=>{!t||!o(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,i||a(!0))},onDragLeave:()=>a(!1),onDrop:async i=>{if(a(!1),!t||!o(i))return;i.preventDefault(),i.stopPropagation();let s=null;try{s=JSON.parse(i.dataTransfer.getData(`application/json`))}catch{s=null}if(!(s?.type!==`document`||!Array.isArray(s.documentIds)||s.documentIds.length===0))try{await t(e.path,s.documentIds,{move:!1,sourcePath:s.sourcePath??n,sourceTreeName:s.sourceTreeName??r})}catch{}}}}function gy(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function _y({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,Z.jsx)(O,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,Z.jsx)(me,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var vy=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function yy({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a}){let o=hy(e,r,i,a);return(0,Z.jsxs)(`button`,{type:`button`,title:vy(e),onClick:()=>t?.(e.path),onContextMenu:t=>gy(t,e,n),onDragOver:o.onDragOver,onDragLeave:o.onDragLeave,onDrop:o.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 ${o.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,Z.jsx)(_y,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,Z.jsx)(O,{className:`hidden h-4 w-4 group-hover:block`}):(0,Z.jsx)(ke,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function by({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a}){let o=hy(e,r,i,a),s=e.color?{color:e.color}:void 0;return(0,Z.jsxs)(`button`,{type:`button`,title:vy(e),onClick:()=>t?.(e.path),onContextMenu:t=>gy(t,e,n),onDragOver:o.onDragOver,onDragLeave:o.onDragLeave,onDrop:o.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-lg border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${o.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,Z.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,Z.jsx)(O,{className:`h-10 w-10`,strokeWidth:1.5}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(me,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:s}),(0,Z.jsx)(ke,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:s})]})}),(0,Z.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function xy({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-4 grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-3 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(by,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a},e.path))})}function Sy({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a}){return e.length===0?null:(0,Z.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Z.jsx)(yy,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a},e.path))})}function Cy({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a}){let o=hy(e,r,i,a);return(0,Z.jsxs)(bm,{className:`cursor-pointer ${o.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:t=>gy(t,e,n),onDragOver:o.onDragOver,onDragLeave:o.onDragLeave,onDrop:o.onDrop,title:vy(e),children:[(0,Z.jsx)(Sm,{className:`w-10`}),(0,Z.jsx)(Sm,{className:`w-12`,children:(0,Z.jsx)(_y,{folder:e})}),(0,Z.jsx)(Sm,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,Z.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,Z.jsx)(Sm,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,Z.jsx)(Sm,{className:`hidden lg:table-cell`}),(0,Z.jsx)(Sm,{className:`hidden lg:table-cell`}),(0,Z.jsx)(Sm,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,Z.jsx)(Sm,{className:`w-12 md:w-auto`})]})}function wy({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,Z.jsxs)(`div`,{className:`sticky top-0 z-10 -mx-1 mb-2 flex items-center gap-2 bg-background/95 px-1 py-1.5 backdrop-blur-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 cursor-pointer accent-primary ${r||i?``:`reveal-on-hover`}`,checked:r,ref:e=>{e&&(e.indeterminate=i&&!r)},onChange:e=>o(e.target.checked),title:`Select everything in "${e}"`,onClick:e=>e.stopPropagation()}),(0,Z.jsxs)(`button`,{type:`button`,onClick:a,"aria-expanded":!n,className:`flex min-w-0 items-center gap-1.5 text-left text-muted-foreground transition-colors hover:text-foreground`,children:[(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,Z.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,Z.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function Ty({documents:e,isLoading:t,contextPath:n,treeName:r,workspaceId:i,totalCount:a,onRemoveDocument:o,onDeleteDocument:s,onDestroyDocument:c,onRemoveDocuments:l,onDeleteDocuments:u,onDestroyDocuments:d,onCopyDocuments:f,onCutDocuments:p,onPasteDocuments:m,onImportDocuments:h,onSelectionChange:g,pastedDocumentIds:_,viewMode:v=`card`,allowViewToggle:y=!1,activeContextUrl:x,currentContextUrl:S,currentPage:C=1,pageSize:T=50,onPageChange:E,onPageSizeChange:D,onPurgeDocuments:O,disablePurgeDocuments:A=!1,backendSearchQueries:j=[],onBackendSearch:M,onRemoveBackendQuery:N,serverSort:P,onServerSortChange:ee,scope:F=`path`,onScopeChange:I,canSaveChanges:L=!1,isSavingChanges:R=!1,onSaveChanges:ne,linkTree:z,folders:re,onOpenFolder:ie}){let[B,ce]=(0,X.useState)(()=>{if(!y)return v;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return v}),V=y?B:v,le=(0,X.useCallback)(e=>{ce(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[ue,de]=(0,X.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),fe=(0,X.useCallback)(()=>{de(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[pe,me]=(0,X.useState)(new Set),he=(0,X.useCallback)(e=>{me(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[_e,ve]=(0,X.useState)(new Set),[ye,H]=(0,X.useState)(null),[be,xe]=(0,X.useState)(null),Se=Uo(),Ce=!!(Se&&i),W=(0,X.useCallback)(t=>{if(!Se||!i)return;let n=t.map(t=>e.find(e=>e.id===t)).filter(e=>!!e);n.length!==0&&Se.openAddRelated({workspaceName:i,documents:n})},[Se,i,e]),[G,we]=(0,X.useState)(!1),[Te,Ee]=(0,X.useState)(null),[De,Oe]=(0,X.useState)(!1),[ke,Ae]=(0,X.useState)(!1),[je,Ne]=(0,X.useState)(null),[Pe,Ie]=(0,X.useState)(null),Le=Lo()==null&&!!i,[Re,ze]=(0,X.useState)(null),Be=!!(z&&m),He=!!i,{showSuccessToast:Ue,showErrorToast:We}=Wr(),Ge=hm(),Ke=i?e=>Ge.open(e,i):void 0,qe=F===`workspace`,Je=qe?void 0:o,Xe=qe?void 0:l,[Ze,Qe]=(0,X.useState)(!1),[$e,et]=(0,X.useState)(!1),[tt,nt]=(0,X.useState)(``),[rt,it]=(0,X.useState)(!1),at=j.length>0,ot=(0,X.useRef)(null),st=(0,X.useCallback)(()=>{nt(``),ot.current&&(ot.current.value=``)},[]);(0,X.useEffect)(()=>{if(!y||window.matchMedia(`(max-width: 767px)`).matches)return;let e=ot.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[y]);let ct=JSON.stringify([i,r,n]),[ut,dt]=(0,X.useState)(ct);ct!==ut&&(dt(ct),ve(new Set),Ee(null),xe(null),H(null)),(0,X.useEffect)(()=>{let e=()=>{Be&&_e.size>0&&xe(Array.from(_e))};return window.addEventListener(`workspace:documents:link-selection`,e),()=>window.removeEventListener(`workspace:documents:link-selection`,e)},[Be,_e]),(0,X.useEffect)(()=>{g?.(Array.from(_e))},[_e,g]);let ft=(0,X.useCallback)(()=>{if(!M)return;let e=tt.trim();e&&(M(e),st())},[M,tt,st]),pt=(0,X.useCallback)(()=>{st(),N&&j.length>0&&N(-1)},[N,j.length,st]),mt=(0,X.useCallback)((e,t)=>{let i;_e.has(t)&&_e.size>1?i=Array.from(_e):(i=[t],ve(new Set([t])));let a={type:`document`,documentIds:i,sourcePath:n,sourceTreeName:r};e.dataTransfer.setData(`application/json`,JSON.stringify(a)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[_e,n,r]),gt=(0,X.useCallback)(async e=>{if(!m)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let r=null;try{r=JSON.parse(t)}catch{return}r?.type!==`document`||!Array.isArray(r.documentIds)||r.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),it(!1),await m(n,r.documentIds,{move:e.shiftKey,sourcePath:r.sourcePath,sourceTreeName:r.sourceTreeName}),ve(new Set))},[n,m]),_t=(0,X.useCallback)(e=>{m&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,it(!0))},[m]),vt=(0,X.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||it(!1)},[]),yt=(0,X.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2},{name:`schema`,weight:.1}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),xt=(0,X.useMemo)(()=>e.length===0?null:new Oo(e,yt),[e,yt]),St=(0,X.useDeferredValue)(tt),Ct=(0,X.useMemo)(()=>{if(!St.trim())return e;let{text:t,ids:n,invalid:r}=Df(St);if(r)return[];let i=t&&xt?xt.search(t).map(e=>e.item):e;return n.length?i.filter(e=>n.every(t=>e.id===t)):i},[e,St,xt]),wt=(0,X.useMemo)(()=>{if(!re||re.length===0||St.trim())return[];let e=P?.order===`desc`?-1:1;return[...re].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)},[re,St,P?.order]),Tt=wt.length>0,[Et,Dt]=(0,X.useState)(null),kt=(0,X.useMemo)(()=>i&&r&&ie?(e,t)=>Dt({x:t.clientX,y:t.clientY,path:e}):void 0,[i,r,ie]),At={folders:wt,onOpen:ie,onMenu:kt,onPasteDocuments:m,contextPath:n,treeName:r},{sorted:Mt,sort:Nt,toggleSort:Pt}=Tm(Ct,(0,X.useMemo)(()=>({title:e=>Ui(e).title?.toLowerCase()??``,schema:e=>Ui(e).schemaLabel??``,type:ua,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),Ft=(0,X.useCallback)(e=>{let t=P?.sortBy===`crud:updated`?e.updatedAt:e.createdAt,n=Date.parse(t??``);return Number.isNaN(n)?null:n},[P?.sortBy]),It=(0,X.useMemo)(()=>nv(Ct,Ft,P?.order===`asc`?`asc`:`desc`),[Ct,Ft,P?.order]),Lt=ue&&!Bi(P?.sortBy)&&It.length>1,zt=(0,X.useCallback)((e,t)=>{ve(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),Bt=(0,X.useMemo)(()=>(V===`table`?Mt:Lt?It.filter(e=>!pe.has(e.key)).flatMap(e=>e.items):Ct).map(e=>e.id),[V,Mt,Lt,It,pe,Ct]),Ht=(0,X.useRef)(null),Ut=JSON.stringify([i,n,r,C]),Wt=(0,X.useCallback)((e,t,n,r=!1)=>{let i=Ht.current,a=i?.scope===Ut&&Bt.includes(i.id)?i.id:null;(!r||a===null)&&(Ht.current={scope:Ut,id:e}),ve(i=>{if(r)return jf(Bt,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[Ut,Bt]),qt=(0,X.useCallback)((e,t)=>{let n;_e.has(e)?n=Array.from(_e):(n=[e],ve(new Set([e]))),H({anchor:t,ids:n})},[_e]),Jt=(0,X.useCallback)((e,t)=>{qt(t,Gf(e))},[qt]),Yt=(0,X.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),qt(t,iy(e)))},[qt]),Zt=(0,X.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){we(!0);try{for(let n of t)await Ca(i,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;Ue(`Created ${n} relation${n===1?``:`s`}`),Dm(),xe(null)}catch(e){We(e instanceof Error?e.message:`Failed to create relations`)}finally{we(!1)}}},[i,Ue,We]),Qt=(0,X.useCallback)(async(e,t,n)=>{if(m){for(let r of e)await m(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});ve(new Set)}},[m]),$t=(0,X.useCallback)(async(t,n,r)=>{if(!(!i||!Te)){Oe(!0);try{let a=await La(i,Te.ids,{to:t,mode:n,keepDocument:r.keepDocument,folder:r.folder,filename:r.filename,onConflict:r.onConflict}),o=a.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,s=a.successful.length-o,c=a.failed.length,l=n===`delete`?`Deleted from`:n===`move`?`Moved to`:`Copied to`,u=t.join(`, `),d=[o?`${o} already there`:null,c?`${c} skipped`:null].filter(Boolean).join(` · `);s>0?Ue(`${l} ${u}: ${s} document${s===1?``:`s`}${d?` · ${d}`:``}`):o>0&&Ue(`Nothing to do — already on ${u}`),c>0&&(We(Of(a.failed,new Map(e.map(e=>[e.id,Ui(e).title]))),`${c} file${c===1?``:`s`} skipped`),console.warn(`Backend transfer skipped documents:`,a.failed)),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`));let f=a.failed.map(e=>e.id);Ee(f.length?{ids:f,mode:n}:null),ve(new Set(f))}catch(e){We(e instanceof Error?e.message:String(e))}finally{Oe(!1)}}},[i,Te,e,Ue,We]),en=(0,X.useCallback)(()=>{_e.size===Ct.length?ve(new Set):ve(new Set(Ct.map(e=>e.id)))},[_e.size,Ct]),tn=(0,X.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)}},[]),rn=t=>{if(t.length===0)return[];let n=t.length,r=n>1?` (${n})`:``,i=n===1?e.find(e=>e.id===t[0]):void 0,a=()=>ve(new Set),o=t.some(t=>(e.find(e=>e.id===t)?.locations?.length??0)>0),l=[],m=e=>{e&&l.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;m({id:`view`,group:`open`,label:`View details`,icon:Vt,run:()=>ze({document:i})}),m(Qg(i)&&Le&&{id:`edit`,group:`open`,label:`Edit`,icon:Fe,run:()=>ze({document:i,edit:!0})}),m(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:gn,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),m(Ke&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:se,run:()=>Ke(i)})}return m(f&&{id:`copy`,group:`clipboard`,label:`Copy${r}`,icon:Ve,shortcut:`Mod+C`,run:()=>f(t)}),m(p&&{id:`cut`,group:`clipboard`,label:`Cut${r}`,icon:lr,shortcut:`Mod+X`,run:()=>p(t)}),m(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:Xt,run:()=>tn(String(i.id))}),m(Be&&{id:`link-to`,group:`organize`,label:`Link to…${r}`,icon:Gt,run:()=>xe(t)}),m(Ce&&{id:`add-related`,group:`organize`,label:`Add related document…${r}`,icon:U,run:()=>W(t)}),m(Le&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${r}`,icon:Fe,run:()=>Ie(t)}),m(Le&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:Ve,run:()=>Ne(t)}),m({id:`export`,group:`organize`,label:`Export…${r}`,icon:er,run:()=>Qe(!0)}),m((Je||Xe)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${r}`,icon:ge,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{n===1&&Je?Je(t[0]):Xe?.(t),a()}}),m((s||u)&&{id:`delete`,group:`remove`,label:`Delete from index${r}`,icon:lt,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{n===1&&s?s(t[0]):u?.(t),a()}}),o&&He?(m({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${r}`,icon:hr,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Ee({ids:t,mode:`copy`})}),m({id:`backend-move`,group:`backends`,label:`Move to backend…${r}`,icon:jt,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Ee({ids:t,mode:`move`})}),m({id:`backend-delete`,group:`backends`,label:`Delete from backend…${r}`,icon:lt,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Ee({ids:t,mode:`delete`})})):o&&(c||d)&&m({id:`destroy`,group:`backends`,label:`Delete from backend(s)${r}`,icon:lt,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{n===1&&c?c(t[0]):d?.(t),a()}}),l},an=()=>{let t=[],r=e=>{e&&t.push(e)},i=_??[];return r(m&&i.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${i.length})`,icon:b,shortcut:`Mod+V`,run:async()=>{try{await m(n,i)}catch(e){console.error(`Failed to paste documents:`,e)}}}),r(Ct.length>0&&{id:`select-all`,group:`select`,label:tt?`Select all matches (${Ct.length})`:`Select all on this page`,icon:Tn,shortcut:`Mod+A`,run:()=>ve(new Set(Ct.map(e=>e.id)))}),r(_e.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:nn,run:()=>ve(new Set)}),r(m&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:Ot,hint:`Browse and add existing documents to this folder`,run:()=>Ae(!0)}),r(h&&{id:`import`,group:`add`,label:`Import…`,icon:te,run:()=>et(!0)}),r(e.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:er,run:()=>{ve(new Set),Qe(!0)}}),r(O&&a>0&&{id:`purge`,group:`purge`,label:`Purge all (${a})`,icon:lt,destructive:!0,disabled:A||!!tt,hint:A||tt?`Purge is disabled while local search is active`:`Delete all documents matching the current server-side filters across all pages`,run:O}),t},on=!!(ee&&P&&i),sn=ye?ye.ids?rn(ye.ids):an():[],cn=ye?.ids?.length===1?e.find(e=>e.id===ye.ids[0]):void 0,ln=cn?(0,Z.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Z.jsx)(Dp,{document:cn,chip:!0}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Ui(cn).title}),(0,Z.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,cn.id,` · `,cn.schema]})]})]}):(0,Z.jsx)(`div`,{className:`truncate text-base font-semibold`,children:ye?.ids?`${ye.ids.length} documents`:`This folder`}),un=e=>{H({anchor:Gf(e.currentTarget),ids:_e.size>0?Array.from(_e):null})},dn=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),ve(new Set),H({anchor:iy(e),ids:null}))},fn=e=>{if(e.defaultPrevented||Vf(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Uf(e)){e.preventDefault(),t?qt(Number(t.dataset.documentId),Gf(t,`inside`)):H({anchor:Gf(e.target,`inside`),ids:_e.size>0?Array.from(_e):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&&Wt(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&_e.size>0){e.preventDefault(),ve(new Set);return}Hf(e,[...rn(Array.from(_e)),...an()])},pn=(0,X.useCallback)(async e=>{if(!h)return!1;try{return await h(e,n)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[h,n]),mn=e=>Lt?It.map(t=>{let n=pe.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!_e.has(t),0);return(0,Z.jsxs)(`section`,{className:`group mb-4`,children:[(0,Z.jsx)(wy,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>he(t.key),onSelectAll:e=>zt(r,e)}),!n&&e(t.items)]},t.key)}):e(Ct);return t?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})}):(0,Z.jsxs)(`div`,{tabIndex:-1,onKeyDown:fn,className:`flex-1 flex flex-col min-h-0 p-4 rounded-lg outline-none transition-colors ${rt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:_t,onDragLeave:vt,onDrop:gt,children:[(0,Z.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,Z.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:tt?`${Ct.length} of ${e.length}`:`${a.toLocaleString()} document${a===1?``:`s`}`})]}),(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsxs)(`p`,{className:`min-w-0 truncate`,children:[`Context: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n}),x&&S&&x!==S&&(0,Z.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,Z.jsxs)(`p`,{className:`shrink-0`,children:[_e.size>0&&(0,Z.jsxs)(`span`,{className:`text-info`,children:[_e.size,` selected`]}),_e.size>0&&(tt||a>T)&&(0,Z.jsx)(`span`,{className:`mx-1`,children:`·`}),tt?`on this page`:a>T?`Showing ${Math.min((C-1)*T+1,a)}–${Math.min(C*T,a)}`:null]})]})]}),(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[I&&(0,Z.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>I(`path`),className:`px-2.5 py-2 transition-colors ${F===`path`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List documents in the selected path`,children:`This path`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>I(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${F===`workspace`?`bg-primary text-primary-foreground`:`bg-background text-muted-foreground hover:text-foreground hover:bg-muted`}`,title:`List every document in the workspace (staging excluded)`,children:[(0,Z.jsx)(ae,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),y&&(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,Rt,`Table view`],[`tile`,dr,`Tile view`],[`card`,ht,`Card view`]].map(([e,t,n])=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>le(e),title:n,"aria-pressed":V===e,className:`rounded-sm p-1.5 transition-colors ${V===e?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(t,{className:`h-4 w-4`})},e))}),y&&V!==`table`&&!Bi(P?.sortBy)&&(0,Z.jsx)(`button`,{type:`button`,onClick:fe,title:ue?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":ue,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors ${ue?`bg-accent text-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Z.jsx)(Nn,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,Z.jsx)(pr,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,Z.jsx)(`input`,{ref:ot,type:`text`,placeholder:M?at?`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=>nt(e.target.value),onFocus:e=>{let t=e.currentTarget;window.matchMedia(`(max-width: 767px)`).matches&&setTimeout(()=>t.scrollIntoView({block:`center`,behavior:`smooth`}),250)},onKeyDown:e=>{e.key===`Enter`&&M&&(e.preventDefault(),ft())},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`}),(tt||at)&&(0,Z.jsx)(`button`,{onClick:pt,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),M&&tt.trim()&&!j.includes(tt.trim())&&(0,Z.jsxs)(Y,{size:`sm`,variant:`default`,onClick:ft,className:`shrink-0`,title:at?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,Z.jsx)(pr,{className:`h-3.5 w-3.5 mr-1`}),at?`Refine`:`Search server`]}),L&&ne&&(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:ne,disabled:R,className:`shrink-0`,title:`Save current query and filters`,children:[(0,Z.jsx)(k,{className:`h-3.5 w-3.5 mr-1`}),R?`Saving...`:`Save filters`]})]}),at&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),j.map((e,t)=>(0,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),N&&(0,Z.jsx)(`button`,{onClick:()=>N(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,Z.jsx)(Me,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),N&&j.length>1&&(0,Z.jsx)(`button`,{onClick:()=>N(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(E&&a>0||on)&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mt-3 pt-3 border-t max-sm:gap-1`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground`,children:[E&&a>0&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Show:`}),(0,Z.jsxs)(`select`,{value:T,onChange:e=>D?.(Number(e.target.value)),className:`h-control-sm rounded-(--input-radius) border-(length:--input-border-width) border-input bg-background px-2 text-sm focus-ring`,"aria-label":`Documents per page`,children:[(0,Z.jsx)(`option`,{value:25,children:`25`}),(0,Z.jsx)(`option`,{value:50,children:`50`}),(0,Z.jsx)(`option`,{value:100,children:`100`}),(0,Z.jsx)(`option`,{value:200,children:`200`})]}),(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`per page`})]}),on&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs max-sm:sr-only`,children:`Sort`}),(0,Z.jsx)(q_,{workspaceId:i,value:P,onChange:ee})]})]}),E&&a>0&&(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 max-sm:gap-0.5`,children:[(0,Z.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((C-1)*T+1,a),` - `,Math.min(C*T,a),` of `,a]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>E(1),disabled:C===1,className:`p-1 touch-target`,children:(0,Z.jsx)(w,{className:`h-4 w-4`})}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>E(C-1),disabled:C===1,className:`p-1 touch-target`,children:(0,Z.jsx)(oe,{className:`h-4 w-4`})}),(0,Z.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),C,(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,Z.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(a/T)]}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>E(C+1),disabled:C>=Math.ceil(a/T),className:`p-1 touch-target`,children:(0,Z.jsx)(Ye,{className:`h-4 w-4`})}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>E(Math.ceil(a/T)),disabled:C>=Math.ceil(a/T),className:`p-1 touch-target`,children:(0,Z.jsx)(gr,{className:`h-4 w-4`})})]})]})]}),(e.length>0||h||m)&&(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 border-t pt-3`,children:[(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:un,"aria-haspopup":`menu`,className:`flex items-center gap-1.5`,title:`Actions (${zf(`Shift+F10`)} or right-click)`,children:[(0,Z.jsx)(Kt,{className:`h-4 w-4`}),`Actions`,_e.size>0?` (${_e.size} selected)`:``]}),_e.size>0&&(0,Z.jsxs)(Y,{variant:`ghost`,size:`sm`,onClick:()=>ve(new Set),title:`Clear selection (Esc)`,children:[(0,Z.jsx)(Me,{className:`mr-1 h-3.5 w-3.5`}),`Clear`]}),_&&_.length>0&&m&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:()=>m(n,_),className:`flex items-center gap-1.5`,title:`Paste into this folder (${zf(`Mod+V`)})`,children:[(0,Z.jsx)(b,{className:`h-4 w-4`}),`Paste (`,_.length,`)`]})]})]}),Ct.length===0&&!Tt?(0,Z.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,onContextMenu:dn,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(bt,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:tt?`No documents match your search`:`No documents found in this context`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:tt?(0,Z.jsxs)(Z.Fragment,{children:[`Search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,tt,`"`]})]}):(0,Z.jsxs)(Z.Fragment,{children:[`Path: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:n})]})}),tt&&(0,Z.jsx)(`button`,{onClick:st,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!tt&&_&&_.length>0&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,zf(`Mod+V`),` to paste `,_.length,` document(s)`]})]})}):V===`tile`?(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:dn,children:[(0,Z.jsx)(xy,{...At}),Ct.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),mn(e=>(0,Z.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,Z.jsx)(my,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Wt,onOpenToSide:Ke,onRightClick:Yt,onOpenActions:Jt,onDragStart:mt},e.id))}))]}):V===`table`?(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:dn,children:(0,Z.jsxs)(gm,{children:[(0,Z.jsx)(_m,{children:(0,Z.jsxs)(bm,{children:[(0,Z.jsx)(xm,{className:`w-10`,children:(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:Ct.length>0&&_e.size===Ct.length,ref:e=>{e&&(e.indeterminate=_e.size>0&&_e.size<Ct.length)},onChange:en,title:`Select all on this page`})}),(0,Z.jsx)(wm,{label:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:Nt,onSort:Pt,className:`w-12`}),(0,Z.jsx)(wm,{label:`Title`,sortKey:`title`,sort:Nt,onSort:Pt,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,Z.jsx)(wm,{label:`Schema`,sortKey:`schema`,sort:Nt,onSort:Pt,className:`hidden md:table-cell`}),(0,Z.jsx)(wm,{label:`ID`,sortKey:`id`,sort:Nt,onSort:Pt,className:`hidden lg:table-cell`}),(0,Z.jsx)(xm,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,Z.jsx)(wm,{label:`Created`,sortKey:`created`,sort:Nt,onSort:Pt,className:`hidden sm:table-cell`}),(0,Z.jsx)(xm,{className:`w-12 md:w-auto`,children:(0,Z.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,Z.jsxs)(vm,{children:[wt.map(e=>(0,Z.jsx)(Cy,{folder:e,onOpen:ie,onMenu:kt,onPasteDocuments:m,contextPath:n,treeName:r},e.path)),Mt.map(e=>(0,Z.jsx)(sy,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Wt,onOpenToSide:Ke,onRightClick:Yt,onOpenActions:Jt,onDragStart:mt},e.id))]})]})}):(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,onContextMenu:dn,children:[(0,Z.jsx)(Sy,{...At}),Ct.length===0&&(0,Z.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),mn(e=>(0,Z.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,Z.jsx)(`div`,{children:(0,Z.jsx)(cy,{document:e,isSelected:_e.has(e.id),workspaceId:i,onSelect:Wt,onOpenToSide:Ke,onRightClick:Yt,onOpenActions:Jt,onDragStart:mt})},e.id))}))]}),ye&&(0,Z.jsx)(Xf,{anchor:ye.anchor,items:sn,onClose:()=>H(null),label:ye.ids?`Document actions`:`Folder actions`,header:ln}),(0,Z.jsx)(ty,{isOpen:Ze,onClose:()=>Qe(!1),documents:e,selectedDocuments:_e}),(0,Z.jsx)(ny,{isOpen:$e,onClose:()=>et(!1),onImport:pn}),je&&i&&(0,Z.jsx)(Wp,{workspaceId:i,ids:je,onClose:()=>Ne(null)}),be&&z&&(0,Z.jsx)(Hp,{onClose:()=>xe(null),children:(0,Z.jsx)(Bp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,documentCount:be.length,fixedWorkspaceName:i,tabs:[`context`,`directory`,`relations`],saving:G,relationExcludeIds:new Set(be),onConfirm:(e,t)=>Qt(e,be,t),onConfirmRelation:e=>Zt(e,be),onClose:()=>xe(null)})}),Te&&i&&(0,Mf.createPortal)((0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Z.jsx)(dm,{workspaceId:i,documentCount:Te.ids.length,initialMode:Te.mode,defaultFilename:Te.ids.length===1?ri(e.find(e=>e.id===Te.ids[0])??{}):``,saving:De,onConfirm:$t,onClose:()=>{De||Ee(null)}})}),window.document.body),ke&&m&&(0,Mf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>Ae(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(fm,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:i,onConfirm:async e=>{await m(n,e),Ae(!1)},onClose:()=>Ae(!1)})})]}),window.document.body),Pe&&i&&(0,Z.jsx)(om,{workspaceId:i,documentIds:Pe,onClose:()=>Ie(null)}),(0,Z.jsx)(N_,{document:Re?.document??null,isOpen:!!Re,onClose:()=>ze(null),workspaceId:i,initialEdit:Re?.edit}),Et&&i&&r&&ie&&(0,Z.jsx)(ey,{x:Et.x,y:Et.y,workspaceName:i,treeName:r,path:Et.path,onClose:()=>Dt(null),onOpen:ie,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:i,treeName:r,path:e}})),pastedDocumentIds:_,onPasteDocuments:m?(e,t)=>m(e,t):void 0})]})}function Ey(e,t){let n=typeof e.setCanvasQueries==`function`,[r,i]=(0,X.useState)(e.canvasQueries??[]),a=(0,X.useMemo)(()=>n?e.canvasQueries??[]:r,[n,e.canvasQueries,r]),o=(0,X.useCallback)(r=>{n?e.setCanvasQueries(r):i(r),t?.()},[n,e,t]);return{queries:a,runSearch:(0,X.useCallback)(e=>{let t=e.trim();!t||a.includes(t)||o([...a,t])},[a,o]),removeQuery:(0,X.useCallback)(e=>{o(e<0?[]:a.filter((t,n)=>n!==e))},[a,o]),clearSearch:(0,X.useCallback)(()=>o([]),[o])}}function Dy({config:e,canvas:t}){let n=typeof e.pageSize==`number`?e.pageSize:50,r=e.viewMode===`card`||e.viewMode===`tile`||e.viewMode===`table`?e.viewMode:`table`,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(1),[u,d]=(0,X.useState)(!0),f=t.canvasSort??U_,{queries:p,runSearch:m,removeQuery:h}=Ey(t,()=>l(1));(0,X.useEffect)(()=>{let e=!1;return(async()=>{d(!0);try{let r=await t.fetchDocuments({limit:n,page:c,sortBy:f.sortBy,order:f.order,queries:p.length?p:void 0});if(e)return;a(r.payload||[]),s(r.totalCount||r.count||0)}catch{e||(a([]),s(0))}finally{e||d(!1)}})(),()=>{e=!0}},[t,n,c,f.sortBy,f.order,p]);let g=(0,X.useCallback)(e=>{t.setCanvasSort?.(e),l(1)},[t]),_=t.readOnly===!0;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!_&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 border-b px-1 pb-2`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Sort`}),(0,Z.jsx)(q_,{workspaceId:t.workspaceId,value:f,onChange:g})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,Z.jsx)(Ty,{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})})]})}wf({type:`documents-table`,name:`Documents`,icon:Rt,defaultSize:{w:8,h:6,minW:4,minH:3},mobileHeight:.9,defaultConfig:{pageSize:50,viewMode:`table`},component:Dy});function Oy({config:e,setConfig:t,canvas:n}){let[r,i]=(0,X.useState)(()=>new Date),a=e.format!==`24`;return(0,X.useEffect)(()=>{let e=setInterval(()=>i(new Date),1e3);return()=>clearInterval(e)},[]),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-1`,children:[(0,Z.jsx)(`div`,{className:`text-3xl font-semibold tabular-nums`,children:r.toLocaleTimeString(void 0,{hour12:a,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:r.toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`})}),!n.readOnly&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t({...e,format:a?`24`:`12`}),className:`mt-1 px-2 py-0.5 text-[10px] border rounded-md text-muted-foreground hover:bg-accent`,children:a?`12h`:`24h`})]})}wf({type:`clock`,name:`Clock`,icon:cn,defaultSize:{w:3,h:2,minW:2,minH:2},defaultConfig:{format:`24`},component:Oy});var ky=450,Ay=10;function jy(e,t){let{open:n}=i_(),r=(0,X.useRef)(null),i=(0,X.useRef)(null),a=(0,X.useRef)(!1),o=()=>{e&&n(e,t)},s=()=>{r.current&&=(clearTimeout(r.current),null)};return{activationProps:{role:`button`,tabIndex:0,onClick:()=>{if(a.current){a.current=!1;return}o()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())},onContextMenu:e=>{e.preventDefault(),o()},onPointerDown:e=>{e.pointerType===`touch`&&(i.current={x:e.clientX,y:e.clientY},a.current=!1,s(),r.current=setTimeout(()=>{a.current=!0,o()},ky))},onPointerMove:e=>{i.current&&Math.hypot(e.clientX-i.current.x,e.clientY-i.current.y)>Ay&&s()},onPointerUp:s,onPointerCancel:s,onPointerLeave:s},stopRowActivation:e=>e.stopPropagation()}}function My({doc:e,workspaceId:t}){let n=Ui(e),{activationProps:r}=jy(e,t);return(0,Z.jsxs)(`li`,{...r,title:`Open details`,className:`canvas-no-drag cursor-pointer py-1.5 min-w-0 rounded px-1 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(`div`,{className:`truncate font-medium`,children:n.title}),n.preview&&(0,Z.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:n.preview})]})}function Ny({config:e,canvas:t}){let n=typeof e.limit==`number`?e.limit:10,[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(!0),[s,c]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=!1;return(async()=>{o(!0);try{let r=await t.fetchDocuments({limit:n});if(e)return;i(r.payload||[]),c(null)}catch(t){if(e)return;c(t instanceof Error?t.message:`Failed to load documents`),i([])}finally{e||o(!1)}})(),()=>{e=!0}},[t,n]),a?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`Loading…`}):s?(0,Z.jsx)(`div`,{className:`text-xs text-destructive p-1`,children:s}):r.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground p-1`,children:`No documents on this canvas.`}):(0,Z.jsx)(`ul`,{className:`divide-y text-sm`,children:r.map(e=>(0,Z.jsx)(My,{doc:e,workspaceId:t.workspaceId},e.id))})}wf({type:`recent-documents`,name:`Recent documents`,icon:Bn,defaultSize:{w:4,h:4,minW:3,minH:2},mobileHeight:.5,defaultConfig:{limit:10},component:Ny});function Py({config:e,setConfig:t,canvas:n}){let r=typeof e.text==`string`?e.text:``;return(0,Z.jsx)(`textarea`,{value:r,readOnly:n.readOnly,onChange:n=>t({...e,text:n.target.value}),placeholder:n.readOnly?``:`Jot something down…`,className:`canvas-no-drag w-full h-full resize-none bg-transparent text-sm leading-6 outline-none`})}wf({type:`note`,name:`Note`,icon:xn,defaultSize:{w:3,h:3,minW:2,minH:2},defaultConfig:{text:``},component:Py});var Fy=`data/schema/file`,Iy=`data/schema/drawing`;function Ly(e){return(e.schema===Fy||e.schema===Iy)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Ry(e){return e.schema===Fy&&String(e.metadata?.contentType||``).startsWith(`video/`)}var zy=`data/mime/image`;function By(e,t,n=!1){let[r,i]=(0,X.useState)([]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(1),[l,u]=(0,X.useState)(!0),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{queries:h,runSearch:g,removeQuery:_,clearSearch:v}=Ey(e,()=>c(1)),y=e.canvasSort??U_;(0,X.useEffect)(()=>{let r=!1,a=async()=>{u(!0),f(null);try{let a=await e.fetchDocuments({limit:t,page:s,queries:h.length?h:void 0,sortBy:y.sortBy,order:y.order,...n?{anyOf:[zy,`data/mime/video`]}:{allOf:[zy]}});if(r)return;i((a.payload||[]).filter(e=>Ly(e)||n&&Ry(e))),o(a.totalCount||a.count||0)}catch(e){if(r)return;i([]),o(0),f(e instanceof Error?e.message:`Failed to load images`)}finally{r||u(!1)}};return a(),window.addEventListener(`workspace:documents:refresh`,a),()=>{r=!0,window.removeEventListener(`workspace:documents:refresh`,a)}},[e,t,s,h,y.sortBy,y.order,n]);let b=(0,X.useCallback)(()=>{let e=p.trim();m(``),g(e)},[p,g]),x=(0,X.useCallback)(()=>{m(``),v()},[v]),S=(0,X.useCallback)(e=>{_(e)},[_]),C=(0,X.useCallback)(t=>{e.setCanvasSort?.(t),c(1)},[e]);return{images:r,isLoading:l,error:d,page:s,setPage:c,totalCount:a,totalPages:(0,X.useMemo)(()=>Math.max(1,Math.ceil(a/t)),[a,t]),input:p,setInput:m,submit:b,clearSearch:x,removeQuery:S,activeQueries:h,sort:y,setSort:C}}function Vy({workspaceId:e,doc:t,onClick:n,className:r=`aspect-square`,comments:i=`off`}){let{blobUrl:a,error:o,loading:s}=nh(e,t.id,512,{blobFallback:!Ry(t),version:t.checksumArray?.[0]??null}),c=ri(t)||`image-${t.id}`,l=go(t),u=l!==``&&i!==`off`;return(0,Z.jsxs)(`button`,{type:`button`,onClick:n,title:l||c,className:`canvas-no-drag group relative block w-full overflow-hidden rounded-lg border bg-muted/40 shadow-elevation-1 transition-shadow hover:shadow-elevation-2 hover:ring-2 hover:ring-primary/30 ${r}`,children:[s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),o&&!Ry(t)&&(0,Z.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center p-1 text-[10px] text-destructive`,children:o}),a&&(0,Z.jsx)(`img`,{src:a,alt:c,loading:`lazy`,className:`h-full w-full object-cover transition-transform duration-200 group-hover:scale-105`}),Ry(t)&&(0,Z.jsxs)(`span`,{className:`absolute inset-0 flex items-center justify-center`,children:[(0,Z.jsx)(De,{className:`h-10 w-10 rounded-full bg-black/60 p-2 text-white`}),(0,Z.jsx)(`span`,{className:`sr-only`,children:`Play video`})]}),u&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute inset-x-0 bottom-0 px-1.5 pb-1 pt-4 text-left text-[11px] leading-snug text-white bg-gradient-to-t from-black/75 via-black/45 to-transparent ${i===`reveal`?`caption-reveal`:``}`,children:(0,Z.jsx)(`span`,{className:`line-clamp-2`,children:l})}),l!==``&&i!==`caption`&&(0,Z.jsx)(`span`,{className:`pointer-events-none absolute right-1 top-1 rounded-full bg-black/55 p-1 text-white transition-opacity ${i===`reveal`?`hidden [@media(hover:hover)]:block [@media(hover:hover)]:group-hover:opacity-0`:``}`,title:`Has a comment`,children:(0,Z.jsx)(v,{className:`h-3 w-3`})})]})}function Hy({workspaceId:e,docs:t,index:n,onClose:r,onNavigate:i}){let a=t[n],{blobUrl:o,error:s,loading:c}=Ao(e,a.id,{version:a.checksumArray?.[0]??null,enabled:!Ry(a)}),l=ri(a)||`image-${a.id}`,u=go(a),[d,f]=(0,X.useState)(!1);return Ff(r),(0,X.useEffect)(()=>{let e=e=>{e.target?.closest(`video`)||(e.key===`ArrowLeft`&&n>0&&i(n-1),e.key===`ArrowRight`&&n<t.length-1&&i(n+1))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,t.length,i]),(0,Mf.createPortal)((0,Z.jsxs)(`div`,{"data-scheme":`dark`,className:`fixed inset-0 z-fullscreen flex flex-col bg-scrim p-0 sm:p-4`,onClick:r,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:r,className:`canvas-no-drag absolute right-2 top-2 z-10 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20 touch-target sm:right-4 sm:top-4`,title:`Close`,children:(0,Z.jsx)(Me,{className:`h-5 w-5`})}),n>0&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n-1)},className:`canvas-no-drag absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Previous`,children:(0,Z.jsx)(oe,{className:`h-6 w-6 touch-target`})}),n<t.length-1&&!d&&(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i(n+1)},className:`canvas-no-drag absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-foreground/10 p-2 text-foreground hover:bg-foreground/20`,title:`Next`,children:(0,Z.jsx)(Ye,{className:`h-6 w-6 touch-target`})}),(0,Z.jsxs)(`figure`,{className:`flex min-h-0 flex-1 flex-col`,onClick:e=>e.stopPropagation(),children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center`,children:[c&&(0,Z.jsx)(`div`,{className:`text-sm text-foreground/70`,children:`Loading…`}),s&&(0,Z.jsx)(`div`,{className:`text-sm text-destructive`,children:s}),Ry(a)&&(0,Z.jsx)(Wy,{workspaceId:e,doc:a},a.id),o&&(0,Z.jsx)(Wm,{src:o,alt:l,onZoomChange:f,className:`max-h-full max-w-full rounded object-contain`})]}),(0,Z.jsxs)(`figcaption`,{className:`shrink-0 px-4 py-2 text-center text-xs text-foreground/70`,children:[u&&(0,Z.jsx)(`span`,{className:`mx-auto mb-1 block max-w-2xl whitespace-pre-wrap text-sm text-foreground`,children:u}),l,` · `,n+1,`/`,t.length,!d&&!Ry(a)&&(0,Z.jsx)(`span`,{className:`ml-2 opacity-70`,children:`· double-tap to zoom`})]})]})]}),document.body)}function Uy({workspaceId:e,state:t,comments:n,onToggleComments:r}){let{input:i,setInput:a,submit:o,clearSearch:s,removeQuery:c,activeQueries:l,sort:u,setSort:d,page:f,setPage:p,totalPages:m,totalCount:h,isLoading:g}=t,_=l.length>0;return(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b px-1 pb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-[9rem] flex-1 basis-full sm:basis-auto`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()},placeholder:_?`Refine: add another query (Enter)…`:`Search media (Enter)…`,className:`h-7 w-full rounded-md border bg-background pl-7 pr-7 text-xs`}),_&&(0,Z.jsx)(`button`,{type:`button`,onClick:s,title:`Clear search`,className:`absolute right-1.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]}),_&&(0,Z.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-1 order-last`,children:l.map((e,t)=>(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t>0&&(0,Z.jsx)(`span`,{className:`text-[10px] uppercase text-muted-foreground`,children:`then`}),(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border bg-accent/50 px-2 py-0.5 text-xs`,children:[(0,Z.jsx)(`span`,{className:`max-w-[10rem] truncate`,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(t),title:`Remove "${e}"`,className:`rounded p-0.5 text-muted-foreground hover:text-foreground touch-target`,children:(0,Z.jsx)(Me,{className:`h-3 w-3`})})]})]},`${e}-${t}`))}),(0,Z.jsxs)(`div`,{className:`flex flex-1 basis-full items-center justify-between gap-2 sm:basis-auto sm:justify-end`,children:[r&&(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-pressed":n!==`off`,title:n===`off`?`Show comments on tiles`:`Hide comments on tiles`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border touch-target ${n===`off`?`text-muted-foreground hover:bg-accent`:`border-primary/30 bg-primary/15 text-primary hover:bg-primary/25`}`,children:(0,Z.jsx)(v,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(q_,{workspaceId:e,value:u,onChange:d}),(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1`,children:[g&&(0,Z.jsx)(xd,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`shrink-0 whitespace-nowrap tabular-nums text-xs text-muted-foreground`,children:[h.toLocaleString(),(0,Z.jsxs)(`span`,{className:`hidden sm:inline`,children:[` item`,h===1?``:`s`]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.max(1,f-1)),disabled:f<=1,title:`Previous page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(oe,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`span`,{className:`shrink-0 tabular-nums text-xs text-muted-foreground`,children:[f,`/`,m]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(Math.min(m,f+1)),disabled:f>=m,title:`Next page`,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground hover:bg-accent disabled:opacity-40 touch-target`,children:(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5`})})]})]})]})}function Wy({workspaceId:e,doc:t}){let{src:n,loading:r,error:i}=Po(e,t.id);return(0,Z.jsxs)(Z.Fragment,{children:[r&&(0,Z.jsx)(`span`,{children:`Loading video…`}),i&&(0,Z.jsx)(`span`,{role:`alert`,children:i}),n&&(0,Z.jsx)(`video`,{src:n,controls:!0,playsInline:!0,preload:`metadata`,className:`max-h-full max-w-full`})]})}function Gy({config:e,setConfig:t,canvas:n}){let r=By(n,typeof e.pageSize==`number`?e.pageSize:60,!0),i=Lo()==null&&(n.interactive??!n.readOnly),[a,o]=(0,X.useState)(new Set),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),p=e=>o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),[m,h]=(0,X.useState)(null),{images:g,isLoading:_,error:v,activeQueries:y}=r,b=e.showComments===!1?`off`:`caption`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Uy,{workspaceId:n.workspaceId,state:r,comments:b,onToggleComments:()=>t({...e,showComments:b===`off`})}),i&&(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-2 py-1`,children:[(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>{c(!s),o(new Set)},children:s?`Done selecting`:`Select`}),s&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,onClick:()=>o(new Set(g.map(e=>e.id))),children:`Select page`}),a.size>0&&(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>u([...a]),children:[`Bulk Edit… (`,a.size,`)`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:v?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:v}):g.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:_?`Loading media…`:y.length?`No images or videos match your search.`:`No images or videos in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(min(120px,100%),1fr))] gap-2 sm:grid-cols-[repeat(auto-fill,minmax(min(200px,100%),1fr))] sm:gap-3`,children:g.map((e,t)=>(0,Z.jsxs)(`div`,{className:`relative`,onContextMenu:t=>{i&&(t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,ids:a.has(e.id)?[...a]:[e.id]}))},children:[(0,Z.jsx)(Vy,{workspaceId:n.workspaceId,doc:e,onClick:()=>s?p(e.id):h(t),comments:b}),s&&(0,Z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select document ${e.id}`,checked:a.has(e.id),onChange:()=>p(e.id),className:`canvas-no-drag absolute left-2 top-2 h-4 w-4 accent-primary`})]},e.id))})}),d&&(0,Z.jsx)(Xf,{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:Fe,run:()=>u(d.ids)}]}),l&&(0,Z.jsx)(om,{workspaceId:n.workspaceId,documentIds:l,onClose:()=>u(null)}),m!=null&&g[m]&&(0,Z.jsx)(Hy,{workspaceId:n.workspaceId,docs:g,index:m,onClose:()=>h(null),onNavigate:h})]})}wf({type:`gallery`,name:`Gallery`,icon:sn,defaultSize:{w:8,h:6,minW:3,minH:3},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Gy});var Ky=150;function qy(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)&&t>0?t:0}function Jy(e){let t=e.metadata??{},n=e.data??{};return{w:qy(t.width)||qy(t.imageWidth)||qy(n.width)||qy(n.imageWidth),h:qy(t.height)||qy(t.imageHeight)||qy(n.height)||qy(n.imageHeight)}}function Yy(e,t){if(t%9==0)return{cols:2,rows:2};let{w:n,h:r}=Jy(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 Xy({config:e,setConfig:t,canvas:n}){let r=By(n,typeof e.pageSize==`number`?e.pageSize:60),[i,a]=(0,X.useState)(null),{images:o,isLoading:s,error:c,activeQueries:l}=r,u=e.showComments===!1?`off`:`reveal`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[!n.readOnly&&(0,Z.jsx)(Uy,{workspaceId:n.workspaceId,state:r,comments:u,onToggleComments:()=>t({...e,showComments:u===`off`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-1`,children:c?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-destructive`,children:c}):o.length===0?(0,Z.jsx)(`div`,{className:`p-4 text-sm text-muted-foreground`,children:s?`Loading images…`:l.length?`No images match your search.`:`No images in this canvas' context.`}):(0,Z.jsx)(`div`,{className:`grid gap-2`,style:{gridTemplateColumns:`repeat(auto-fill, minmax(${Ky}px, 1fr))`,gridAutoRows:`${Ky}px`,gridAutoFlow:`dense`},children:o.map((e,t)=>{let{cols:r,rows:i}=Yy(e,t);return(0,Z.jsx)(`div`,{style:{gridColumn:`span ${r}`,gridRow:`span ${i}`},children:(0,Z.jsx)(Vy,{workspaceId:n.workspaceId,doc:e,onClick:()=>a(t),className:`h-full`,comments:u})},e.id)})})}),i!=null&&o[i]&&(0,Z.jsx)(Hy,{workspaceId:n.workspaceId,docs:o,index:i,onClose:()=>a(null),onNavigate:a})]})}wf({type:`mosaic`,name:`Mosaic`,icon:$n,defaultSize:{w:8,h:7,minW:4,minH:4},mobileHeight:.9,defaultConfig:{pageSize:60,showComments:!0},component:Xy});var Zy=`data/schema/task`;function Qy({doc:e,workspaceId:t,readOnly:n,onChanged:r}){let i=Ph(e),[a,o]=(0,X.useState)(!1),{replicating:s,label:c}=xo(e),l=i.status===`completed`,u=i.status??`pending`,d=Ih(i),{activationProps:f,stopRowActivation:p}=jy(e,t),m=async()=>{if(!(n||a)){o(!0);try{await Rh(t,e,l?`pending`:`completed`),r()}catch{}finally{o(!1)}}};return(0,Z.jsxs)(`div`,{...f,title:`Open details`,className:`canvas-no-drag flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-2.5 py-2 transition-colors hover:bg-accent/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring ${s?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{p(e),m()},disabled:n||a||s,"aria-pressed":l,title:l?`Mark not done`:`Mark done`,className:`canvas-no-drag mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${l?`border-success bg-success text-success-foreground`:`border-input hover:border-success`} ${n?`cursor-default opacity-70`:``}`,children:a?(0,Z.jsx)(Mt,{className:`h-2.5 w-2.5 animate-spin`}):l&&(0,Z.jsx)($e,{className:`h-3 w-3`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm ${l?`text-muted-foreground line-through`:``}`,children:i.title||`Todo ${e.id}`}),(0,Z.jsxs)(`div`,{className:`mt-0.5 flex flex-wrap items-center gap-1.5 text-[11px]`,children:[(0,Z.jsx)(`span`,{className:`rounded-full px-1.5 py-0.5 ${Fh[u]}`,children:Eh[u]}),i.dueDate&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Z.jsx)(de,{className:`h-3 w-3`}),Lh(i.dueDate)]}),typeof i.priority==`number`&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-muted-foreground`,children:[(0,Z.jsx)(bn,{className:`h-3 w-3`}),`P`,i.priority]}),s&&(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,role:`status`,children:[(0,Z.jsx)(Mt,{className:`h-3 w-3 animate-spin`}),c]})]})]})]})}function $y({config:e,setConfig:t,canvas:n}){let r=typeof e.pageSize==`number`?e.pageSize:50,[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!0),[c,l]=(0,X.useState)(0),u=n.interactive===!1,d=n.readOnly!==!0,[f,p]=(0,X.useState)(e.hideDone===!0),m=d?e.hideDone===!0:f,h=n=>{d?t({...e,hideDone:n}):p(n)};(0,X.useEffect)(()=>{let e=!1;return(async()=>{s(!0);try{let t=await n.fetchDocuments({limit:r,allOf:[Zy],sortBy:`tasks`,order:`asc`});if(e)return;a((t.payload||[]).filter(e=>e.schema===hi))}catch{e||a([])}finally{e||s(!1)}})(),()=>{e=!0}},[n,r,c]),(0,X.useEffect)(()=>{let e=()=>l(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]);let g=(0,X.useCallback)(()=>l(e=>e+1),[]),_=m?i.filter(e=>Ph(e).status!==`completed`):i,v=i.filter(e=>{let t=Ph(e).status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex items-center justify-between gap-2 border-b px-1 pb-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[v,` open`]}),(0,Z.jsxs)(`label`,{className:`flex items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`h-3 w-3`}),`Hide done`]})]}),(0,Z.jsx)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto p-1`,children:o&&i.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading todos…`}):_.length===0?(0,Z.jsx)(`div`,{className:`p-3 text-sm text-muted-foreground`,children:`No todos in this canvas' context.`}):_.map(e=>(0,Z.jsx)(Qy,{doc:e,workspaceId:n.workspaceId,readOnly:u,onChanged:g},e.id))})]})}wf({type:`todos`,name:`Todos`,icon:On,defaultSize:{w:4,h:6,minW:3,minH:3},mobileHeight:.6,defaultConfig:{pageSize:50,hideDone:!1},component:$y});function eb(e){if(!e)return`/`;let t=e.replace(/\/+/g,`/`);return t.startsWith(`/`)?t:`/${t}`}var tb=`context`;function nb(e){let t=e=>{try{return decodeURIComponent(e)}catch{return e}},n=e.split(`/`).filter(Boolean);if(n[0]!==`workspaces`)return{treeName:tb,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:tb,path:e?`/${e}`:`/`}}return{treeName:tb,path:`/`}}function rb(e,t,n){let r=n&&n!==tb?`/trees/${encodeURIComponent(n)}`:``,i=eb(t);return`/workspaces/${e}${r}${i===`/`?``:`/path/${i.split(`/`).filter(Boolean).map(encodeURIComponent).join(`/`)}`}`}function ib({canvas:e}){return Lo()!=null||!dd()?(0,Z.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Workspace pins are available in the signed-in workspace view.`}):(0,Z.jsx)(ab,{workspaceId:e.workspaceId},e.workspaceId)}function ab({workspaceId:e}){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(`Workspace`),[a,o]=(0,X.useState)(!0),[s,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(0);return(0,X.useEffect)(()=>{let t=!1,r=0,a=async()=>{let a=++r;o(!0);try{let[o,s]=await Promise.all([Zi(e),_o(e)]);if(t||a!==r)return;i(o.label||o.name||`Workspace`),n(s),l(null)}catch{if(t||a!==r)return;n([]),l(`Workspace pins are unavailable. Check your workspace access or try again.`)}finally{!t&&a===r&&o(!1)}},s=()=>{document.visibilityState===`visible`&&a()};a(),window.addEventListener(`focus`,s),document.addEventListener(`visibilitychange`,s);let c=id.on(`pins.changed`,s),u=window.setInterval(s,6e4);return()=>{t=!0,window.removeEventListener(`focus`,s),document.removeEventListener(`visibilitychange`,s),c?.(),window.clearInterval(u)}},[e,u]),(0,Z.jsxs)(`div`,{className:`canvas-no-drag flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-2 pb-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:r}),(0,Z.jsx)(`button`,{type:`button`,title:`Refresh pins`,"aria-label":`Refresh pins`,disabled:a,onClick:()=>d(e=>e+1),className:`rounded p-1.5 text-muted-foreground hover:bg-accent disabled:opacity-40`,children:(0,Z.jsx)(we,{className:`h-3.5 w-3.5 ${a?`animate-spin`:``}`})})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-1`,children:s?(0,Z.jsx)(`p`,{role:`alert`,className:`p-2 text-sm text-muted-foreground`,children:s}):t.length?(0,Z.jsx)(`ul`,{className:`space-y-2`,children:t.map(t=>{let n=t.resolvable===!1,r=hp(t.color),i=(0,Z.jsxs)(Z.Fragment,{children:[n?(0,Z.jsx)(at,{className:`h-5 w-5 shrink-0 text-warning`}):(0,Z.jsx)(c,{icon:t.icon||(t.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),width:22,height:22,color:r,className:`shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`p`,{className:`truncate text-sm font-medium`,children:t.label||t.name||t.path}),(0,Z.jsxs)(`p`,{className:`truncate text-xs text-muted-foreground`,children:[t.tree,`:`,t.path]}),t.description&&(0,Z.jsx)(`p`,{className:`line-clamp-2 text-xs text-muted-foreground`,children:t.description}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-warning`,children:`Folder no longer exists`})]})]}),a=`flex items-center gap-3 rounded-lg border border-l-4 bg-card p-3`,o={borderLeftColor:r||`transparent`};return(0,Z.jsx)(`li`,{children:n?(0,Z.jsx)(`div`,{className:`${a} opacity-60`,style:o,children:i}):(0,Z.jsx)(Su,{to:rb(e,t.path,t.tree),title:`Open ${t.tree}:${t.path}`,className:`${a} transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,style:o,children:i})},t.id)})}):(0,Z.jsx)(`p`,{className:`p-2 text-sm text-muted-foreground`,children:a?`Loading pins…`:`No workspace pins yet. Pin a folder from the workspace tree menu.`})})]})}wf({type:`workspace-pins`,name:`Workspace pins`,icon:R,defaultSize:{w:4,h:6,minW:3,minH:2},mobileHeight:.6,defaultConfig:{},component:ib});function ob({title:e,icon:t,onRemove:n,fill:r,onToggleFill:i,readOnly:a=!1,stacked:o=!1,children:s}){let[c,l]=(0,X.useState)(!1),u=c?document.getElementById(`content-area`):null,d=(0,Z.jsxs)(`div`,{className:c?u?`absolute inset-0 z-40 flex flex-col bg-background`:`fixed inset-0 z-50 flex flex-col bg-background`:`flex flex-col h-full rounded-lg border bg-background overflow-hidden`,children:[(0,Z.jsxs)(`div`,{className:`canvas-drag-handle flex items-center gap-2 px-2 py-1 border-b bg-muted/30 select-none ${o?``:`cursor-move`}`,children:[t&&(0,Z.jsx)(t,{className:`w-3.5 h-3.5 text-muted-foreground shrink-0`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium truncate flex-1`,children:e}),!a&&i&&!c&&!o&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(sb,{on:r?.w===!0,onClick:()=>i(`w`),label:`Fill width`,icon:le}),(0,Z.jsx)(sb,{on:r?.h===!0,onClick:()=>i(`h`),label:`Fill height`,icon:jn})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>l(e=>!e),className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-accent touch-target`,title:c?`Restore`:`Full screen`,children:c?(0,Z.jsx)(it,{className:`w-3.5 h-3.5`}):(0,Z.jsx)(Fn,{className:`w-3.5 h-3.5`})}),!a&&n&&(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`canvas-no-drag shrink-0 p-0.5 rounded text-muted-foreground hover:text-destructive hover:bg-destructive/10 touch-target`,title:`Remove widget`,children:(0,Z.jsx)(Me,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 min-h-0 overflow-auto p-2`,children:s})]});return c?(0,Mf.createPortal)(d,u??document.body):d}function sb({on:e,onClick:t,label:n,icon:r}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-pressed":e,title:e?`${n} (on)`:n,className:`canvas-no-drag shrink-0 p-0.5 rounded touch-target ${e?`bg-primary/15 text-primary hover:bg-primary/25`:`text-muted-foreground hover:text-foreground hover:bg-accent`}`,children:(0,Z.jsx)(r,{className:`w-3.5 h-3.5`})})}var cb=(0,Sf.WidthProvider)(Sf.default),lb=12,ub=80,db=40,fb=[12,12],pb=[8,8],mb={w:!1,h:!1};function hb(e){return Math.max(1,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function gb(e){return Math.max(0,...e.map(e=>e.y+e.h).filter(Number.isFinite))}function _b(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 vb(e,t,n=0){let r=n>0?n:hb(e);return e.map(e=>{let n=t[e.i]??mb;return!n.w&&!n.h?e:{...e,x:n.w?0:e.x,w:n.w?lb:e.w,y:n.h?0:e.y,h:n.h?Math.max(e.minH??1,r):e.h}})}var yb=4;function bb(e,t,n=fb[1]){return Math.max(1,Math.ceil((e-n-yb)/(t+n)))}var xb=45,Sb=640;function Cb(e,t,n=0,r){let i=[...vb(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:lb,y:a,h:n};return a+=n,i})}var wb=e=>e&&e.trim()?[e]:[];function Tb(e){let t=e?.ui??{},n=Array.isArray(t.layout)?t.layout.map(_b):[],r={};for(let e of n)r[e.i]={w:e.fillW??e.w>=lb,h:e.fillH===!0};return{layout:n,fills:r,widgets:t.widgets&&typeof t.widgets==`object`?t.widgets:{}}}function Eb({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,metadata:a,isLocked:o=!1,readOnly:s=!1,interactive:c=!0,fetchDocuments:l,onSaved:u}){let d=!s,f=(0,X.useMemo)(()=>Tb(a),[a]),[p,m]=(0,X.useState)(f.layout),[h,g]=(0,X.useState)(f.widgets),[_,v]=(0,X.useState)(f.fills),y=(0,X.useRef)(f.fills),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),[E,D]=(0,X.useState)(null),[O,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(0),N=(0,X.useRef)(0),P=(0,X.useCallback)(e=>{y.current=e,v(e)},[]),[ee,F]=(0,X.useState)(()=>I_(i?.sort)),I=(0,X.useRef)(!1),[L,R]=(0,X.useState)(()=>wb(i?.query)),te=(0,X.useRef)(!1),ne=(0,X.useRef)(null),z=(0,X.useRef)(f),re=(0,X.useCallback)(e=>{let t=Tf(h[e]?.type??``)?.mobileHeight;if(!(!t||j<=0))return Math.max(1,Math.round(j*t))},[h,j]),ie=(0,X.useMemo)(()=>O?Cb(p,_,j,re):vb(p,_,j),[p,_,O,j,re]),ae=O?db:ub,oe=(0,X.useMemo)(()=>JSON.stringify(a?.ui??null),[a?.ui]);(0,X.useEffect)(()=>{let e=Tb(a);m(e.layout),g(e.widgets),P(e.fills),z.current=e,F(I_(i?.sort)),I.current=!1,R(wb(i?.query)),te.current=!1,C(!1)},[n,r]),(0,X.useEffect)(()=>{if(!s)return;let e=Tb(a);m(e.layout),g(e.widgets),P(e.fills),z.current=e},[s,oe,a,P]),(0,X.useEffect)(()=>{let e=ne.current;if(!e)return;let t=()=>{let t=e.clientHeight,n=e.clientWidth>0&&e.clientWidth<Sb;A(n),N.current=t,e.style.setProperty(`--canvas-host-h`,`${t}px`);let r=n?pb:fb;e.style.setProperty(`--canvas-grid-gutter`,`${r[1]}px`),t>0&&M(bb(t,n?db:ub,r[1]))};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[p]);let se=(0,X.useCallback)(e=>{F(e),I.current=!0,C(!0)},[]),B=(0,X.useCallback)(e=>{R(e),te.current=!0,C(!0)},[]),ce=(0,X.useMemo)(()=>({workspaceId:e,treeName:t,path:n,layerId:r,querySpec:i,readOnly:!d,interactive:c,canvasSort:ee,setCanvasSort:d?se:void 0,canvasQueries:L,setCanvasQueries:d?B:void 0,fetchDocuments:l??(async r=>{let i;if(r?.anyOf?.length&&(i=((await Yi(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 Yi(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,ee,se,L,B]),V=(0,X.useCallback)((e,t,n)=>{z.current={layout:e,widgets:t,fills:n??y.current},C(!0)},[]),le=(0,X.useCallback)(async()=>{if(!(!d||w)){T(!0),D(null);try{let r={widgets:z.current.widgets,layout:z.current.layout.map(e=>({...e,fillW:y.current[e.i]?.w===!0,fillH:y.current[e.i]?.h===!0}))};z.current={...r,fills:y.current};let o=I.current||te.current?{...i||{},...I.current?{sort:ee.sortBy?ee:null}:{},...te.current?{query:L.join(` `).trim()||null}:{}}:void 0;await Fi(e,n,t,{...a||{},ui:r},o),I.current=!1,te.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,ee,L]),ue=(0,X.useCallback)(e=>{!d||O||m(t=>{let n=e.map(e=>{let n=t.find(t=>t.i===e.i),r=y.current[e.i];return n?{...e,x:r?.w?n.x:e.x,w:r?.w?n.w:e.w,y:r?.h?n.y:e.y,h:r?.h?n.h:e.h}:e});return V(n,h),n})},[d,O,V,h]),de=(0,X.useCallback)((e,t,n)=>{if(!d)return;let r=y.current[n.i]??mb,i=fb[1]+(n.y+n.h)*(ub+fb[1]),a={w:n.x+n.w>=lb,h:N.current>0&&i>=N.current-xb};if(a.w||=r.w&&n.w===t.w,a.h||=r.h&&n.h===t.h,a.w===r.w&&a.h===r.h)return;let o={...y.current,[n.i]:a};P(o),V(z.current.layout,h,o)},[d,P,V,h]),fe=(0,X.useCallback)((e,t)=>{if(!d)return;let n=y.current[e]??mb,r={...y.current,[e]:{...n,[t]:!n[t]}};P(r),V(p,h,r)},[d,P,V,p,h]),pe=(0,X.useCallback)(e=>{let t=Tf(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:gb(ie),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>=lb,h:!1}};m(l),g(u),P(d),x(!1),V(l,u,d)},[p,ie,h,P,V]),me=(0,X.useCallback)(e=>{let t=p.filter(t=>t.i!==e),n={...h};delete n[e];let r={...y.current};delete r[e],m(t),g(n),P(r),V(t,n,r)},[p,h,P,V]),he=(0,X.useCallback)((e,t)=>{g(n=>{let r={...n,[e]:{...n[e],config:t}};return V(p,r),r})},[p,V]),ge=Object.keys(h);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0`,children:[d&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 border-b shrink-0 sm:px-3`,children:[(0,Z.jsxs)(`div`,{className:`relative shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>x(e=>!e),className:`flex items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs border rounded-md hover:bg-accent`,children:[(0,Z.jsx)(U,{className:`w-3.5 h-3.5`}),`Add`,(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:` widget`})]}),b&&(0,Z.jsx)(`div`,{className:`absolute left-0 top-full mt-1 z-20 w-48 rounded-md border bg-popover shadow-elevation-2 py-1`,children:Ef().map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>pe(e.type),className:`flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left hover:bg-accent`,children:[(0,Z.jsx)(e.icon,{className:`w-3.5 h-3.5 text-muted-foreground`}),e.name]},e.type))})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:le,disabled:!S||w,className:K(`flex shrink-0 items-center gap-1.5 whitespace-nowrap px-2.5 py-1 text-xs rounded-md transition-colors disabled:opacity-50`,S?`bg-primary text-primary-foreground hover:bg-primary`:`border hover:bg-accent`),children:[(0,Z.jsx)(k,{className:`w-3.5 h-3.5`}),w?`Saving…`:`Save`]}),(0,Z.jsxs)(`span`,{className:`min-w-0 truncate text-xs text-muted-foreground`,children:[ge.length,` widget`,ge.length===1?``:`s`,S?` · unsaved`:``,E?` · ${E}`:``]})]}),(0,Z.jsx)(`div`,{ref:ne,className:`canvas-grid-host flex-1 min-h-0 bg-muted/10 overflow-y-auto overflow-x-hidden`,children:ge.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-center h-full gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(`p`,{children:`No widgets yet.`}),d&&(0,Z.jsx)(`p`,{className:`text-xs`,children:`Use “Add widget” to place one on the canvas.`})]}):(0,Z.jsx)(cb,{className:`layout`,layout:ie,cols:lb,rowHeight:ae,margin:O?pb:fb,isDraggable:d&&!O,isResizable:d&&!O,resizeHandles:[`s`,`e`,`se`],draggableHandle:`.canvas-drag-handle`,draggableCancel:`.canvas-no-drag`,onLayoutChange:ue,onResizeStop:de,compactType:`vertical`,children:ge.map(e=>{let t=h[e],n=Tf(t.type),r=_[e]??mb,i=[r.w?`w`:``,r.h?`h`:``].filter(Boolean).join(` `);return(0,Z.jsx)(`div`,{"data-fill":i||void 0,children:n?(0,Z.jsx)(ob,{title:n.name,icon:n.icon,readOnly:!d,stacked:O,onRemove:()=>me(e),fill:_[e]??mb,onToggleFill:d?t=>fe(e,t):void 0,children:(0,Z.jsx)(n.component,{config:t.config??{...n.defaultConfig||{}},setConfig:t=>he(e,t),canvas:ce})}):(0,Z.jsx)(ob,{title:`Unknown: ${t.type}`,readOnly:!d,stacked:O,onRemove:()=>me(e),children:(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:`This widget type is not available.`})})},e)})})})]})}var Db=`data/schema/file`;function Ob(e){return String(e.locations?.[0]?.url||``).trim()}function kb(e){let t=Ob(e);if(!t)return``;let n=t.split(/[?#]/)[0].split(`/`).filter(Boolean).pop()||``;try{return decodeURIComponent(n)}catch{return n}}function Ab(e){return e.schema===Db&&String(e.metadata?.contentType||``).startsWith(`image/`)}function jb(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 Mb(e){if(e.schema!==Db)return Ui(e);let t=kb(e),n=String(e.metadata?.contentType||``).trim(),r=jb(e.metadata?.size);return{...Ui(e),title:t||`File ${e.id}`,preview:[n,r].filter(Boolean).join(` · `),subtitle:Ob(e),schemaLabel:`file`}}function Nb(e){return/^https?:\/\/[^\s]+$/i.test(e)}function Pb(e,t){if(e.schema===`data/schema/tab`){let t=String(e.data?.url||``).trim();return Nb(t)?t:null}return t.isExternal&&Nb(t.subtitle)?t.subtitle:Nb(t.title)?t.title:null}function Fb(e,t,n=!1){return jo(e,t,{download:n})}function Ib(e){return e.split(/(https?:\/\/[^\s]+)/gi).map((e,t)=>Nb(e)?(0,Z.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`underline decoration-muted-foreground underline-offset-2 hover:text-primary`,children:e},`${e}-${t}`):e)}function Lb(e){return e?new Date(e).toLocaleString():``}function Rb(){let{code:e=``}=ll(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),d=(0,X.useMemo)(()=>t?.documents?Array.isArray(t.documents)?t.documents:t.documents.data||[]:[],[t]),f=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();return e?d.filter(t=>{let n=Mb(t);return[t.schema,n.title,n.preview,n.subtitle,kb(t),t.metadata?.contentType].join(` `).toLowerCase().includes(e)}):d},[d,l]),p=(0,X.useCallback)(async()=>{if(e){i(!0);try{let t=await J.get(`${Rr}/pub/c/${encodeURIComponent(e)}`,{skipAuth:!0});n(t),o(null)}catch(e){n(null),o(e instanceof Error?e.message:`Failed to load public canvas`)}finally{i(!1)}}},[e]);(0,X.useEffect)(()=>{p()},[p]),(0,X.useEffect)(()=>{if(!e)return;let t=Br(`${zr}/pub`,{transports:[`websocket`],auth:{code:e},reconnection:!0,reconnectionAttempts:10,reconnectionDelay:1500});return t.on(`connect`,()=>c(!0)),t.on(`disconnect`,()=>c(!1)),t.on(`connect_error`,()=>c(!1)),t.on(`canvas:changed`,()=>p()),()=>{t?.disconnect(),t=null}},[e,p]);let m=(0,X.useCallback)(e=>{e?.preventDefault(),u(l.trim())},[l]),h=(0,X.useCallback)(()=>{u(``)},[]),g=(0,X.useCallback)(async e=>({payload:Bi(e?.sortBy)?ei(d,e.sortBy,e?.order):d,totalCount:t?.stats.documentCount??d.length}),[d,t]);if(r&&!t)return(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted flex items-center justify-center p-6`,children:(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`Loading canvas...`})});if(a||!t)return(0,Z.jsxs)(`main`,{className:`min-h-screen bg-muted flex flex-col items-center justify-center p-6`,children:[(0,Z.jsxs)(Fu,{className:`max-w-md bg-card`,children:[(0,Z.jsx)(Iu,{children:(0,Z.jsx)(Lu,{children:`Canvas unavailable`})}),(0,Z.jsx)(zu,{className:`text-sm text-muted-foreground`,children:a||`This public canvas does not exist.`})]}),(0,Z.jsx)(td,{className:`mt-6 text-center`})]});let _=t.canvas.metadata?.ui??{},v=!!_.widgets&&Object.keys(_.widgets).length>0;return(0,Z.jsx)(Vo.Provider,{value:e,children:(0,Z.jsx)(`main`,{className:`min-h-screen bg-muted p-2 text-foreground sm:p-4 md:p-10`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl`,children:[(0,Z.jsxs)(Fu,{className:`bg-card shadow-elevation-3`,children:[(0,Z.jsx)(Iu,{className:`border-b p-3 sm:p-6`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 md:flex-row md:items-start md:justify-between md:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 gap-3 sm:gap-4`,children:[(0,Z.jsx)(`div`,{className:`mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-accent text-primary sm:mt-1 sm:h-12 sm:w-12 sm:rounded-2xl`,style:t.canvas.color?{borderLeft:`4px solid ${t.canvas.color}`}:void 0,children:(0,Z.jsx)($n,{className:`h-5 w-5 sm:h-6 sm:w-6`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-xs uppercase tracking-wide text-muted-foreground`,children:t.workspace.label||t.workspace.name}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] text-muted-foreground md:hidden`,children:[s?(0,Z.jsx)(S,{className:`h-3 w-3 text-success`}):(0,Z.jsx)(qe,{className:`h-3 w-3 text-muted-foreground`}),s?`Live`:`Offline`]})]}),(0,Z.jsx)(Lu,{className:`mt-0.5 truncate text-2xl sm:mt-1 sm:text-3xl md:text-5xl`,children:t.canvas.label||t.canvas.name||`Canvas`}),t.canvas.description&&(0,Z.jsx)(`p`,{className:`mt-1.5 max-w-3xl text-sm text-muted-foreground sm:mt-3 sm:text-base`,children:t.canvas.description})]})]}),(0,Z.jsxs)(`div`,{className:`hidden shrink-0 items-center gap-2 rounded-full border px-3 py-1 text-xs text-muted-foreground md:flex`,children:[s?(0,Z.jsx)(S,{className:`h-3.5 w-3.5 text-success`}):(0,Z.jsx)(qe,{className:`h-3.5 w-3.5 text-muted-foreground`}),s?`Live`:`Offline`]})]})}),(0,Z.jsxs)(zu,{className:`space-y-4 p-3 sm:space-y-6 sm:p-6 md:p-8`,children:[(0,Z.jsxs)(`section`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs text-muted-foreground md:hidden`,children:[(0,Z.jsx)(`span`,{className:`w-full truncate font-mono text-foreground`,children:t.share.path}),(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[t.stats.documentCount,` docs`]}),f.length!==t.stats.documentCount&&(0,Z.jsxs)(`span`,{className:`tabular-nums`,children:[`· `,f.length,` shown`]}),(0,Z.jsxs)(`span`,{className:`truncate`,children:[`· `,Lb(t.stats.refreshedAt)]})]}),(0,Z.jsxs)(`section`,{className:`hidden gap-3 md:grid md:grid-cols-4`,children:[(0,Z.jsx)(zb,{label:`Path`,value:t.share.path,mono:!0}),(0,Z.jsx)(zb,{label:`Documents`,value:String(t.stats.documentCount)}),(0,Z.jsx)(zb,{label:`Shown`,value:String(f.length)}),(0,Z.jsx)(zb,{label:`Refreshed`,value:Lb(t.stats.refreshedAt)})]}),v&&(0,Z.jsx)(`section`,{id:`content-area`,className:`flex w-full flex-col overflow-hidden rounded-2xl border h-viewport-card min-h-[420px] md:h-viewport-pane`,children:(0,Z.jsx)(Eb,{workspaceId:t.workspace.name,treeName:t.share.treeName,path:t.share.path,layerId:t.canvas.id,querySpec:t.canvas.querySpec,metadata:t.canvas.metadata,readOnly:!0,interactive:!1,fetchDocuments:g},JSON.stringify(_))}),!v&&(0,Z.jsxs)(`section`,{className:`rounded-2xl border`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 border-b px-4 py-3 md:flex-row md:items-center md:justify-between`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold`,children:`Content`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center`,children:[(0,Z.jsxs)(`form`,{onSubmit:m,className:`flex min-w-0 items-center gap-2`,children:[(0,Z.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{type:`search`,value:l,onChange:e=>u(e.target.value),placeholder:`Search loaded documents...`,className:`w-full rounded-md border py-1.5 pl-9 pr-8 text-sm md:w-72`}),l&&(0,Z.jsx)(`button`,{type:`button`,onClick:h,className:`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground`,"aria-label":`Clear search`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsx)(`button`,{type:`submit`,className:`rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:`Search`})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:p,className:`inline-flex items-center justify-center gap-2 rounded-md border px-3 py-1.5 text-xs hover:bg-muted`,children:[(0,Z.jsx)(we,{className:`h-3.5 w-3.5 ${r?`animate-spin`:``}`}),`Refresh`]})]})]}),l.trim()&&(0,Z.jsxs)(`div`,{className:`border-b bg-muted px-4 py-2 text-xs text-muted-foreground`,children:[`Local search: `,(0,Z.jsxs)(`span`,{className:`font-mono`,children:[`"`,l.trim(),`"`]})]}),(0,Z.jsx)(`div`,{className:`divide-y`,children:f.length===0?(0,Z.jsx)(`div`,{className:`p-8 text-center text-sm text-muted-foreground`,children:l.trim()?`No loaded documents match your search.`:`No documents yet.`}):f.map(t=>{let n=Mb(t),r=Pb(t,n),i=t.schema===Db,a=i?Fb(e,t.id):null,o=a||r;return(0,Z.jsxs)(`article`,{className:`p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-1 md:flex-row md:items-start md:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h3`,{className:`truncate font-medium`,children:o?(0,Z.jsx)(`a`,{href:o,target:`_blank`,rel:`noreferrer`,className:`hover:text-primary hover:underline`,children:n.title}):n.title}),(0,Z.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted-foreground`,children:n.schemaLabel})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-3`,children:[i&&(0,Z.jsxs)(`a`,{href:Fb(e,t.id,!0),download:n.title,className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(er,{className:`h-3.5 w-3.5`}),`Download`]}),(0,Z.jsx)(`time`,{className:`text-xs text-muted-foreground`,children:Lb(t.updatedAt||t.createdAt)})]})]}),n.preview&&(0,Z.jsx)(`p`,{className:`mt-3 line-clamp-3 text-sm leading-6 text-foreground`,children:Ib(n.preview)}),Ab(t)&&(0,Z.jsx)(`a`,{href:a||void 0,target:`_blank`,rel:`noreferrer`,className:`mt-3 block w-fit`,children:(0,Z.jsx)(`img`,{src:a||void 0,alt:n.title,loading:`lazy`,className:`max-h-64 max-w-full rounded border bg-muted object-contain transition-opacity hover:opacity-90`})})]},t.id)})})]})]})]}),(0,Z.jsx)(td,{className:`mt-6 text-center`})]})})})}function zb({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`min-w-0 rounded-xl border bg-muted p-4`,children:[(0,Z.jsx)(`div`,{className:`text-xs uppercase tracking-wide text-muted-foreground`,children:e}),(0,Z.jsx)(`div`,{className:`mt-2 truncate text-lg font-semibold ${n?`font-mono text-sm`:``}`,children:t||`-`})]})}var Bb=(0,X.createContext)(void 0);function Vb(){let e=(0,X.useContext)(Bb),t=Uo()?.state,n=!!t,r=t?.activeContextType,i=t?.activeContextId,a=t?.activeWorkspaceName,o=t?.activeContextPath,s=t?.activeTreeName;return(0,X.useMemo)(()=>e===void 0?n?r===`context`&&i?{mode:`context`,contextId:i}:a&&o?{mode:`workspace`,workspaceName:a,path:o,treeName:s||`context`,treeType:s===`directory`||s===`backends`?`directory`:`context`}:null:null:e,[e,n,r,i,a,o,s])}function Hb({value:e,onChange:t,onBlur:n,placeholder:r,innerRef:i}){let a=(0,X.useRef)(null),o=(0,X.useCallback)(()=>{let e=a.current;e&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)},[]);return(0,X.useEffect)(()=>{o()},[e,o]),(0,Z.jsx)(`textarea`,{ref:e=>{a.current=e,i?.(e)},value:e,onChange:e=>t(e.target.value),onBlur:n,placeholder:r,rows:1,spellCheck:!1,className:`w-full resize-none overflow-hidden border-0 bg-transparent p-0 text-sm leading-relaxed text-foreground outline-none placeholder:text-muted-foreground/60`})}function Ub({onLinkTo:e,onDelete:t}){return(0,Z.jsxs)(`span`,{className:`reveal-on-hover flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:e,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,"aria-label":`Link to…`,title:`Link to…`,children:(0,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,className:`rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-destructive`,"aria-label":`Delete`,title:`Delete (moves to trash)`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function Wb({documentId:e,workspaceName:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,X.useState)(!1);return(0,Z.jsx)(Hp,{onClose:n,children:(0,Z.jsx)(Bp,{onClose:n,onConfirm:async(t,a)=>{if(t.length){o(!0);try{for(let n of t)await li(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:Vp,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 Ca(t,e,a,c,s),r(`Related to ${c.length} document${c.length===1?``:`s`}`),Dm(),n()}catch(e){i(e instanceof Error?e.message:`Failed to create relation`),o(!1)}}}})})}var Gb=1200;function Kb(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 qb(e,t){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(!1),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=(0,X.useCallback)(()=>{if(!e)return Promise.resolve();if(e.mode===`context`){let{contextId:n}=e;return Promise.all([ds(n,[t]),fs(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 so(n,i,[t],{treeName:o,treeType:c,limit:50}).then(e=>{r(e.payload||[]),l({workspaceName:n,path:i,treeName:o,treeType:c})}).catch(e=>s(e instanceof Error?e.message:`Failed to load documents`)).finally(()=>a(!1))},[e,t]),d=(0,X.useCallback)(async()=>{if(!e){r([]),l(null);return}a(!0),s(null),await u()},[e,u]),[f,p]=(0,X.useState)(null);return(!f||f.target!==e||f.schema!==t)&&(p({target:e,schema:t}),e?(a(!0),s(null)):(r([]),l(null))),(0,X.useEffect)(()=>{u()},[u]),(0,X.useEffect)(()=>{let e=()=>d();return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[d]),{docs:n,setDocs:r,loading:i,error:o,scope:c,reload:d,removeDoc:(0,X.useCallback)(async e=>{if(!c)throw Error(`No workspace scope resolved`);await ho(c.workspaceName,[e],c.path,[],c.treeName,c.treeType),r(t=>t.filter(t=>t.id!==e))},[c])}}var Jb=`2.0`;function Yb({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o}){let[s,c]=(0,X.useState)(String(e.data?.title??``)),[l,u]=(0,X.useState)(String(e.data?.content??``)),[d,f]=(0,X.useState)(`idle`),p=(0,X.useRef)({title:String(e.data?.title??``),content:String(e.data?.content??``)}),m=(0,X.useRef)(null),h=(0,X.useRef)(0),g=(0,X.useCallback)(async(n,r)=>{if(!t||n===p.current.title&&r===p.current.content||!r.trim())return;let i=++h.current;f(`saving`);try{if(await Da(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data||{},...n.trim()?{title:n.trim()}:{title:void 0},content:r},metadata:e.metadata}),i!==h.current)return;p.current={title:n,content:r},f(`saved`),setTimeout(()=>f(e=>e===`saved`?`idle`:e),1500)}catch{i===h.current&&f(`error`)}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),_=(0,X.useCallback)((e,t)=>{f(`dirty`),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(e,t),Gb)},[g]),v=(0,X.useCallback)(()=>{m.current&&=(clearTimeout(m.current),null),g(s,l)},[g,s,l]);return(0,X.useEffect)(()=>()=>{m.current&&clearTimeout(m.current)},[]),(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[Kb(e.createdAt),` · #`,e.id]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[d===`saving`&&(0,Z.jsx)(Mt,{className:`inline h-3 w-3 animate-spin`}),d===`saved`&&(0,Z.jsx)($e,{className:`inline h-3 w-3 text-success`}),d===`dirty`&&`·`,d===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Ub,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsx)(`input`,{value:s,onChange:e=>{c(e.target.value),_(e.target.value,l)},onBlur:v,placeholder:`Untitled`,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(Hb,{value:l,onChange:e=>{u(e),_(s,e)},onBlur:v,innerRef:t=>r(e.id,t)})]})}function Xb({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New note`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(Me,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`Untitled`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(Hb,{value:a,onChange:o,placeholder:`Write your note…`}),l&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:l}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!a.trim()||!e||s)){c(!0),u(null);try{await cs(e,[{schema:Mi,schemaVersion:Jb,data:{...r.trim()?{title:r.trim()}:{},content:a},metadata:{features:[]}}]),t()}catch(e){u(e instanceof Error?e.message:`Failed to create note`),c(!1)}}},disabled:!a.trim()||s,className:`rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground disabled:opacity-50`,children:s?`Saving…`:`Save note`})})]})}function Zb({autoAdd:e=!1}){let t=Vb(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=qb(t,Mi),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(`desc`),[m,h]=(0,X.useState)(e),[g,_]=(0,X.useState)(null),v=(0,X.useRef)(new Map),y=(0,X.useRef)(new Map),b=(0,X.useCallback)((e,t)=>{t?v.current.set(e,t):v.current.delete(e)},[]),x=(0,X.useCallback)((e,t)=>{t?y.current.set(e,t):y.current.delete(e)},[]),S=(0,X.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete note ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await s(e.id)}catch{}},[s]),C=(0,X.useMemo)(()=>{let e=[...n];return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return f===`asc`?n:-n}),e},[n,f]),w=(0,X.useMemo)(()=>{let e=c.trim().toLowerCase();if(!e)return[];let t=[];for(let n of C){let r=String(n.data?.content??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[c,C]),T=w.length?w[Math.min(u,w.length-1)]:null;(0,X.useEffect)(()=>{T&&v.current.get(T.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[T]);let E=(0,X.useCallback)(e=>{if(!w.length)return;let t=e?(u+1)%w.length:u;e&&d(t);let n=w[t],r=y.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+c.trim().length)),v.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[w,u,c]);return t?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),d(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),E(!0))},placeholder:`Search notes…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),c.trim()&&(0,Z.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:w.length?`${Math.min(u+1,w.length)}/${w.length}`:`0/0`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:f===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:f===`desc`?(0,Z.jsx)(hn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>h(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a note`,children:[(0,Z.jsx)(U,{className:`h-3.5 w-3.5`}),`Note`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[m&&(0,Z.jsx)(Xb,{target:t,onCreated:()=>{h(!1),o()},onCancel:()=>h(!1)}),r&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),i&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:i}),!r&&!i&&!C.length&&!m&&(0,Z.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:`No notes here yet - add the first one.`}),C.map(e=>(0,Z.jsx)(Yb,{doc:e,updateWorkspace:a?.workspaceName??null,registerEl:b,registerBody:x,highlighted:T?.docId===e.id,onLinkTo:()=>_(e.id),onDelete:()=>S(e)},e.id))]}),g!==null&&(0,Z.jsx)(Wb,{documentId:g,workspaceName:a?.workspaceName,onClose:()=>_(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:bs(t)})}var Qb=`2.1`,$b=new Set([`completed`,`cancelled`]);function ex({doc:e,updateWorkspace:t,registerEl:n,registerBody:r,highlighted:i,onLinkTo:a,onDelete:o,onStatusSaved:s}){let[c,l]=(0,X.useState)(String(e.data?.title??``)),[u,d]=(0,X.useState)(String(e.data?.description??``)),[f,p]=(0,X.useState)(e.data?.status||`pending`),[m,h]=(0,X.useState)(kh(e.data?.dueDate)),[g,_]=(0,X.useState)(`idle`),{replicating:v,label:y}=xo(e),b=(0,X.useRef)({title:String(e.data?.title??``),description:String(e.data?.description??``)}),x=(0,X.useRef)(null),S=(0,X.useRef)(0),C=(0,X.useCallback)(async n=>{if(!t||!n.title.trim())return!1;let r=++S.current;_(`saving`);try{let i=Ah(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 Da(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:a,metadata:e.metadata}),r!==S.current||(b.current={title:n.title,description:n.description},_(`saved`),setTimeout(()=>_(e=>e===`saved`?`idle`:e),1500),!0)}catch{return r===S.current&&_(`error`),!1}},[e.id,e.schema,e.schemaVersion,e.data,e.metadata,t]),w=(0,X.useCallback)((e,t)=>{(e!==b.current.title||t!==b.current.description)&&(_(`dirty`),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>C({title:e,description:t,status:f,due:m}),Gb))},[C,f,m]),T=(0,X.useCallback)(()=>{x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:m})},[C,c,u,f,m]);(0,X.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]);let E=(0,X.useCallback)(async()=>{let t=f,n=f===`completed`?`pending`:`completed`;p(n),await C({title:c,description:u,status:n,due:m})?s(e.id,n):p(t)},[f,C,c,u,m,e.id,s]),D=(0,X.useCallback)(e=>{h(e),x.current&&=(clearTimeout(x.current),null),C({title:c,description:u,status:f,due:e})},[C,c,u,f]),O=$b.has(f);return(0,Z.jsxs)(`div`,{ref:t=>n(e.id,t),className:K(`group border-t border-border/60 px-4 py-3 transition-colors`,i&&`bg-primary/5`),children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:[(0,Z.jsxs)(`span`,{className:`shrink-0`,children:[Kb(e.createdAt),` · #`,e.id,f!==`pending`&&(0,Z.jsxs)(`span`,{children:[` · `,Eh[f]??f]})]}),(0,Z.jsx)(jg,{value:m,onChange:D,compact:!0,placeholder:`No due date`,className:`w-[168px] shrink-0 normal-case tracking-normal`})]}),(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 text-[10px] text-muted-foreground/70`,children:[g===`saving`&&(0,Z.jsx)(Mt,{className:`inline h-3 w-3 animate-spin`}),v&&(0,Z.jsx)(`span`,{className:`whitespace-nowrap`,children:y}),g===`saved`&&(0,Z.jsx)($e,{className:`inline h-3 w-3 text-success`}),g===`dirty`&&`·`,g===`error`&&(0,Z.jsx)(`span`,{className:`text-destructive`,children:`save failed`}),(0,Z.jsx)(Ub,{onLinkTo:a,onDelete:o})]})]}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:E,className:`mt-0.5 shrink-0 text-muted-foreground transition-colors hover:text-foreground`,"aria-label":O?`Mark as pending`:`Mark as completed`,title:O?`Mark as pending`:`Mark as completed`,children:O?(0,Z.jsx)(L,{className:`h-4 w-4 text-success`}):(0,Z.jsx)(an,{className:`h-4 w-4`})}),(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`input`,{value:c,onChange:e=>{l(e.target.value),w(e.target.value,u)},onBlur:T,placeholder:`Untitled`,spellCheck:!1,className:K(`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold outline-none placeholder:text-muted-foreground/50`,O?`text-muted-foreground line-through`:`text-foreground`)}),(0,Z.jsx)(Hb,{value:u,onChange:e=>{d(e),w(c,e)},onBlur:T,placeholder:`Description…`,innerRef:t=>r(e.id,t)})]})]})]})}function tx({target:e,onCreated:t,onCancel:n}){let[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(jh()),[l,u]=(0,X.useState)(!1),[d,f]=(0,X.useState)(null);return(0,Z.jsxs)(`div`,{className:`border-t border-border/60 bg-muted/30 px-4 py-3`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between`,children:[(0,Z.jsx)(`span`,{className:`text-[10px] uppercase tracking-wide text-muted-foreground/70`,children:`New todo`}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground hover:text-foreground`,"aria-label":`Discard draft`,children:(0,Z.jsx)(Me,{className:`h-3 w-3`})})]}),(0,Z.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`What needs doing?`,autoFocus:!0,spellCheck:!1,className:`mb-1 w-full border-0 bg-transparent p-0 text-sm font-semibold text-foreground outline-none placeholder:text-muted-foreground/50`}),(0,Z.jsx)(Hb,{value:a,onChange:o,placeholder:`Description (optional)…`}),(0,Z.jsx)(`div`,{className:`mt-2`,children:(0,Z.jsx)(jg,{value:s,onChange:c,compact:!0,placeholder:`No due date`,className:`w-[188px]`})}),d&&(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-destructive`,children:d}),(0,Z.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(!r.trim()||!e||l)){u(!0),f(null);try{await cs(e,[{schema:hi,schemaVersion:Qb,data:Mh({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 nx({autoAdd:e=!1}){let t=Vb(),{docs:n,setDocs:r,loading:i,error:a,scope:o,reload:s,removeDoc:c}=qb(t,hi),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(0),[p,m]=(0,X.useState)(`desc`),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(e),[y,b]=(0,X.useState)(null),x=(0,X.useRef)(new Map),S=(0,X.useRef)(new Map),C=(0,X.useCallback)((e,t)=>{t?x.current.set(e,t):x.current.delete(e)},[]),w=(0,X.useCallback)((e,t)=>{t?S.current.set(e,t):S.current.delete(e)},[]),T=(0,X.useCallback)(async e=>{let t=e.data?.title?`"${e.data.title}"`:`#${e.id}`;if(window.confirm(`Delete todo ${t}?\n\nIt is removed from this path and moves to the workspace trash if nothing else links it.`))try{await c(e.id)}catch{}},[c]),E=(0,X.useCallback)((e,t)=>{r(n=>n.map(n=>n.id===e?{...n,data:{...n.data||{},status:t,completed:t===`completed`}}:n))},[r]),D=(0,X.useMemo)(()=>{let e=h?[...n]:n.filter(e=>!$b.has(String(e.data?.status??`pending`)));return e.sort((e,t)=>{let n=new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime();return p===`asc`?n:-n}),e},[n,p,h]),O=(0,X.useMemo)(()=>n.filter(e=>$b.has(String(e.data?.status??`pending`))).length,[n]),k=(0,X.useMemo)(()=>{let e=l.trim().toLowerCase();if(!e)return[];let t=[];for(let n of D){let r=String(n.data?.description??``),i=String(n.data?.title??``),a=r.toLowerCase().indexOf(e);a>=0?t.push({docId:n.id,offset:a}):i.toLowerCase().includes(e)&&t.push({docId:n.id,offset:-1})}return t},[l,D]),A=k.length?k[Math.min(d,k.length-1)]:null;(0,X.useEffect)(()=>{A&&x.current.get(A.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[A]);let j=(0,X.useCallback)(e=>{if(!k.length)return;let t=e?(d+1)%k.length:d;e&&f(t);let n=k[t],r=S.current.get(n.docId);r&&n.offset>=0&&(r.focus(),r.setSelectionRange(n.offset,n.offset+l.trim().length)),x.current.get(n.docId)?.scrollIntoView({block:`center`,behavior:`smooth`})},[k,d,l]);return t?(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-3 py-2`,children:[(0,Z.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Z.jsx)(pr,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Z.jsx)(`input`,{value:l,onChange:e=>{u(e.target.value),f(0)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),j(!0))},placeholder:`Search todos…`,spellCheck:!1,className:`w-full rounded-md border border-input bg-transparent py-1 pl-7 pr-14 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring`}),l.trim()&&(0,Z.jsx)(`span`,{className:`absolute right-2 top-1/2 -translate-y-1/2 text-[10px] tabular-nums text-muted-foreground`,children:k.length?`${Math.min(d+1,k.length)}/${k.length}`:`0/0`})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),className:K(`rounded-md border p-1.5 transition-colors`,h?`border-foreground text-foreground`:`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:h?`Hide done items`:`Show done items${O?` (${O})`:``}`,"aria-label":h?`Hide done items`:`Show done items`,children:h?(0,Z.jsx)(Vt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(kn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(e=>e===`desc`?`asc`:`desc`),className:`rounded-md border border-border p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:p===`desc`?`Newest first (click for oldest first)`:`Oldest first (click for newest first)`,"aria-label":`Toggle sort order`,children:p===`desc`?(0,Z.jsx)(hn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Et,{className:`h-3.5 w-3.5`})}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>v(!0),className:`flex items-center gap-1 rounded-md bg-primary px-2 py-1.5 text-xs text-primary-foreground`,title:`Add a todo`,children:[(0,Z.jsx)(U,{className:`h-3.5 w-3.5`}),`Todo`]})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:[_&&(0,Z.jsx)(tx,{target:t,onCreated:()=>{v(!1),s()},onCancel:()=>v(!1)}),i&&!n.length&&(0,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{className:`h-5 w-5 animate-spin text-muted-foreground`})}),a&&(0,Z.jsx)(`p`,{className:`px-4 py-6 text-center text-sm text-destructive`,children:a}),!i&&!a&&!D.length&&!_&&(0,Z.jsx)(`p`,{className:`px-4 py-10 text-center text-sm text-muted-foreground`,children:O?`Nothing pending - ${O} done item${O>1?`s`:``} hidden.`:`No todos here yet - add the first one.`}),D.map(e=>(0,Z.jsx)(ex,{doc:e,updateWorkspace:o?.workspaceName??null,registerEl:C,registerBody:w,highlighted:A?.docId===e.id,onLinkTo:()=>b(e.id),onDelete:()=>T(e),onStatusSaved:E},e.id))]}),y!==null&&(0,Z.jsx)(Wb,{documentId:y,workspaceName:o?.workspaceName,onClose:()=>b(null)})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:bs(t)})}var rx=(0,X.createContext)(null);function ix(){let e=(0,X.useContext)(rx);if(!e)throw Error(`useLensFeed must be used within a LensFeedProvider`);return e}function ax(e=!0){let{registerViewer:t}=ix();(0,X.useEffect)(()=>{if(e)return t()},[e,t])}var ox=[{id:`720p`,label:`720p`,width:1280,height:720},{id:`1080p`,label:`1080p`,width:1920,height:1080},{id:`4k`,label:`4K`,width:3840,height:2160}],sx=`canvas.lens.camera`,cx={min:1,max:4,step:.1,hardware:!1};function lx(){let e={deviceId:null,resolution:`1080p`};try{let t=JSON.parse(localStorage.getItem(sx)||`null`);return t?{deviceId:typeof t.deviceId==`string`?t.deviceId:null,resolution:ox.some(e=>e.id===t.resolution)?t.resolution:e.resolution}:e}catch{return e}}function ux(e,t){let n=ox.find(t=>t.id===e.resolution)??ox[1];return{...t&&e.deviceId?{deviceId:{exact:e.deviceId}}:{facingMode:`environment`},width:{ideal:n.width},height:{ideal:n.height}}}function dx(e={}){let t=(0,X.useRef)(null),n=(0,X.useRef)(e.onEnded);(0,X.useEffect)(()=>{n.current=e.onEnded});let r=(0,X.useRef)(null),i=(0,X.useRef)(null),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(lx),p=(0,X.useRef)(d),[m,h]=(0,X.useState)([]),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(null),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(1),w=(0,X.useRef)(1),[T,E]=(0,X.useState)(!1),D=(0,X.useRef)(null),O=()=>r.current?.getVideoTracks()[0]??null,k=(0,X.useCallback)(async e=>{let t=O();if(!t)return!1;try{return await t.applyConstraints({advanced:[e]}),!0}catch{return!1}},[]),A=(0,X.useCallback)(async()=>{try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`videoinput`&&e.deviceId);h(e.map((e,t)=>({deviceId:e.deviceId,label:e.label||`Camera ${t+1}`})))}catch{}},[]),j=(0,X.useCallback)(()=>{D.current&&window.clearTimeout(D.current),r.current?.getTracks().forEach(e=>e.stop()),r.current=null,t.current&&(t.current.srcObject=null),c(null),o(!1),_(!1),y(null),x(null),C(1),w.current=1,E(!1)},[]),M=(0,X.useCallback)(async(e,i)=>{r.current=e,e.getVideoTracks().forEach(e=>{e.onended=()=>{j(),n.current?.()}}),t.current&&(t.current.srcObject=e,await t.current.play().catch(()=>{}));let a=e.getVideoTracks()[0],s=a?.getSettings();if(x(s?.width&&s?.height?{width:s.width,height:s.height}:null),_(i),E(!1),i&&a){let e=a.getCapabilities?.()??{};y(e),e.focusMode?.includes(`continuous`)&&await k({focusMode:`continuous`});let t=a.getSettings().zoom;C(e.zoom?t??e.zoom.min:1),w.current=1,A()}c(e),o(!0)},[j,k,A]),N=(0,X.useCallback)(async e=>{try{return await navigator.mediaDevices.getUserMedia({video:ux(e,!0),audio:!1})}catch(t){let n=t?.name;if(e.deviceId&&(n===`OverconstrainedError`||n===`NotFoundError`||n===`NotReadableError`))return navigator.mediaDevices.getUserMedia({video:ux(e,!1),audio:!1});throw t}},[]),P=(0,X.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Camera needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getUserMedia)return u(`Camera API not available in this browser.`),!1;try{let e=await N(p.current);return await M(e,!0),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Camera permission denied.`:t===`NotFoundError`?`No camera found.`:`Camera failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M,N]),ee=(0,X.useCallback)(async()=>{if(u(null),!window.isSecureContext)return u(`Screen capture needs a secure context (https or localhost).`),!1;if(!navigator.mediaDevices?.getDisplayMedia)return u(`Screen capture API not available in this browser.`),!1;try{let e=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1280},height:{ideal:720}},audio:!1});return await M(e,!1),!0}catch(e){let t=e?.name;return u(t===`NotAllowedError`?`Screen capture cancelled.`:`Screen capture failed: ${e?.message||t||`unknown error`}`),o(!1),!1}},[M]),F=(0,X.useCallback)(e=>{let t={...p.current,...e};p.current=t,f(t);try{localStorage.setItem(sx,JSON.stringify(t))}catch{}!r.current||!g||(r.current.getTracks().forEach(e=>{e.onended=null,e.stop()}),r.current=null,P().then(e=>{e||(j(),n.current?.())}))},[g,P,j]),I=(0,X.useCallback)(e=>{C(e),v?.zoom?k({zoom:e}):w.current=e},[v,k]),L=(0,X.useCallback)(e=>{k({torch:e}).then(t=>{t&&E(e)})},[k]),R=!!v?.focusMode?.some(e=>e===`single-shot`||e===`continuous`),te=(0,X.useCallback)(e=>{let t=v?.focusMode??[];if(!t.length)return;D.current&&window.clearTimeout(D.current);let n=navigator.mediaDevices.getSupportedConstraints(),r=e&&n.pointsOfInterest?{pointsOfInterest:[e]}:{};t.includes(`single-shot`)?(k({...r,focusMode:`single-shot`}),t.includes(`continuous`)&&(D.current=window.setTimeout(()=>void k({...r,focusMode:`continuous`}),1500))):k({...r,focusMode:`continuous`})},[v,k]),ne=(0,X.useCallback)((e=640,n=.72)=>{let r=t.current;if(!r||r.readyState<2||!r.videoWidth)return null;let a=Math.max(1,w.current),o=r.videoWidth/a,s=r.videoHeight/a,c=(r.videoWidth-o)/2,l=(r.videoHeight-s)/2,u=Math.min(1,e/Math.max(o,s)),d=Math.round(o*u),f=Math.round(s*u);i.current||=document.createElement(`canvas`);let p=i.current;p.width=d,p.height=f;let m=p.getContext(`2d`);return m?(m.drawImage(r,c,l,o,s,0,0,d,f),p.toDataURL(`image/jpeg`,n)):null},[]);return(0,X.useEffect)(()=>j,[j]),{videoRef:t,stream:s,active:a,error:l,start:P,startScreen:ee,stop:j,captureFrame:ne,camera:(0,X.useMemo)(()=>g?{devices:m,prefs:d,setPrefs:F,size:b,zoomRange:v?.zoom?{min:v.zoom.min,max:v.zoom.max,step:v.zoom.step||.1,hardware:!0}:cx,zoom:S,setZoom:I,torchSupported:!!v?.torch,torch:T,setTorch:L,focusSupported:R,focusAt:te}:null,[g,m,d,F,b,v,S,I,T,L,R,te])}}async function fx(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 J.postEnvelope(`${Sr.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 px=[{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}],mx=1e3,hx=32,gx=12,_x=`canvas.lens.fit`;function vx({className:e,interactive:t=!1}){let{stream:n,camera:r,fit:i}=ix(),a=(0,X.useRef)(null),[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=a.current;if(e)return e.srcObject=n,n&&e.play().catch(()=>{}),()=>{e.srcObject=null}},[n]),(0,X.useEffect)(()=>{if(!o)return;let e=window.setTimeout(()=>s(null),900);return()=>window.clearTimeout(e)},[o]);let c=r&&!r.zoomRange.hardware?r.zoom:1;return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`video`,{ref:a,muted:!0,playsInline:!0,onClick:t?e=>{let t=a.current;if(!t||!r?.focusSupported||!t.videoWidth)return;let n=t.getBoundingClientRect(),o=(e.clientX-n.left)/n.width,l=(e.clientY-n.top)/n.height,u=.5+(o-.5)/c,d=.5+(l-.5)/c,f=i===`contain`?Math.min(n.width/t.videoWidth,n.height/t.videoHeight):Math.max(n.width/t.videoWidth,n.height/t.videoHeight),p=t.videoWidth*f/n.width,m=t.videoHeight*f/n.height,h=.5+(u-.5)/p,g=.5+(d-.5)/m;h<0||h>1||g<0||g>1||(r.focusAt({x:h,y:g}),s({x:o,y:l,key:Date.now()}))}:void 0,style:c===1?void 0:{transform:`scale(${c})`},className:K(e,i===`contain`?`object-contain`:`object-cover`,t&&r?.focusSupported&&`cursor-crosshair`)}),o&&(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute h-10 w-10 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white/90 animate-fade-in`,style:{left:`${o.x*100}%`,top:`${o.y*100}%`}},o.key)]})}function yx({children:e}){let t=Uo(),n=(0,X.useRef)(t);(0,X.useEffect)(()=>{n.current=t});let r=t?.state.activeWorkspaceName??null,i=t!==null,a=(0,X.useRef)(()=>{}),{videoRef:o,stream:s,camera:c,error:l,start:u,startScreen:d,stop:f,captureFrame:p}=dx({onEnded:()=>a.current()}),[m,h]=(0,X.useState)(null),g=(0,X.useRef)(m);(0,X.useEffect)(()=>{g.current=m},[m]);let[_,v]=(0,X.useState)(null),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(mx),[C,w]=(0,X.useState)(``),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(null),[k,A]=(0,X.useState)(null),[j,M]=(0,X.useState)(null),[N,P]=(0,X.useState)([]),[ee,F]=(0,X.useState)(null),[I,L]=(0,X.useState)(null),R=I&&I.frame===ee?I:null,te=(0,X.useRef)(null),[ne,z]=(0,X.useState)(0),[re,ie]=(0,X.useState)(``),[ae,oe]=(0,X.useState)(()=>{try{return localStorage.getItem(_x)===`cover`?`cover`:`contain`}catch{return`contain`}}),se=(0,X.useCallback)(e=>{oe(e);try{localStorage.setItem(_x,e)}catch{}},[]),B=(0,X.useRef)({running:!1,paused:!1,consumer:null,workspaceRef:``,contextPath:null,text:``,maxDistance:NaN,rateMs:mx,snapshot:!1}),ce=(0,X.useRef)([]),V=(0,X.useRef)(new Map),le=(0,X.useRef)(null),ue=(0,X.useRef)(null),de=(0,X.useRef)(null),fe=(0,X.useRef)(0),pe=(0,X.useRef)(``),me=(0,X.useRef)(!1),he=(0,X.useRef)(async()=>{}),ge=(0,X.useRef)(()=>{});(0,X.useEffect)(()=>{B.current.text=T,B.current.maxDistance=C===``?NaN:Number(C),B.current.rateMs=x,B.current.paused=y},[T,C,x,y]);let _e=(0,X.useCallback)(()=>(z(e=>e+1),()=>z(e=>Math.max(0,e-1))),[]),ve=(0,X.useCallback)(e=>{ce.current=[...ce.current.slice(-2),e];let t=ce.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=le.current;(!a||a.length!==i.length||a.some((e,t)=>e!==i[t]))&&(le.current=i,n.current?.setLensIds(i))},[]),ye=(0,X.useCallback)((e,t)=>{for(let n of e)V.current.set(n.id,{doc:n,distance:t.get(n.id)});let n=e.map(e=>e.id);ce.current=[...ce.current.slice(-2),n];let r=ce.current,i=r[r.length-1]??[],a=r.length<2?i:i.filter(e=>r.filter(t=>t.includes(e)).length>=2),o=[...V.current.keys()].filter(e=>!i.includes(e)&&r.filter(t=>t.includes(e)).length>=2),s=[...a,...o].map(e=>V.current.get(e)).filter(e=>!!e);M(s.length),P(s)},[]),H=(0,X.useCallback)(async(e,t)=>{let r=performance.now(),i=t.consumer===`applet`;de.current?.abort();let a=new AbortController;de.current=a;try{let o=n.current?.state,s=!i&&o?.activeContextType===`context`,c=await fx(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?[...V_(o.filters.timeline),...R_(o.filters.geo),...z_(o.filters.lens,o.filters.geo.includeUnlocated)]:void 0,applyCanvasQuerySpec:!s&&void 0,limit:i?gx:hx,idsOnly:!i,debug:i,signal:a.signal});return a.signal.aborted||B.current!==t||!t.running?!1:(fe.current=0,A(Math.round(performance.now()-r)),O(null),i?ye(c.documents,new Map((c.distances??[]).map(e=>[e.id,e.distance]))):ve(c.ids),!0)}catch(e){return a.signal.aborted||B.current!==t||!t.running?!1:(fe.current++,e?.name!==`AbortError`&&O(e?.message||`search failed`),!1)}},[ye,ve]),be=(0,X.useCallback)(async()=>{let e=B.current;if(!e.running)return;let t=performance.now();if(!e.paused&&!e.snapshot){let t=p();t&&e.workspaceRef&&await H(t,e)}if(B.current.running){let e=Math.max(fe.current?Math.min(3e4,1e3*2**Math.min(fe.current-1,5)):0,B.current.rateMs-(performance.now()-t));ue.current=window.setTimeout(()=>void he.current(),e)}},[p,H]);(0,X.useEffect)(()=>{he.current=be},[be]);let U=(0,X.useCallback)(()=>{let e=B.current.consumer===`filter`;B.current.running=!1,fe.current=0,B.current.consumer=null,ue.current&&window.clearTimeout(ue.current),de.current?.abort(),f(),ce.current=[],V.current.clear(),le.current=null,h(null),v(null),b(!1),ie(``),P([]),F(null),M(null),A(null),O(null),e&&n.current?.state.activeContextType!==`context`&&n.current?.setLensIds(null)},[f]);(0,X.useEffect)(()=>{a.current=U},[U]);let xe=(0,X.useCallback)(async(e,t,r)=>{if(!r.workspaceRef||me.current||(B.current.running&&U(),e===`photo`&&!r.image))return!1;me.current=!0;let i=e===`photo`?!0:e===`camera`?await u():await d();return me.current=!1,i?(ce.current=[],V.current.clear(),le.current=null,P([]),M(null),O(null),ie(r.workspaceRef),B.current={...B.current,running:!0,paused:!1,consumer:t,workspaceRef:r.workspaceRef,contextPath:r.contextPath??null,snapshot:e===`photo`},F(e===`photo`?r.image:null),h(e),v(t),b(!1),t===`filter`&&n.current?.setLensIds([]),e===`photo`?ge.current(r.image):be(),!0):!1},[u,d,U,be]),Se=JSON.stringify(t?{contextId:t.state.activeContextId,path:t.state.activeContextPath,tree:t.state.activeTreeName,features:t.state.filters.features,timeline:t.state.filters.timeline,geo:t.state.filters.geo,gps:t.state.filters.lens.gps}:null);(0,X.useEffect)(()=>{pe.current!==Se&&(pe.current=Se,B.current.consumer===`filter`&&(de.current?.abort(),ce.current=[],le.current=null,n.current?.setLensIds([])))},[Se]);let Ce=(0,X.useCallback)(e=>{B.current.contextPath=e},[]),W=(0,X.useCallback)(e=>{B.current.paused=e,b(e)},[]),G=JSON.stringify([T,C,Se]),we=(0,X.useRef)(G);(0,X.useEffect)(()=>{we.current=G});let Te=(0,X.useCallback)(e=>{let t=B.current;!t.running||!t.workspaceRef||(te.current={frame:e,key:we.current},ce.current=[],V.current.clear(),le.current=null,M(null),H(e,t))},[H]);(0,X.useEffect)(()=>{ge.current=Te},[Te]);let Ee=(0,X.useCallback)(()=>{let e=B.current;if(!e.running)return;let t=p(1280,.85);t&&(e.snapshot=!0,F(t),Te(t))},[p,Te]),De=(0,X.useCallback)(()=>{if(B.current.running&&g.current===`photo`){U();return}B.current.snapshot=!1,de.current?.abort(),ce.current=[],V.current.clear(),F(null)},[U]),Oe=(0,X.useCallback)(async(e,t,n)=>{let r=B.current;return r.running&&r.consumer===t&&g.current===`camera`?(r.snapshot=!0,F(e),Te(e),!0):xe(`photo`,t,{...n,image:e})},[xe,Te]);(0,X.useEffect)(()=>{if(!ee)return;let e=!0,t=new Image;return t.onload=()=>{e&&L({frame:ee,width:t.naturalWidth,height:t.naturalHeight})},t.src=ee,()=>{e=!1}},[ee]),(0,X.useEffect)(()=>{if(!ee)return;let e=te.current;if(e&&e.frame===ee&&e.key===G)return;let t=window.setTimeout(()=>Te(ee),350);return()=>window.clearTimeout(t)},[ee,G,Te]),(0,X.useEffect)(()=>{!i||!B.current.running||r&&r===B.current.workspaceRef||U()},[i,r,U]);let ke=(0,X.useCallback)(()=>{let e=n.current;if(e){if(B.current.consumer===`applet`){e.setView(`apps`),e.openApplet(`lens`);return}e.setView(`tools`),e.setToolsTab(`lens`)}},[]);(0,X.useEffect)(()=>U,[U]);let Ae=(0,X.useMemo)(()=>({source:m,running:m!==null,paused:y,consumer:_,stream:s,camera:c,fit:ae,setFit:se,workspaceRef:re,rateMs:x,setRateMs:S,maxDistance:C,setMaxDistance:w,text:T,setText:E,error:l||D,latencyMs:k,lastCount:j,hits:N,start:xe,setContextPath:Ce,stop:U,setPaused:W,snapshot:ee,takeSnapshot:Ee,clearSnapshot:De,snapshotSize:R,searchPhoto:Oe,reopen:ke,hasViewer:ne>0,registerViewer:_e}),[m,y,_,s,c,ae,se,re,x,C,T,l,D,k,j,N,xe,Ce,U,W,ee,Ee,De,R,Oe,ke,ne,_e]);return(0,Z.jsxs)(rx.Provider,{value:Ae,children:[e,(0,Z.jsx)(`video`,{ref:o,muted:!0,playsInline:!0,"aria-hidden":!0,className:`pointer-events-none fixed bottom-0 left-0 h-px w-px opacity-0`})]})}var bx=`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`,xx=`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`,Sx=e=>`${e<10?e.toFixed(1):Math.round(e)}×`;function Cx({className:e}){let{camera:t,fit:n,setFit:r}=ix();if(!t)return null;let{devices:i,prefs:a,setPrefs:o,size:s,zoomRange:c,zoom:l,setZoom:u}=t,d=c.max>c.min;return(0,Z.jsxs)(`div`,{className:K(`flex flex-col gap-2`,e),children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i.length>1&&(0,Z.jsxs)(`select`,{className:K(bx,`max-w-[12rem] flex-1`),value:a.deviceId??``,onChange:e=>o({deviceId:e.target.value||null}),title:`Camera / lens. On phones with several rear cameras, pick the main or wide one if the picture is too zoomed in.`,"aria-label":`Camera`,children:[(0,Z.jsx)(`option`,{value:``,children:`Default rear camera`}),i.map(e=>(0,Z.jsx)(`option`,{value:e.deviceId,children:e.label},e.deviceId))]}),(0,Z.jsx)(`select`,{className:bx,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:ox.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(n===`contain`?`cover`:`contain`),className:xx,title:n===`contain`?`Showing the whole frame — switch to fill the preview`:`Filling the preview (edges cropped) — switch to the whole frame`,"aria-label":n===`contain`?`Fill preview`:`Fit whole frame`,children:n===`contain`?(0,Z.jsx)(Zt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(pn,{className:`h-3.5 w-3.5`})}),t.focusSupported&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t.focusAt(),className:xx,title:`Refocus (or tap the preview to focus on a spot)`,children:[(0,Z.jsx)(cr,{className:`h-3.5 w-3.5`}),` Focus`]}),t.torchSupported&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t.setTorch(!t.torch),className:K(xx,t.torch&&`border-foreground text-foreground`),"aria-pressed":t.torch,title:t.torch?`Torch off`:`Torch on`,children:t.torch?(0,Z.jsx)(Lt,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Wn,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[s.width,`×`,s.height]})]}),d&&(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,title:c.hardware?`Optical/sensor zoom`:`Digital zoom — crops the searched frame too`,children:[(0,Z.jsx)(B,{className:`h-3.5 w-3.5 shrink-0`}),(0,Z.jsx)(`input`,{type:`range`,min:c.min,max:c.max,step:c.step,value:l,onChange:e=>u(Number(e.target.value)),onDoubleClick:()=>u(c.min),className:`h-1 min-w-0 flex-1 accent-foreground`,"aria-label":`Zoom`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>u(c.min),className:`w-10 shrink-0 text-right tabular-nums hover:text-foreground`,title:`Reset zoom`,children:Sx(l)})]})]})}function wx(){let{running:e,source:t,snapshot:n,takeSnapshot:r,clearSnapshot:i,fit:a}=ix();return e?n?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`img`,{src:n,alt:`Snapshot being searched`,className:K(`absolute inset-0 h-full w-full bg-black`,a===`contain`?`object-contain`:`object-cover`)}),(0,Z.jsx)(`span`,{className:`pointer-events-none absolute left-2 top-2 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-white`,children:t===`photo`?`Photo`:`Snapshot`}),(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`absolute bottom-2 left-1/2 flex h-9 -translate-x-1/2 items-center gap-1.5 rounded-full bg-black/60 px-3 text-xs font-medium text-white backdrop-blur transition-colors hover:bg-black/75`,title:t===`photo`?`Close the photo and clear its matches`:`Discard the snapshot and go back to the live feed`,children:t===`photo`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`}),` Close`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(He,{className:`h-3.5 w-3.5`}),` Live`]})})]}):t===`photo`?null:(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Take a snapshot and search it`,title:`Snapshot: freeze this frame and search for similar items`,className:`absolute bottom-2 left-1/2 flex h-12 w-12 -translate-x-1/2 items-center justify-center rounded-full border-4 border-white/90 bg-white/25 text-white shadow-lg backdrop-blur transition-transform hover:bg-white/40 active:scale-90`,children:(0,Z.jsx)(Wt,{className:`h-5 w-5`})}):null}async function Tx(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 Ex({consumer:e,workspaceRef:t,contextPath:n,disabled:r,className:i}){let{searchPhoto:a}=ix(),o=(0,X.useRef)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(null),d=async r=>{if(r){c(!0),u(null);try{let i=await Tx(r);await a(i,e,{workspaceRef:t,contextPath:n})}catch{u(`Could not read that image.`)}finally{c(!1),o.current&&(o.current.value=``)}}};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>o.current?.click(),disabled:r||s||!t,className:i,title:l??`Search with a photo from the camera app or gallery`,children:[(0,Z.jsx)(rn,{className:`h-3.5 w-3.5`}),` `,s?`Reading…`:`Photo`]}),(0,Z.jsx)(`input`,{ref:o,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>void d(e.target.files?.[0])}),l&&(0,Z.jsx)(`span`,{className:`text-xs text-destructive`,children:l})]})}var Dx=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring`,Ox=`h-8 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`;function kx({workspaceRef:e,doc:t,distance:n,onOpen:r}){let i=ki(t),{blobUrl:a}=nh(e,t.id,256,{enabled:i}),o=Ui(t);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(t),title:`Open ${o.title}`,className:`rounded-lg border border-border bg-card overflow-hidden flex flex-col text-left cursor-pointer transition-colors hover:border-foreground/30 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(`div`,{className:`aspect-square bg-muted/40 flex items-center justify-center overflow-hidden`,children:i&&a?(0,Z.jsx)(`img`,{src:a,alt:o.title,className:`h-full w-full object-cover`}):(0,Z.jsx)(Dp,{document:t,size:10})}),(0,Z.jsxs)(`div`,{className:`p-2 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-xs font-medium truncate`,title:o.title,children:o.title}),(0,Z.jsxs)(`div`,{className:`text-[10px] text-muted-foreground truncate`,children:[o.schemaLabel,n==null?``:` · d=${n.toFixed(3)}`]})]})]})}function Ax(){let e=Vb(),t=i_(),n=ix(),{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:[];ax(p);let _=p?n.snapshotSize??n.camera?.size:null,v=!!_&&_.height>_.width,y=e=>{d&&n.start(e,`applet`,{workspaceRef:d,contextPath:f})},{setContextPath:b}=n;return(0,X.useEffect)(()=>{p&&b(f)},[p,f,b]),e?.mode===`workspace`?(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3 overflow-y-auto p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`select`,{className:Dx,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:px.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(Ox,`w-44`),placeholder:`Optional text (fused mode)`,value:a,onChange:e=>o(e.target.value)}),(0,Z.jsx)(`input`,{className:K(Ox,`w-28`),placeholder:`max distance`,inputMode:`decimal`,value:s,onChange:e=>c(e.target.value),title:`Cosine-distance floor (0 = identical). Empty = top-K.`}),p?(0,Z.jsxs)(`button`,{type:`button`,onClick:n.stop,className:`flex h-8 items-center gap-1 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground transition-colors hover:bg-destructive/90`,children:[(0,Z.jsx)(Se,{className:`h-3.5 w-3.5`}),` `,n.source===`photo`?`Close photo`:`Stop`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y(`camera`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(z,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y(`screen`),disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`,children:[(0,Z.jsx)(fe,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(Ex,{consumer:`applet`,workspaceRef:d,contextPath:f,disabled:m,className:`flex h-8 items-center gap-1 rounded-md bg-foreground px-3 text-xs font-medium text-background transition-colors hover:bg-foreground/90 disabled:opacity-50`})]}),(0,Z.jsxs)(`div`,{className:K(`relative shrink-0 overflow-hidden rounded-xl border border-border bg-black/80`,v?`aspect-[3/4] max-h-[60vh]`:`aspect-video max-h-80`),children:[p&&(0,Z.jsx)(vx,{className:`h-full w-full`,interactive:!0}),p&&(0,Z.jsx)(wx,{}),!p&&(0,Z.jsxs)(`div`,{className:`absolute inset-0 flex items-center justify-center text-sm text-muted-foreground`,children:[(0,Z.jsx)(g,{className:`mr-2 h-4 w-4`}),` camera off · or pick a photo`]})]}),p&&(0,Z.jsx)(Cx,{className:`shrink-0`}),(0,Z.jsx)(`div`,{className:`shrink-0 text-xs text-muted-foreground`,children:u?(0,Z.jsx)(`span`,{className:`text-destructive`,children:u}):p?(0,Z.jsxs)(Z.Fragment,{children:[n.snapshot?`snapshot`:`live`,` · `,l==null?`searching…`:`${l} ms/frame`,` · `,h.length,` match`,h.length===1?``:`es`,f?` · scoped to ${f}`:``]}):m?`The Lens filter is using the camera. Stop it there first.`:`Frames are ephemeral: embedded for the query, never stored or indexed.`}),h.length===0?(0,Z.jsx)(`div`,{className:`flex min-h-24 flex-1 items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground`,children:p?n.snapshot?`Nothing similar in the snapshot`:`Nothing matching in view`:`Matches appear here`}):(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4`,children:h.map(e=>(0,Z.jsx)(kx,{workspaceRef:d,doc:e.doc,distance:e.distance,onOpen:e=>t.open(e,d)},e.doc.id))})]}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:`Lens searches a workspace. Bind it to a workspace path to start.`})}function jx({doc:e,scope:t,onOpen:n,onRemove:r}){let{blobUrl:i,loading:a}=nh(t.workspaceName,e.id,256,{version:e.checksumArray?.[0]??null}),o=String(e.data?.title??`Sketch`);return(0,Z.jsxs)(`div`,{className:`group relative overflow-hidden rounded-lg border bg-card shadow-elevation-2 transition-shadow hover:shadow-elevation-3`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:n,className:`block w-full text-left`,children:[(0,Z.jsx)(`div`,{className:`flex aspect-[4/3] items-center justify-center overflow-hidden bg-muted/30`,children:i?(0,Z.jsx)(`img`,{src:i,alt:o,className:`h-full w-full object-contain`}):(0,Z.jsx)(rt,{className:`h-6 w-6 text-muted-foreground ${a?`animate-pulse`:``}`})}),(0,Z.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,Z.jsx)(`div`,{className:`truncate text-xs font-medium`,children:o}),(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground`,children:Kb(e.updatedAt||e.createdAt)})]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:r,"aria-label":`Delete ${o}`,className:`absolute right-1.5 top-1.5 rounded-md bg-background/80 p-1 opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})}function Mx({autoAdd:e}){let t=Vb(),{docs:n,loading:r,error:i,scope:a,reload:o,removeDoc:s}=qb(t,Pa),[c,l]=(0,X.useState)(e?`new`:null),{showErrorToast:u}=Wr();return t?(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 p-3`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,className:`self-start`,onClick:()=>l(`new`),children:[(0,Z.jsx)(U,{className:`mr-1.5 h-4 w-4`}),`New sketch`]}),i&&(0,Z.jsx)(`p`,{className:`text-sm text-destructive`,children:i}),r&&!n.length&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketches…`}),!r&&!n.length&&!i&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No sketches here yet.`}),a&&n.length>0&&(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4`,children:n.map(e=>(0,Z.jsx)(jx,{doc:e,scope:a,onOpen:()=>l(e),onRemove:()=>{confirm(`Delete "${String(e.data?.title??`Sketch`)}"?`)&&s(e.id).catch(e=>u(e instanceof Error?e.message:`Failed to delete sketch`))}},`${e.id}:${e.checksumArray?.[0]??``}`))}),c&&a&&(0,Z.jsx)(X.Suspense,{fallback:(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Z.jsx)(d_,{doc:c===`new`?null:c,workspaceName:a.workspaceName,target:t,onSaved:()=>{l(null),o()},onClose:()=>l(null)})}),c&&!a&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Resolving destination…`})})]}):(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Select a context or workspace path first.`})}var Nx=[{id:`notes`,label:`Notes`,icon:xn,modes:[`context`],description:`All notes in the current context, editable in place`,Component:Zb},{id:`todo`,label:`Todos`,icon:On,modes:[`context`],description:`Todos in the current context, done items hidden by default`,Component:nx},{id:`sketch`,label:`Sketch`,icon:rt,modes:[`context`],description:`Quick-sketch into the current context; tap a sketch to keep editing`,Component:Mx},{id:`lens`,label:`Lens`,icon:ze,modes:[`context`],description:`Point a camera at things; matching documents surface live`,Component:Ax}];function Px(e){return Nx.filter(t=>t.modes.includes(e))}function Fx({target:e,children:t}){return(0,Z.jsx)(Bb.Provider,{value:e,children:t})}function Ix({children:e}){let[t,n]=(0,X.useState)(null),r=(0,X.useCallback)((e,t)=>n({document:e,workspaceId:t}),[]),i=(0,X.useCallback)(()=>n(null),[]),a=(0,X.useMemo)(()=>({open:r,close:i}),[r,i]);return(0,Z.jsxs)(n_.Provider,{value:a,children:[e,(0,Z.jsx)(N_,{document:t?.document??null,isOpen:!!t,onClose:i,workspaceId:t?.workspaceId})]})}var Lx=`universe`;function Rx(){let{appletId:e}=ll(),[t,n]=Ou(),r=Nx.find(t=>t.id===e),i=t.get(`context`),a=t.get(`workspace`)||Lx,o=t.get(`path`)||`/`,s=t.get(`tree`)||`context`,c=t.get(`add`)===`1`,l=(0,X.useMemo)(()=>i?{mode:`context`,contextId:i}:{mode:`workspace`,workspaceName:a,path:o,treeName:s,treeType:s===`directory`?`directory`:`context`},[i,a,o,s]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)([]);(0,X.useEffect)(()=>{Xr().then(d).catch(()=>d([])),ns().then(p).catch(()=>p([]))},[]);let[m,h]=(0,X.useState)(o),[g,_]=(0,X.useState)(o);g!==o&&(_(o),h(o));let v=e=>{let r=new URLSearchParams(t);r.delete(`add`);for(let[t,n]of Object.entries(e))n===null?r.delete(t):r.set(t,n);n(r,{replace:!0})};if(!r)return(0,Z.jsxs)(`div`,{className:`flex h-viewport flex-col items-center justify-center gap-3 surface-desk`,children:[(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Unknown app`,e?` "${e}"`:``,`.`]}),(0,Z.jsx)(`div`,{className:`flex gap-2`,children:Nx.map(e=>(0,Z.jsx)(Su,{to:`/apps/${e.id}`,className:`rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted`,children:e.label},e.id))})]});let y=i?`context`:`path`;return(0,Z.jsx)(Ix,{children:(0,Z.jsx)(yx,{children:(0,Z.jsxs)(`div`,{className:`flex h-viewport flex-col surface-desk p-shell gap-shell`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 rounded-xl border bg-card px-3 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(r.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:r.label}),(0,Z.jsx)(`div`,{className:`ml-2 flex overflow-hidden rounded-md border border-border`,children:[`path`,`context`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{e!==y&&v(e===`path`?{context:null}:{context:f[0]?.id??``,workspace:null,path:null,tree:null})},className:K(`px-2.5 py-1 text-xs capitalize transition-colors`,y===e?`bg-foreground text-background`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:e},e))}),y===`path`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`select`,{value:a,onChange:e=>v({workspace:e.target.value,path:`/`}),className:`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Workspace`,children:[!u.some(e=>e.name===a)&&(0,Z.jsx)(`option`,{value:a,children:a}),u.map(e=>(0,Z.jsx)(`option`,{value:e.name,children:e.label||e.name},e.id))]}),(0,Z.jsx)(`input`,{value:m,onChange:e=>h(e.target.value),onBlur:()=>{let e=m.trim()||`/`;e!==o&&v({path:e})},onKeyDown:e=>{e.key===`Enter`&&e.target.blur()},spellCheck:!1,placeholder:`/`,className:`h-7 w-40 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,"aria-label":`Path`})]}):(0,Z.jsxs)(`select`,{value:i??``,onChange:e=>v({context:e.target.value}),className:`h-7 max-w-56 rounded-md border border-input bg-transparent px-1.5 text-xs`,"aria-label":`Context`,children:[!i&&(0,Z.jsx)(`option`,{value:``,children:`Pick a context…`}),f.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.id,e.url?` (${e.url})`:``]},e.id))]}),(0,Z.jsx)(`div`,{className:`grow`}),(0,Z.jsx)(Su,{to:`/home`,className:`flex items-center gap-1 rounded-md p-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,title:`Open the full Canvas app`,children:(0,Z.jsx)(xe,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-elevation-2`,children:y===`context`&&!i?(0,Z.jsxs)(`div`,{className:`flex h-full items-center justify-center p-6 text-center text-sm text-muted-foreground`,children:[`Pick a context above to bind `,r.label,` to it.`]}):(0,Z.jsx)(Fx,{target:l,children:(0,Z.jsx)(r.Component,{autoAdd:c},JSON.stringify(l))})})]})})})}var zx=`false`,Bx=`false`,Vx=zx===`true`,Hx=Bx===`true`;function Ux(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,Vx||u?.()};async function f(){if(`serviceWorker`in navigator){if(c=await m(async()=>{let{Workbox:e}=await import(`./workbox-window.prod.es5-Bd17z0YL.js`);return{Workbox:e}},[]).then(({Workbox:e})=>new e(`/sw.js`,{scope:`/`,type:`classic`})).catch(e=>{s?.(e)}),!c)return;if(u=()=>{c?.messageSkipWaiting()},!Hx){if(Vx)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 Wx=new Set,Gx=!1,Kx=Ux({immediate:!0,onRegisteredSW(e,t){t&&setInterval(()=>{t.update()},36e5)},onNeedRefresh(){Gx=!0,Wx.forEach(e=>e())}});function qx(e){return Wx.add(e),Gx&&e(),()=>{Wx.delete(e)}}function Jx(){Kx(!0)}function Yx(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>qx(()=>t(!0)),[]),!e||n?null:(0,Z.jsx)(`div`,{className:`fixed bottom-4 left-1/2 z-50 -translate-x-1/2`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 rounded-full border border-border bg-card px-4 py-2 shadow-elevation-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm`,children:`A new version of Canvas is ready`}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>Jx(),className:`flex items-center gap-1 rounded-full bg-foreground px-3 py-1 text-xs font-medium text-background hover:bg-foreground/90`,children:[(0,Z.jsx)(we,{className:`h-3 w-3`}),` Reload`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(!0),"aria-label":`Not now`,className:`rounded-full p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]})})}var Xx;function Zx(){let[e,t]=(0,X.useState)({local:!1});return(0,X.useEffect)(()=>{Xx??=fetch(`${Rr}/runtime/capabilities`).then(async e=>e.ok?(await e.json()).payload:{local:!1}).catch(()=>({local:!1}));let e=!0;return Xx.then(n=>{e&&t(n)}),()=>{e=!1}},[]),e}function Qx(e){return e.isShared||e.type===`shared`?e.id:e.name}function $x({title:e,description:t,actions:n,backTo:r,onBack:i,className:a,compact:o}){let s=al();return(0,Z.jsxs)(`div`,{className:K(`flex flex-wrap items-start gap-x-3 gap-y-2`,!o&&`border-b pb-4`,a),children:[(0,Z.jsxs)(`div`,{className:`flex min-w-[14rem] flex-1 items-start gap-3`,children:[(i||r)&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i?i():s(r),"aria-label":`Back`,title:`Back`,className:`mt-1 shrink-0 text-muted-foreground transition-colors hover:text-foreground touch-target`,children:(0,Z.jsx)(Bt,{className:`h-5 w-5`})}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h1`,{className:K(`truncate font-bold tracking-tight`,o?`text-xl`:`text-3xl`),children:e}),t&&(0,Z.jsx)(`p`,{className:K(`break-words text-muted-foreground`,o?`mt-1 text-xs`:`mt-2`),children:t})]})]}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>s(`/`),"aria-label":`Close`,title:`Close`,className:`order-2 flex h-9 w-9 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})}),n&&(0,Z.jsx)(`div`,{className:`order-3 flex w-full items-center gap-2 max-sm:flex-wrap sm:order-1 sm:w-auto`,children:n})]})}function eS({className:e}){let t=al();return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(`/`),"aria-label":`Close`,title:`Close`,className:K(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,e),children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})}function tS({onBack:e,title:t=`Back`,className:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:e,"aria-label":t,title:t,className:K(`flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground touch-target`,n),children:(0,Z.jsx)(Bt,{className:`h-4 w-4`})})}var nS=180;function rS({x:e,y:t,current:n,onChange:r,onClose:i}){Ff(i);let[a,o]=(0,X.useState)(``),[s,l]=(0,X.useState)([]),[u,d]=(0,X.useState)({q:``,list:[]}),[f,p]=(0,X.useState)(!0),m=(0,X.useRef)(null),h=(0,X.useRef)({name:``,t:0}),g=(e,t)=>{r({icon:e}),h.current.name===e&&t-h.current.t<350&&i(),h.current={name:e,t}};(0,X.useEffect)(()=>{m.current?.focus()},[]),(0,X.useEffect)(()=>{let e=!0;return Qf().then(t=>{e&&(l(t),p(!1))}),()=>{e=!1}},[]),(0,X.useEffect)(()=>{let e=a.trim();if(!e)return;let t=setTimeout(()=>{$f(e).then(t=>{d({q:e,list:t})})},250);return()=>clearTimeout(t)},[a]);let _=a.trim(),v=u.q===_,y=_!==``&&!v,b=(0,X.useMemo)(()=>(_?v?u.list:[]:s).slice(0,nS),[_,v,u.list,s]),x=(0,X.useRef)(null),[S,C]=(0,X.useState)({x:e,y:t});return(0,X.useLayoutEffect)(()=>{let n=x.current;if(!n)return;let r=()=>{let{width:r,height:i}=n.getBoundingClientRect();C({x:Math.max(8,Math.min(e,window.innerWidth-r-8)),y:Math.max(8,Math.min(t,window.innerHeight-i-8))})};r();let i=new ResizeObserver(r);return i.observe(n),window.addEventListener(`resize`,r),()=>{i.disconnect(),window.removeEventListener(`resize`,r)}},[e,t]),(0,Mf.createPortal)((0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:i}),(0,Z.jsxs)(`div`,{ref:x,className:`fixed z-50 w-[270px] max-w-[90vw] rounded-md border bg-popover p-2 shadow-elevation-4`,style:{left:S.x,top:S.y},children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1.5`,children:[(0,Z.jsx)(`span`,{className:`text-xs font-medium`,children:`Icon & color`}),(0,Z.jsx)(`button`,{type:`button`,onClick:i,className:`text-muted-foreground hover:text-foreground`,children:(0,Z.jsx)(Me,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-1.5 px-1 pb-2`,children:[ep.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e,onClick:()=>r({color:e}),className:K(`w-5 h-5 rounded-full border transition-transform hover:scale-110`,n.color===e?`ring-2 ring-offset-1 ring-foreground`:`border-border`),style:{backgroundColor:e}},e)),(0,Z.jsx)(`button`,{type:`button`,title:`No color`,onClick:()=>r({color:void 0}),className:K(`w-5 h-5 rounded-full border flex items-center justify-center text-muted-foreground hover:scale-110 transition-transform`,!n.color&&`ring-2 ring-offset-1 ring-foreground`),children:(0,Z.jsx)(Me,{className:`w-3 h-3`})}),(0,Z.jsx)(`label`,{title:`Custom color`,className:K(`relative w-5 h-5 rounded-full border border-border cursor-pointer hover:scale-110 transition-transform overflow-hidden`,n.color&&!ep.includes(n.color)&&`ring-2 ring-offset-1 ring-foreground`),style:{background:n.color&&!ep.includes(n.color)?n.color:`conic-gradient(from 0deg, #ef4444, #eab308, #22c55e, #06b6d4, #6366f1, #ec4899, #ef4444)`},children:(0,Z.jsx)(`input`,{type:`color`,value:n.color??`#3b82f6`,onChange:e=>r({color:e.target.value}),className:`absolute inset-0 opacity-0 cursor-pointer`})})]}),(0,Z.jsx)(`input`,{ref:m,value:a,onChange:e=>o(e.target.value),placeholder:`Search icons…`,className:`w-full mb-2 rounded-sm border bg-background px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-primary`}),f||y?(0,Z.jsxs)(`div`,{className:`flex items-center justify-center gap-2 py-8 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`w-4 h-4 animate-spin`}),` `,y?`Searching…`:`Loading icons…`]}):(0,Z.jsxs)(`div`,{className:`grid grid-cols-7 gap-0.5 max-h-[200px] overflow-y-auto`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`No icon`,onClick:()=>r({icon:void 0}),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent text-muted-foreground`,!n.icon&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(Me,{className:`w-4 h-4`})}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,title:e.replace(/^[^:]+:/,``).replace(`-fill`,``),onClick:t=>g(e,t.timeStamp),className:K(`aspect-square flex items-center justify-center rounded-sm hover:bg-accent`,n.icon===e&&`bg-accent ring-1 ring-primary`),children:(0,Z.jsx)(c,{icon:e,width:18,height:18,color:n.color})},e))]}),!f&&!y&&b.length===0&&(0,Z.jsxs)(`div`,{className:`px-1 py-3 text-center text-[11px] text-muted-foreground`,children:[`No icons match “`,a,`”`]})]})]}),document.body)}function iS(e,t,n){let r=(0,X.useRef)(n);(0,X.useEffect)(()=>{r.current=n}),(0,X.useEffect)(()=>{if(!e)return;e.emit(`subscribe`,{channel:t});let n=Object.keys(r.current).map(t=>{let n=(...e)=>{r.current[t]?.(...e)};return e.on(t,n),[t,n]});return()=>{e.emit(`unsubscribe`,{channel:t});for(let[t,r]of n)e.off(t,r)}},[e,t])}function aS({title:e,onClose:t,children:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 rounded-lg border bg-card p-4 shadow-elevation-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:e}),(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-label":`Close`,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),n]})}function oS({workspace:e,onStart:t,onStop:n,onEnter:r,onEdit:i,onSettings:a,onDestroy:o}){let[s,c]=(0,X.useState)(!1),l=e.status===`active`,u=e.type===`universe`||e.name===`universe`,d=e.status===`error`,f=e.status===`not_found`,p=e.isShared===!0||e.type===`shared`,m=e.ownerEmail||e.owner,h=typeof e.sharedVia==`object`&&e.sharedVia?e.sharedVia:null,g=h?.permissions||[],_=g.includes(`admin`)?`admin`:g.includes(`write`)?`read/write`:`read-only`,v=h?.type===`group`?`via group ${h.principal}`:h?.type===`user`?`shared with you`:``,y=e.origin===`remote`,b=e.status===`offline`,x=hp(e.color),S=x?``:`border-border`,C=x?{borderLeftColor:x,borderLeftWidth:`4px`}:{borderLeftWidth:`4px`};return(0,Z.jsx)(Z.Fragment,{children:(0,Z.jsxs)(Fu,{className:`relative ${S}`,style:C,children:[(0,Z.jsx)(Iu,{children:(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1 basis-40`,children:[(0,Z.jsx)(Lu,{className:`truncate`,children:e.label||e.name}),(0,Z.jsx)(Ru,{children:p?`Shared from ${m}`:e.description||``})]}),(0,Z.jsxs)(`div`,{className:`flex w-full shrink-0 flex-wrap items-center gap-2 sm:w-auto`,children:[l?(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>n(Qx(e)),title:`Stop Workspace`,disabled:d||f,children:(0,Z.jsx)(nn,{className:`h-4 w-4`})}):(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>t(Qx(e)),title:b?`Remote unreachable${e.statusMessage?`: ${e.statusMessage}`:``}`:`Start Workspace`,disabled:d||f||b,children:(0,Z.jsx)(De,{className:`h-4 w-4`})}),l&&(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>r(Qx(e)),title:`Enter Workspace`,disabled:d||f,children:(0,Z.jsx)(fr,{className:`h-4 w-4`})}),a&&(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>a(e),title:`Workspace settings`,"aria-label":`Workspace settings`,disabled:f,children:(0,Z.jsx)(Qt,{className:`h-4 w-4`})}),i&&!u&&!p&&(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,onClick:()=>i(e),title:`Edit Workspace`,disabled:d||f,children:(0,Z.jsx)(xt,{className:`h-4 w-4`})}),o&&!u&&!p&&(0,Z.jsxs)(Lr,{open:s,onOpenChange:c,children:[(0,Z.jsx)(Ar,{asChild:!0,children:(0,Z.jsx)(Y,{variant:`outline`,size:`icon`,title:y?`Remove remote workspace reference`:`Delete Workspace`,disabled:l&&!y,className:`text-destructive hover:text-destructive hover:bg-destructive/10`,children:(0,Z.jsx)(lt,{className:`h-4 w-4`})})}),(0,Z.jsxs)(kr,{children:[(0,Z.jsxs)(Ir,{children:[(0,Z.jsx)(wr,{children:y?`Remove remote workspace`:`Delete Workspace`}),(0,Z.jsx)(Cr,{children:y?(0,Z.jsxs)(Z.Fragment,{children:[`Remove the reference to "`,e.label||e.name,`" from this server?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),`The workspace itself stays untouched on `,e.remote?.url||e.host,`; only the stored share token and the local cache entry are dropped.`]}):(0,Z.jsxs)(Z.Fragment,{children:[`Are you sure you want to delete the workspace "`,e.label||e.name,`"?`,(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`br`,{}),(0,Z.jsx)(`strong`,{children:`This action cannot be undone.`}),` All data associated with this workspace, including documents, contexts, and configurations will be permanently removed.`]})})]}),(0,Z.jsxs)(Nr,{children:[(0,Z.jsx)(Fr,{children:`Cancel`}),(0,Z.jsx)(Mr,{onClick:()=>{o(e),c(!1)},className:`bg-destructive text-destructive-foreground hover:bg-destructive/90`,children:y?`Remove reference`:`Delete Workspace`})]})]})]})]})]})}),(0,Z.jsx)(zu,{children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`div`,{className:`h-3 w-3 rounded-full ${(()=>{switch(e.status){case`active`:return`bg-success`;case`inactive`:case`available`:return`bg-muted-foreground`;case`error`:case`offline`:return`bg-destructive`;case`not_found`:return`bg-muted-foreground`;default:return`bg-accent`}})()}`}),(0,Z.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:(()=>{switch(e.status){case`active`:return`Active`;case`inactive`:return`Inactive`;case`error`:return`Error`;case`not_found`:return`Not Found`;case`available`:return`Available`;case`removed`:return`Removed`;case`destroyed`:return`Destroyed`;case`offline`:return`Offline`;default:return e.status}})()}),u&&(0,Z.jsx)(`span`,{className:`ml-2 rounded-full bg-primary/10 px-2 py-1 text-xs text-primary`,children:`Universe`}),y&&(0,Z.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:e.remote?.url?`${e.remote.url} (${(e.remote.permissions||[]).join(`, `)||`no permissions`})`:void 0,children:[`Remote · `,e.host]}),p&&(0,Z.jsxs)(`span`,{className:`ml-2 rounded-full bg-info/10 px-2 py-1 text-xs text-info`,title:[v,`${_} access`].filter(Boolean).join(` · `),children:[`Shared · `,_]})]})})]})})}function sS(){let[e,t]=Ou(),n=e.get(`create`)===`1`,[r,i]=(0,X.useState)(n),[a,o]=(0,X.useState)(n);return n!==a&&(o(n),n&&i(!0)),[r,(0,X.useCallback)(r=>{if(i(r),!r&&n){let n=new URLSearchParams(e);n.delete(`create`),t(n,{replace:!0})}},[e,n,t])]}var cS=`canvas:lastPath`,lS=200;function uS(){try{let e=localStorage.getItem(cS);if(!e)return{};let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return{}}}function dS(e){try{localStorage.setItem(cS,JSON.stringify(e))}catch{}}function fS(e,t,n){if(!e)return;let r=uS(),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>lS)for(let e of a.slice(0,a.length-lS))delete r[e];dS(r)}function pS(e){let t=uS()[e];return!t||typeof t.path!=`string`||typeof t.tree!=`string`?null:t}function mS(e){let t=pS(e);return t?rb(e,t.path,t.tree):`/workspaces/${e}`}var hS=[{id:`device`,label:`This device`,description:`Personalize this browser and manage content available offline.`,items:[{path:`/appearance`,icon:Ke,label:`Appearance`,description:`Choose the theme, layout, colours, display density and document reading pane.`},{path:`/key-bindings`,icon:Le,label:`Keyboard shortcuts`,description:`View and customize shortcuts for navigation and actions.`},{path:`/offline`,icon:C,label:`Offline & cache`,description:`Manage cached content and storage on this device.`}]},{id:`account`,label:`Your account`,description:`Manage your access and the defaults your workspaces inherit.`,items:[{path:`/api-tokens`,icon:D,label:`API access tokens`,description:`Create and revoke credentials for apps and integrations.`},{path:`/devices`,icon:fe,label:`Registered devices`,description:`Manage devices connected to your account.`},{path:`/embedding`,icon:Vn,label:`Search & AI defaults`,description:`Choose default embedding providers and models for your workspaces.`},{path:`/shared`,icon:_n,label:`Shared with you`,description:`Find content other people have shared with your account.`}]},{id:`server`,label:`Server administration`,description:`Administrator controls for everyone using this Canvas server.`,items:[{path:`/admin/users`,icon:Ue,label:`Users`,description:`Manage accounts and server access.`},{path:`/admin/roles`,icon:Xn,label:`Roles & permissions`,description:`Manage reusable permissions across the server.`},{path:`/admin/auth`,icon:rr,label:`Authentication`,description:`Configure sign-in backends: local passwords, LDAP and IMAP.`},{path:`/admin/embedding`,icon:Vn,label:`Server search & AI defaults`,description:`Set the embedding providers and models accounts inherit.`},{path:`/admin/logs`,icon:Tt,label:`Server logs`,description:`Inspect server activity and troubleshoot failures.`},{path:`/admin/contexts`,icon:Ct,label:`All contexts`,description:`Inspect and manage contexts across the server.`},{path:`/admin/workspaces`,icon:ke,label:`All workspaces`,description:`Inspect and manage workspaces across the server.`},{path:`/admin/agents`,icon:dt,label:`All agents`,description:`Inspect and manage agents across the server.`}]},{id:`information`,label:`Information`,description:`Information about your Canvas installation.`,items:[{path:`/about`,icon:A,label:`About Canvas`,description:`View versions and information about this installation.`}]}],gS=[`/settings`,...hS.filter(e=>e.id!==`server`).flatMap(e=>e.items.map(e=>e.path))];function _S(e,...t){let n=t.join(` `).toLocaleLowerCase();return e.toLocaleLowerCase().trim().split(/\s+/).every(e=>n.includes(e))}var vS=[{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.`}],yS=`canvas:layout`;function bS(){try{return localStorage.getItem(yS)===`strip`?`strip`:`classic`}catch{return`classic`}}var xS=bS(),SS=new Set;function CS(){for(let e of SS)e()}function wS(){return xS}function TS(e){try{e===`strip`?localStorage.setItem(yS,e):localStorage.removeItem(yS)}catch{}xS=e,CS()}function ES(e){SS.add(e);let t=t=>{(t.key===yS||t.key===null)&&(xS=bS(),e())};return window.addEventListener(`storage`,t),()=>{SS.delete(e),window.removeEventListener(`storage`,t)}}function DS(){return(0,X.useSyncExternalStore)(ES,wS,()=>`classic`)}var OS=[{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.`}],kS=`canvas:layout-nav`;function AS(){try{let e=localStorage.getItem(kS);return e===`alt`||e===`ctrl`||e===`none`?e:`shift`}catch{return`shift`}}var jS=AS(),MS=new Set;function NS(){return jS}function PS(e){try{e===`shift`?localStorage.removeItem(kS):localStorage.setItem(kS,e)}catch{}jS=e;for(let e of MS)e()}function FS(e){MS.add(e);let t=t=>{(t.key===kS||t.key===null)&&(jS=AS(),e())};return window.addEventListener(`storage`,t),()=>{MS.delete(e),window.removeEventListener(`storage`,t)}}function IS(){return(0,X.useSyncExternalStore)(FS,NS,()=>`shift`)}function LS(e,t){let n=e.ctrlKey||e.metaKey;switch(t){case`shift`:return e.shiftKey&&!e.altKey&&!n;case`alt`:return e.altKey&&!e.shiftKey&&!n;case`ctrl`:return n&&!e.shiftKey&&!e.altKey;case`none`:return!e.shiftKey&&!e.altKey&&!n}}var RS=(0,X.createContext)(null);function zS(){let e=(0,X.useContext)(RS);if(!e)throw Error(`useMenu must be used within a MenuProvider`);return e}function BS(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`||gS.includes(`/${n}`)?{section:`settings`,entityId:null,m2View:null}:{section:null,entityId:null,m2View:null}}function VS(e,t){let n=nl(),r=al(),i=(0,X.useRef)(!1),a=(0,X.useRef)(e);return(0,X.useEffect)(()=>{a.current=e},[e]),(0,X.useEffect)(()=>{if(i.current){i.current=!1;return}let{section:e,entityId:r,m2View:o}=BS(n.pathname);if(e===null&&n.pathname!==`/`&&wS()===`strip`){let t=a.current;e=t.activeSection,r=t.selectedEntityId,o=t.m2View}let s=window.matchMedia(`(max-width: 767px)`).matches&&wS()!==`strip`;t({type:`SYNC_FROM_URL`,section:e,entityId:r,m2View:o,mobile:s})},[n.key,n.pathname,t]),{navigateToEntity:(0,X.useCallback)(e=>{i.current=!0,r(e)},[r])}}function HS(){let[e,t]=(0,X.useState)(null);return(0,X.useEffect)(()=>{let e=localStorage.getItem(`authToken`);if(!e)return;let n=Br(Sr.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 US=[`Home`,`Travel`,`Work`,`Books`,`Workouts`,`Beauty`,`Recipes`,`To Watch`,`To Read`,`Learning`,`Tech`,`Music`,`Finance`,`Shopping`,`Ideas`];async function WS(e,t,n){let r=0,i=0,a=n===`directory`?`directory`:`context`;for(let n of t)try{await _a(e,`/${n}`,!0,a);let t=sp(`/${n}`);t&&await ia(e,`/${n}`,t,a).catch(()=>{}),r+=1}catch{i+=1}return Sa(e),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n}})),{ok:r,failed:i}}function GS(){let[e,t]=(0,X.useState)(new Set),[n,r]=(0,X.useState)(`context`);return{selected:e,setSelected:t,tree:n,setTree:r,toggle:e=>{t(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}}}function KS({selected:e,onToggle:t,tree:n,onTreeChange:r,disabled:i=!1,idPrefix:a=`default-folders`,stacked:o=!1}){return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`text-muted-foreground`,children:`Create in:`}),[`context`,`directory`].map(e=>(0,Z.jsxs)(`label`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(`input`,{type:`radio`,name:`${a}-tree`,checked:n===e,onChange:()=>r(e),disabled:i}),e,` tree`]},e))]}),(0,Z.jsx)(`div`,{className:`mt-3 grid gap-1.5 ${o?`grid-cols-1`:`grid-cols-2 sm:grid-cols-3 md:grid-cols-4`}`,children:US.map(n=>{let r=tp[n.toLowerCase()];return(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded border px-2 py-1.5 text-sm hover:bg-accent/50`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:e.has(n),onChange:()=>t(n),disabled:i}),r?.icon&&(0,Z.jsx)(c,{icon:r.icon,width:16,height:16,color:r.color}),(0,Z.jsx)(`span`,{className:`truncate`,children:n})]},n)})})]})}var qS=[{value:`full`,icon:Mn,title:`Standard`,blurb:`Everything in one folder: your files in home/, alongside db/, data/, git/.`,tree:[`workspace.json`,`home/ ← your files`,`db/ data/ cache/ Git/`]},{value:`home`,icon:hr,title:`Roaming home`,blurb:`The workspace folder IS your drive. Mount it over WebDAV and it looks like a plain home directory. Canvas keeps its files in a hidden .workspace/.`,tree:[`your files, at the top level`,`.workspace/ ← hidden, ignored`]}];function JS({value:e,onChange:t,disabled:n=!1,idPrefix:r=`workspace-layout`,compact:i=!1}){return(0,Z.jsx)(`div`,{className:i?`space-y-1.5`:`grid gap-2 sm:grid-cols-2`,children:qS.map(i=>{let a=e===i.value,o=i.icon;return(0,Z.jsxs)(`button`,{id:`${r}-${i.value}`,type:`button`,role:`radio`,"aria-checked":a,disabled:n,onClick:()=>t(i.value),className:`flex w-full gap-2 rounded-md border p-2.5 text-left transition-colors disabled:opacity-50 ${a?`border-primary bg-accent/40`:`hover:bg-accent/20`}`,children:[(0,Z.jsx)(o,{className:`mt-0.5 h-4 w-4 shrink-0 ${a?`text-primary`:`text-muted-foreground`}`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block text-xs font-medium`,children:i.title}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-[11px] leading-snug text-muted-foreground`,children:i.blurb}),(0,Z.jsx)(`span`,{className:`mt-1 block font-mono text-[10px] leading-relaxed text-muted-foreground/80`,children:i.tree.map(e=>(0,Z.jsx)(`span`,{className:`block truncate`,children:e},e))})]})]},i.value)})})}function YS(){let[e,t]=(0,X.useState)(`full`),[n,r]=(0,X.useState)(!1);return(0,X.useEffect)(()=>{let e=!0;return J.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 XS({disabled:e}){let[t,n]=(0,X.useState)(0),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)([]),[s,c]=(0,X.useState)(null),[l,u]=(0,X.useState)(``),d=(0,X.useRef)(null);return(0,X.useEffect)(()=>{let e=!0;return d.current?.id!==t&&(d.current={id:t,promise:Jr()}),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,Z.jsxs)(`section`,{className:`space-y-2 rounded-md border p-3`,"aria-label":`Find workspace folders`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:`Workspaces folder`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copied a workspace folder here? Scan to add it to your workspaces.`})]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:e||r,onClick:()=>{i(!0),u(``),n(e=>e+1)},children:[(0,Z.jsx)(we,{className:`mr-2 h-3.5 w-3.5 ${r?`animate-spin`:``}`}),r?`Scanning…`:`Rescan`]})]}),r&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Looking for workspace folders…`}),!r&&!l&&(0,Z.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,Z.jsx)(`ul`,{className:`space-y-2`,children:a.map(e=>(0,Z.jsxs)(`li`,{children:[(0,Z.jsx)(Su,{className:`text-sm font-medium underline underline-offset-2`,to:`/workspaces/${encodeURIComponent(e.name)}`,children:e.label||e.name}),(0,Z.jsx)(`p`,{className:`break-all text-xs text-muted-foreground`,children:e.dir})]},e.id))}),l&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:l}),!!s?.skipped.length&&(0,Z.jsxs)(`details`,{className:`text-sm text-muted-foreground`,children:[(0,Z.jsxs)(`summary`,{children:[s.skipped.length,` `,s.skipped.length===1?`folder could`:`folders could`,` not be added`]}),(0,Z.jsx)(`ul`,{className:`mt-1 space-y-1`,children:s.skipped.map(e=>(0,Z.jsxs)(`li`,{className:`break-all`,children:[e.dir,`: `,e.reason]},e.dir))})]})]})}function ZS({name:e,label:t,setName:n,setLabel:r,disabled:i=!1}){return(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace name`,(0,Z.jsx)(q,{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,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Used in addresses. Archive imports also use it as the folder name.`})]}),(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Display label`,(0,Z.jsx)(q,{required:!0,placeholder:`My Workspace`,value:t,onChange:e=>r(e.target.value),disabled:i})]})]})}function QS({onImported:e,disabled:t=!1}){let[n,r]=(0,X.useState)(`upload`),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(``),[u,d]=(0,X.useState)(``),[f,p]=(0,X.useState)(!1),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(``),[v,y]=(0,X.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(Ha[e.phase]||e.phase);try{let t=n===`upload`?await ma(i,e=>h(e<1?`Uploading… ${Math.round(e*100)}%`:`Extracting…`),a,r):await Ra(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,Z.jsxs)(`form`,{className:`space-y-3`,onSubmit:e=>void x(e),children:[(0,Z.jsx)(XS,{disabled:b}),(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Import from`,(0,Z.jsxs)(`select`,{value:n,disabled:b,onChange:e=>r(e.target.value),className:`rounded-md border bg-background p-2`,children:[(0,Z.jsx)(`option`,{value:`upload`,children:`Upload an archive`}),(0,Z.jsx)(`option`,{value:`path`,children:`Path on this server`})]})]}),n===`upload`?(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Workspace archive`,(0,Z.jsx)(q,{required:!0,type:`file`,accept:`.tar.gz,.tgz,.tar.bz2,.tbz2,.tbz`,disabled:b,onChange:e=>a(e.target.files?.[0]||null)})]}):(0,Z.jsxs)(`label`,{className:`grid gap-1 text-sm`,children:[`Server path`,(0,Z.jsx)(q,{required:!0,placeholder:`/tmp/workspace.tar.gz`,value:o,disabled:b,onChange:e=>s(e.target.value)}),(0,Z.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,Z.jsx)(ZS,{name:c,label:u,setName:l,setLabel:d,disabled:b}),(0,Z.jsxs)(Y,{type:`submit`,disabled:b||!c.trim()||!u.trim()||(n===`upload`?!i:!o.trim()),children:[f?(0,Z.jsx)(we,{className:`mr-2 h-4 w-4 animate-spin`}):(0,Z.jsx)(te,{className:`mr-2 h-4 w-4`}),f?`Importing…`:`Import workspace`]}),f&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:m}),g&&(0,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),v&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Imported `,v.label||v.name,`.`]})]})}function $S(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 eC(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function tC(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 nC(e){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(null);return{rowProps:e=>({"data-reorder-index":e}),handleProps:t=>({onPointerDown:r=>{if(r.pointerType===`mouse`&&r.button!==0)return;r.preventDefault(),r.stopPropagation();let a=r.currentTarget.closest(`[data-reorder-index]`);if(!a)return;let o=a.parentElement,s=(o?[...o.querySelectorAll(`:scope > [data-reorder-index]`)]:[a]).map(e=>({index:Number(e.dataset.reorderIndex),rect:e.getBoundingClientRect()})).filter(e=>Number.isFinite(e.index)).sort((e,t)=>e.index-t.index).map(e=>e.rect.top+e.rect.height/2),c=a.getBoundingClientRect(),l=a.cloneNode(!0);Object.assign(l.style,{position:`fixed`,left:`${c.left}px`,top:`${c.top}px`,width:`${c.width}px`,height:`${c.height}px`,margin:`0`,pointerEvents:`none`,zIndex:`100`,opacity:`0.92`,boxShadow:`0 12px 32px rgba(0,0,0,.28)`,willChange:`transform`}),document.body.appendChild(l);let u={x:r.clientX,y:r.clientY},d=t;n(t),i(t);let f={x:r.clientX,y:r.clientY},p=0,m=()=>{p=0,l.style.transform=`translate(${f.x-u.x}px, ${f.y-u.y}px) scale(1.02)`;let e=s.length;for(let t=0;t<s.length;t++)if(f.y<s[t]){e=t;break}e!==d&&(d=e,i(e))},h=e=>{f={x:e.clientX,y:e.clientY},p||=requestAnimationFrame(m)},g=()=>{window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,g),p&&cancelAnimationFrame(p),l.remove(),n(null),i(null),d!==t&&d!==t+1&&e(t,d>t?d-1:d)};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,g)},onClick:e=>{e.preventDefault(),e.stopPropagation()},style:{touchAction:`none`}}),insertIndex:r,draggingIndex:t,insertLineClass:(e,n)=>r===null||t===null?!1:r===e?`shadow-[0_-3px_0_0_var(--color-primary)]`:r===n&&e===n-1&&`shadow-[0_3px_0_0_var(--color-primary)]`}}function rC(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(fp()),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(``),[_,v]=YS(),[y,b]=(0,X.useState)(null),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),T=Zx(),[E,D]=sS(),O=GS(),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(!1),[N,P]=(0,X.useState)(!1),[ee,F]=(0,X.useState)(!1),[I,L]=(0,X.useState)(null),{showToast:R}=Vr(),te=al(),ne=Jm(),{openM2Drawer:z}=zS(),re=HS();iS(re,`workspace`,{"workspace:status:changed":e=>t(t=>t.map(t=>t.id===e.workspaceId?{...t,status:e.status}:t)),"workspace:created":e=>t(t=>[...t,e.workspace]),"workspace:deleted":e=>t(t=>t.filter(t=>t.id!==e.workspaceId))}),(0,X.useEffect)(()=>{let e=async()=>{try{r(!0);let e=await Xr();t($S(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),R({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,R]);let ie=async e=>{if(e.preventDefault(),o.trim()){w(!0);try{let e=await fo({name:o,description:l||void 0,color:d,icon:p,label:h||o,layout:_});if(t(t=>[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),O.selected.size>0){try{await Ua(e.name);let{ok:t,failed:n}=await WS(e.name,Array.from(O.selected),O.tree);n&&R({title:`Folders`,description:`${t} folder(s) created, ${n} failed`,variant:`destructive`})}catch(e){console.error(`Default folder creation failed:`,e),R({title:`Folders`,description:`Workspace created, but default folders failed`,variant:`destructive`})}O.setSelected(new Set)}s(``),u(``),f(fp()),m(null),g(``),R({title:`Success`,description:`Workspace '${e.label||e.name}' created.`}),D(!1)}catch(e){console.error(`Workspace creation error:`,e);let t=`Failed to create workspace`;if(e instanceof Error)t=e.message;else if(typeof e==`object`&&e){let n=e;t=n.message||n.error||n.payload?.message||n.payload?.error||n.statusText||`Failed to create workspace`}R({title:`Error`,description:t,variant:`destructive`})}finally{w(!1)}}},ae=async e=>{if(e.preventDefault(),I)try{let e={label:I.label,description:I.description,color:I.color,icon:I.icon??null};await Ba(I.name,e),t(t=>t.map(t=>t.id===I.id?{...t,...e}:t)),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),R({title:`Success`,description:`Workspace '${I.label}' details updated.`}),L(null)}catch(e){let t=e instanceof Error?e.message:`Failed to update workspace`;R({title:`Error`,description:t,variant:`destructive`})}},oe=e=>{L(e)},se=async e=>{try{await pi(e.name),t(t=>t.filter(t=>t.id!==e.id)),R({title:`Success`,description:`Workspace '${e.label||e.name}' has been destroyed.`})}catch(e){let t=e instanceof Error?e.message:`Failed to destroy workspace`;R({title:`Error`,description:t,variant:`destructive`})}},B=async e=>{try{let n=await Ua(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),R({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`}R({title:`Error`,description:t,variant:`destructive`})}},ce=async e=>{try{let n=await eo(e);t(e=>e.map(e=>e.id===n.id?{...e,...n}:e)),R({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`}R({title:`Error`,description:t,variant:`destructive`})}},V=e=>{te(mS(e))},{rowProps:le,handleProps:ue,draggingIndex:de,insertLineClass:fe}=nC((n,r)=>{let i=eC(e,n,r);t(i),tC(i,(e,t)=>Ba(Qx(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&R({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})});return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)($x,{title:`Workspaces`,description:`Divide your Universe into self-contained workspaces`,actions:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>A(e=>!e),className:`max-sm:hidden`,children:`Open shared Workspace (local)…`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>P(e=>!e),children:`Import workspace`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>M(e=>!e),className:`max-sm:hidden`,children:`Import remote…`}),(0,Z.jsx)(Y,{variant:`outline`,onClick:()=>F(e=>!e),className:`max-sm:hidden`,children:`Open remote…`}),!T.local&&!E&&(0,Z.jsxs)(Y,{onClick:()=>D(!0),className:`max-sm:h-9 max-sm:w-9 max-sm:p-0`,"aria-label":`Create workspace`,title:`Create workspace`,children:[(0,Z.jsx)(U,{className:`h-4 w-4 sm:mr-2`}),(0,Z.jsx)(`span`,{className:`max-sm:hidden`,children:`Create Workspace`})]})]})}),!T.local&&E&&(0,Z.jsx)(aS,{title:`Create New Workspace`,onClose:()=>D(!1),children:(0,Z.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Workspace Name (e.g., 'my-project')`,disabled:C}),(0,Z.jsx)(q,{value:h,onChange:e=>g(e.target.value),placeholder:`Workspace Label (display name, optional)`,disabled:C})]}),(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),placeholder:`Description (optional)`,disabled:C}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{htmlFor:`workspace-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,disabled:C,onClick:e=>b({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(c,{icon:p||`ph:stack-fill`,width:22,height:22,color:hp(d)})}),(0,Z.jsx)(q,{id:`workspace-color`,type:`color`,value:d,onChange:e=>f(e.target.value),className:`h-10 w-16 p-1`,disabled:C}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>f(fp()),disabled:C,children:`Randomize`})]}),y&&(0,Z.jsx)(rS,{x:y.x,y:y.y,current:{icon:p??void 0,color:d},onChange:e=>{`icon`in e&&m(e.icon??null),`color`in e&&e.color&&f(e.color)},onClose:()=>b(null)}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`Folder structure`}),(0,Z.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`How the workspace directory is laid out on disk. Fixed once created.`}),(0,Z.jsx)(JS,{value:_,onChange:v,disabled:C,idPrefix:`create-workspace-layout`})]}),(0,Z.jsxs)(`div`,{className:`rounded-lg border p-3`,children:[(0,Z.jsxs)(`p`,{className:`text-sm font-medium`,children:[`Default folders `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsx)(`p`,{className:`mb-3 mt-0.5 text-xs text-muted-foreground`,children:`Ticked folders are created right after the workspace, with matching icons and colors.`}),(0,Z.jsx)(KS,{selected:O.selected,onToggle:O.toggle,tree:O.tree,onTreeChange:O.setTree,disabled:C,idPrefix:`create-default-folders`})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:C||!o.trim(),children:[(0,Z.jsx)(U,{className:`mr-2 h-4 w-4`}),`Create Workspace`]})]})}),k&&(0,Z.jsx)(aC,{}),ee&&(0,Z.jsx)(oC,{onClose:()=>F(!1),onChanged:async()=>{try{t($S(await Xr()))}catch{}window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}}),N&&(0,Z.jsx)(aS,{title:`Import workspace`,onClose:()=>P(!1),children:(0,Z.jsx)(QS,{onImported:()=>P(!1)})}),j&&(0,Z.jsx)(iC,{onImported:e=>{t(t=>t.some(t=>t.id===e.id)?t:[...t,e]),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),M(!1)},onClose:()=>M(!1)}),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Your Workspaces`}),n&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`Loading workspaces...`}),i&&(0,Z.jsx)(`div`,{className:`text-center text-destructive`,children:(0,Z.jsx)(`p`,{children:i})}),!n&&!i&&e.length===0&&(0,Z.jsx)(`p`,{className:`text-center text-muted-foreground`,children:`No workspaces found`}),e.length>0&&(0,Z.jsx)(`div`,{className:`grid gap-4`,children:e.map((t,n)=>{let r={...t,createdAt:t.createdAt,updatedAt:t.updatedAt,color:t.color===null?void 0:t.color},i=hp(t.color);return(0,Z.jsxs)(`div`,{...le(n),className:`flex items-stretch rounded-lg ${fe(n,e.length)||``} ${de===n?`opacity-60`:``}`,children:[(0,Z.jsx)(`button`,{type:`button`,...ue(n),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:`hidden w-5 shrink-0 cursor-grab items-center justify-center rounded-l-lg active:cursor-grabbing md:flex ${i?``:`bg-muted`}`,style:i?{backgroundColor:i}:void 0,children:(0,Z.jsx)(Je,{className:`h-4 w-4 ${gp(i)}`})}),(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,Z.jsx)(oS,{workspace:r,onStart:B,onStop:ce,onEnter:V,onEdit:oe,onSettings:e=>{ne?z(`workspaces`,`settings`,Qx(e)):te(`/workspaces/${Qx(e)}/settings/general`)},onDestroy:se})})]},t.id)})})]}),I&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-semibold`,children:[`Edit Workspace: `,I.label]}),(0,Z.jsxs)(`form`,{onSubmit:ae,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-label`,value:I.label,onChange:e=>L(t=>t?{...t,label:e.target.value}:null),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`edit-description`,value:I.description||``,onChange:e=>L(t=>t?{...t,description:e.target.value}:null),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`edit-color`,className:`text-sm font-medium`,children:`Icon & Color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>S({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(c,{icon:I.icon||`ph:stack-fill`,width:22,height:22,color:hp(I.color)})}),(0,Z.jsx)(q,{id:`edit-workspace-color`,type:`color`,value:I.color||`#FFFFFF`,onChange:e=>L(t=>t?{...t,color:e.target.value}:null),className:`h-10 w-16 p-1`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>L(e=>e?{...e,color:fp()}:null),children:`Randomize Color`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:!I.label?.trim(),children:`Save Changes`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>L(null),children:`Cancel`})]})]}),x&&(0,Z.jsx)(rS,{x:x.x,y:x.y,current:{icon:I.icon??void 0,color:I.color??void 0},onChange:e=>{L(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 iC({onImported:e,onClose:t}){let{showToast:n}=Vr(),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(``),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(``);return(0,Z.jsx)(aS,{title:`Import (pull) a remote Workspace`,onClose:t,children:(0,Z.jsxs)(`form`,{onSubmit:async t=>{t.preventDefault();let i;try{i=new URL(r.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}if(!a.trim().startsWith(`canvas-`)){n({title:`Error`,description:`Invalid access token (expected canvas-...)`,variant:`destructive`});return}f(!0),m(`Starting…`);try{let t=await uo(i,a.trim(),e=>{m(Ha[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,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:r,onChange:e=>i(e.target.value),disabled:d}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:a,onChange:e=>o(e.target.value),disabled:d}),(0,Z.jsx)(Y,{type:`submit`,disabled:d||!r.trim()||!a.trim()||!s.trim()||!l.trim(),children:d?`Importing…`:`Import Workspace`})]}),(0,Z.jsx)(ZS,{name:s,label:l,setName:c,setLabel:u,disabled:d}),d&&p&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:p}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Pulls a full `,(0,Z.jsx)(`strong`,{children:`copy`}),` of the workspace from the remote canvas-server into this one, where it then lives independently. The remote workspace is stopped while it is packed, and large workspaces can take several minutes — progress is shown above.`]})]})})}function aC(){let{showToast:e}=Vr(),[t,n]=(0,X.useState)(``),[r,i]=(0,X.useState)(``),[a,o]=(0,X.useState)(!1),s=e=>{try{return new URL(e)}catch{return null}};return(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-xl font-semibold`,children:`Open shared Workspace (local)`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Shared URL (e.g., https://host/rest/v2/pub/workspaces/ID)`,value:t,onChange:e=>n(e.target.value)}),(0,Z.jsx)(q,{placeholder:`Access token (canvas-...)`,value:r,onChange:e=>i(e.target.value)}),(0,Z.jsx)(Y,{onClick:async()=>{if(!s(t.trim())){e({title:`Error`,description:`Invalid URL`,variant:`destructive`});return}if(!r.trim().startsWith(`canvas-`)){e({title:`Error`,description:`Invalid access token`,variant:`destructive`});return}o(!0);try{sessionStorage.setItem(`sharedToken:last`,r.trim());let e=new URLSearchParams({url:t.trim()}).toString();window.location.href=`/shared?${e}`}catch(t){e({title:`Error`,description:t instanceof Error?t.message:`Failed to open shared resource`,variant:`destructive`})}finally{o(!1)}},disabled:a||!t.trim()||!r.trim(),children:`Open`})]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`We use your provided URL and token to fetch via the remote's public API.`})]})}function oC({onClose:e,onChanged:t}){let{showToast:n}=Vr(),r=al(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(``),[c,l]=(0,X.useState)(!1),[u,d]=(0,X.useState)([]),f=(0,X.useCallback)(async()=>{try{d(await aa())}catch{d([])}},[]);(0,X.useEffect)(()=>{f()},[f]);let p=async e=>{e.preventDefault();let r;try{r=new URL(i.trim()).origin}catch{n({title:`Error`,description:`Invalid server URL`,variant:`destructive`});return}l(!0);try{let e=await Ga(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 Ji(e.id),await f(),t?.()}catch(e){n({title:`Error`,description:e instanceof Error?e.message:`Failed to remove remote workspace`,variant:`destructive`})}};return(0,Z.jsxs)(aS,{title:`Open a remote Workspace`,onClose:e,children:[(0,Z.jsxs)(`form`,{onSubmit:p,className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{placeholder:`Server URL (e.g., https://my.canvas-server.tld)`,value:i,onChange:e=>a(e.target.value),disabled:c}),(0,Z.jsx)(q,{placeholder:`Workspace share token (canvas-...)`,value:o,onChange:e=>s(e.target.value),disabled:c}),(0,Z.jsx)(Y,{type:`submit`,disabled:c||!i.trim()||!o.trim(),children:c?`Checking…`:`Add Remote`})]}),(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Keeps the workspace on its own server and registers it here as`,` `,(0,Z.jsx)(`code`,{className:`font-mono text-xs`,children:`name@host`}),` — nothing is copied. Every call you make to it is forwarded to the remote with the share token (its permissions apply); document content and thumbnails are cached locally so they stay readable when the remote is offline. Use “Import remote…” if you want an independent local copy instead.`]})]}),u.length>0&&(0,Z.jsx)(`ul`,{className:`mt-4 space-y-2 border-t pt-3`,children:u.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-2 rounded-md border p-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`truncate text-sm font-medium`,children:[e.label,(0,Z.jsx)(`span`,{className:`ml-2 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`remote`})]}),(0,Z.jsxs)(`div`,{className:`mt-0.5 truncate font-mono text-[11px] text-muted-foreground`,children:[e.address,` · `,e.remote.url]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(`/workspaces/${e.address}`),children:`Open`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>m(e),className:`text-destructive hover:text-destructive`,children:`Remove`})]})]},e.id))})]})}function sC(e){let t=rv(`backends`,e.path)?.backend;return(0,Z.jsx)(cC,{...e},JSON.stringify([e.workspace,t]))}function cC({workspace:e,path:t,onNavigate:n}){let r=rv(`backends`,t),i=r.backend,a=r.prefix,[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)(null),u=(0,X.useRef)(!1),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(0),[_,v]=(0,X.useState)(new Set),[y,b]=(0,X.useState)(null),x=(0,X.useCallback)(()=>g(e=>e+1),[]),[S,C]=(0,X.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,X.useEffect)(()=>{let t=!1;return(i?sv(e,i).then(e=>({...e,backends:[]})):Ta(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,X.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=av(T,a),k=async(t,n)=>{if(!(!i||u.current||w||!n.length)&&!(t===`discard`&&!fv(i,n))){u.current=!0,l(t),f(null),m(null),b(null);try{let r=await(t===`restore`?cv:lv)(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,Z.jsxs)(`section`,{className:`flex h-full min-h-0 flex-col bg-background`,"aria-label":`Backend Trash`,children:[(0,Z.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2 border-b px-4 py-3`,children:[(0,Z.jsx)(lt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsx)(Op,{items:kp(t,e).map((e,t)=>t===2&&i?{...e,label:i}:e),onNavigate:n,className:`basis-48`}),(0,Z.jsxs)(`div`,{className:`ml-auto flex max-w-full flex-wrap items-center gap-2`,children:[_.size>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(He,{className:`h-3.5 w-3.5`}),`Restore selected`]}),(0,Z.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,Z.jsx)(lt,{className:`h-3.5 w-3.5`}),`Delete selected`]})]}),i&&O.length>0&&(0,Z.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,Z.jsx)(lt,{className:`h-3.5 w-3.5`}),a?`Empty this folder`:`Empty Trash`]}),(0,Z.jsx)(`button`,{title:`Refresh Trash`,"aria-label":`Refresh Trash`,className:`rounded p-2 hover:bg-accent`,disabled:!!c||w,onClick:x,children:(0,Z.jsx)(we,{className:`h-4 w-4 ${w?`animate-spin`:``}`})})]})]}),(0,Z.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,Z.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:p}),(d||o?.error)&&(0,Z.jsx)(`p`,{role:`alert`,className:`px-4 py-2 text-sm text-destructive`,children:d||o?.error}),c&&(0,Z.jsx)(`p`,{role:`status`,className:`px-4 py-2 text-sm`,children:c===`restore`?`Restoring…`:`Deleting permanently…`}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-3`,children:w?(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`Loading Trash…`}):i?O.length===0?(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`This Trash folder is empty.`}):(0,Z.jsxs)(`table`,{className:`w-full text-left text-sm`,children:[(0,Z.jsx)(`thead`,{className:`border-b text-xs text-muted-foreground`,children:(0,Z.jsxs)(`tr`,{children:[(0,Z.jsx)(`th`,{className:`w-8 p-2`,children:(0,Z.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,Z.jsx)(`th`,{className:`p-2`,children:`Name`}),(0,Z.jsx)(`th`,{className:`p-2 max-sm:hidden`,children:`Original path`}),(0,Z.jsx)(`th`,{className:`p-2 max-md:hidden`,children:`Deleted`}),(0,Z.jsx)(`th`,{className:`p-2`,children:(0,Z.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,Z.jsx)(`tbody`,{children:O.map(e=>(0,Z.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(iv(i,e.key)),children:[(0,Z.jsx)(`td`,{className:`p-2`,children:(0,Z.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,Z.jsx)(`td`,{className:`p-2`,children:(0,Z.jsxs)(`button`,{className:`flex items-center gap-2 text-left`,onClick:()=>e.navigable&&n(iv(i,e.key)),children:[e.directory?(0,Z.jsx)(me,{className:`h-4 w-4 shrink-0`}):(0,Z.jsx)(bt,{className:`h-4 w-4 shrink-0`}),(0,Z.jsxs)(`span`,{children:[e.name,e.navigable&&(0,Z.jsxs)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.items.length,` items`]})]})]})}),(0,Z.jsx)(`td`,{className:`p-2 text-xs text-muted-foreground max-sm:hidden`,children:e.key}),(0,Z.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,Z.jsx)(`td`,{className:`p-2 text-right`,children:(0,Z.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,Z.jsx)(Kt,{className:`h-4 w-4`})})})]},e.id))})]}):(0,Z.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-2 lg:grid-cols-3`,children:[E.map(e=>(0,Z.jsxs)(`button`,{onClick:()=>n(iv(e.address)),className:`flex items-center gap-3 rounded-lg border p-4 text-left hover:bg-accent`,children:[(0,Z.jsx)(lt,{className:`h-6 w-6 text-muted-foreground`}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:e.label||e.address}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.address})]})]},e.address)),!E.length&&(0,Z.jsx)(`p`,{className:`p-4 text-sm text-muted-foreground`,children:`No file backends are available.`})]})}),y&&(0,Z.jsxs)(If,{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,Z.jsxs)(`button`,{className:`flex w-full items-center gap-2 rounded px-3 py-2 text-sm hover:bg-accent`,onClick:()=>{n(iv(i,y.row.key)),b(null)},children:[(0,Z.jsx)(me,{className:`h-4 w-4`}),`Open folder`]}),(0,Z.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,Z.jsx)(He,{className:`h-4 w-4`}),`Restore `,y.row.directory?`folder`:`file`]}),(0,Z.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,Z.jsx)(lt,{className:`h-4 w-4`}),`Delete permanently`]})]})]})}function lC({workspaceName:e,children:t}){let n=e,[r,i]=(0,X.useState)(null),[a,o]=(0,X.useState)(``),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(0);if((0,X.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 ja(e):await Zi(e);!t&&c===r&&(`id`in s&&(a=s.id),i({identity:n,state:Er()||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=Tr(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=id.on(`connect`,c);id.on(`workspace:status:changed`,u),id.on(`workspace.status.changed`,u);let f=Pr(e=>{e||c()});return()=>{t=!0,d?.(),f(),id.off(`workspace:status:changed`,u),id.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,Z.jsx)(`p`,{className:`p-6 text-sm text-muted-foreground`,children:`Checking workspace…`});if(r.state===`active`)return t;let d=r.state===`stopped`;return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:d?`Workspace stopped`:r.state===`offline`?`Server unreachable`:`Workspace unavailable`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:d?`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,Z.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}),(0,Z.jsx)(Y,{disabled:s,onClick:async()=>{c(!0),o(``);try{d&&await Ua(e),u(e=>e+1)}catch(e){o(e instanceof Error?e.message:`Unable to start workspace`)}finally{c(!1)}},children:s?d?`Starting…`:`Checking…`:d?`Start workspace`:`Retry`}),(0,Z.jsx)(Su,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}/settings`,children:`Workspace settings`})]})}function uC({workspaceId:e,workspaceName:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(new Set),o=t=>`${e}:${t.address}:${t.resyncStartedAt||``}`;(0,X.useEffect)(()=>{let t=!1,n=!1,i=!1,a=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 Ta(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=id.on(`connect`,l);return id.on(`backend.resync.changed`,u),id.on(`backend.changed`,d),window.addEventListener(`focus`,l),()=>{t=!0,f?.(),id.off(`backend.resync.changed`,u),id.off(`backend.changed`,d),window.removeEventListener(`focus`,l)}},[e]);let s=n.filter(e=>!i.has(o(e)));return s.length?(0,Z.jsxs)(`aside`,{"aria-label":`Storage scans for ${t}`,className:`absolute bottom-5 right-5 z-50 w-72 max-w-[calc(100vw-2.5rem)] rounded-lg border bg-popover/95 p-3 text-popover-foreground shadow-lg backdrop-blur`,children:[(0,Z.jsxs)(`div`,{role:`status`,className:`mb-2 flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Mt,{"aria-hidden":`true`,className:`h-4 w-4 animate-spin`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block`,children:`Scanning storage`}),(0,Z.jsx)(`span`,{className:`block truncate text-xs font-normal text-muted-foreground`,title:t,children:t})]}),(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Hide scan progress for ${t}`,title:`Hide progress; scanning continues`,className:`rounded p-1 hover:bg-muted focus-visible:outline focus-visible:outline-2`,onClick:()=>a(e=>new Set([...e,...s.map(o)])),children:(0,Z.jsx)(Me,{"aria-hidden":`true`,className:`h-4 w-4`})})]}),(0,Z.jsx)(`div`,{className:`max-h-48 space-y-3 overflow-y-auto`,children:s.map(e=>{let{scanned:t=0,total:n=null}=e.progress||{},r=n&&n>0?Math.min(100,Math.round(t/n*100)):null,i=typeof e.config?.label==`string`?e.config.label:e.address;return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:i}),(0,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:n===null?`${t} files`:`${t} / ${n}`})]}),(0,Z.jsx)(`div`,{role:`progressbar`,"aria-label":`Scanning ${i}`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":r??void 0,className:`mt-1.5 h-1 overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary ${r===null?`animate-pulse`:`transition-all`}`,style:{width:r===null?`35%`:`${r}%`}})})]},e.address)})})]}):null}function dC(){let{openAddPicker:e}=Os();return(0,Z.jsx)(`button`,{type:`button`,onClick:e,title:`Add here`,"aria-label":`Add`,className:`shrink-0 flex items-center justify-center w-7 h-7 rounded-full bg-foreground text-background hover:opacity-90 transition-opacity`,children:(0,Z.jsx)(U,{className:`w-4 h-4`})})}function fC({count:e}){return e<=0?null:(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>window.dispatchEvent(new CustomEvent(`workspace:documents:link-selection`)),title:`Link ${e} selected document(s) to…`,"aria-label":`Link selection`,className:`shrink-0 flex items-center justify-center gap-1 h-7 min-w-7 rounded-full bg-info px-1.5 text-info-foreground hover:bg-info transition-colors touch-target`,children:[(0,Z.jsx)(Gt,{className:`w-3.5 h-3.5`}),(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold leading-none`,children:e})]})}function pC({treeName:e,path:t,rootLabel:n,onBrowseTree:r,onNavigatePath:i}){let a=(0,Z.jsxs)(`span`,{className:`font-mono text-xs text-muted-foreground`,children:[`[`,e,`]`]});return(0,Z.jsxs)(`div`,{className:`flex min-h-9 min-w-0 flex-1 items-center gap-2`,children:[r?(0,Z.jsxs)(`button`,{type:`button`,onClick:r,title:`Browse tree`,"aria-label":`Browse tree`,className:`flex shrink-0 items-center gap-1 rounded border bg-muted px-1.5 py-1 hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,Z.jsx)(Mn,{className:`h-3.5 w-3.5 text-muted-foreground`}),a]}):(0,Z.jsx)(`span`,{className:`shrink-0 rounded border bg-muted px-1.5 py-1`,children:a}),(0,Z.jsx)(Op,{items:kp(t,n),onNavigate:i})]})}function mC({urlType:e,urlDisplay:t,contextPath:n,treeName:r,workspaceId:i,documents:a,isLoading:o,totalCount:s,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,canvasInfo:E,isCanvasPinned:D,onTogglePinCanvas:O,onSaveAsCanvas:A,onShareCanvas:j,onUnshareCanvas:M,onDeleteCanvas:N,isSharingCanvas:P,isDeletingCanvas:ee,isCanvasShared:F,isCanvasLocked:I,backendSearchQueries:L,onBackendSearch:te,onRemoveBackendQuery:ne,serverSort:z,onServerSortChange:re,scope:ie,onScopeChange:ae,canSaveChanges:oe,isSavingChanges:se,onSaveChanges:B,onBrowseTree:ce,onNavigatePath:le,linkTree:ue,selectedCount:de=0,children:fe,contentBanner:me,folders:he,onOpenFolder:ge}){let _e=e===`canvas`,ve=(0,Z.jsx)(pC,{treeName:r?`${r}${e.endsWith(`-layer`)?`:layer`:``}`:e.replace(`-`,`:`),path:n,rootLabel:i||t.split(`://`)[0]||`Workspace`,onBrowseTree:ce,onNavigatePath:le});return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full min-h-0 bg-background`,children:[_e&&E?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 shrink-0 items-center border-b bg-muted/20 px-4 py-1`,children:ve}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0 min-w-0`,children:[E.color&&(0,Z.jsx)(`div`,{className:`w-1 h-6 rounded-full shrink-0`,style:{backgroundColor:E.color}}),(0,Z.jsx)($n,{className:`w-4 h-4 shrink-0 text-primary`}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-lg font-semibold leading-tight truncate`,children:E.label||t.split(`://`)[1]||`Canvas`}),E.description&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground truncate leading-tight`,children:E.description})]}),oe&&B&&(0,Z.jsxs)(`button`,{type:`button`,onClick:B,disabled:se,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:`Save filters`,children:[(0,Z.jsx)(k,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:se?`Saving...`:`Save filters`})]}),O&&(0,Z.jsxs)(`button`,{type:`button`,onClick:O,"aria-pressed":!!D,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground`,title:D?`Unpin from home`:`Pin to home`,children:[D?(0,Z.jsx)(V,{className:`w-3 h-3`}):(0,Z.jsx)(R,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:D?`Unpin`:`Pin`})]}),j&&(0,Z.jsxs)(`button`,{type:`button`,onClick:j,disabled:P||ee,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50`,title:F?`Copy public link`:`Share canvas`,children:[(0,Z.jsx)(_n,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:P?`Sharing...`:F?`Copy link`:`Share`})]}),F&&M&&(0,Z.jsxs)(`button`,{type:`button`,onClick:M,disabled:P||ee,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,Z.jsx)(pe,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Unshare`})]}),N&&(0,Z.jsxs)(`button`,{type:`button`,onClick:N,disabled:ee||I&&!F,title:I&&!F?`Unlock this canvas before deleting it`:`Delete canvas`,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-destructive/10 transition-colors text-muted-foreground hover:text-destructive disabled:opacity-50`,children:[(0,Z.jsx)(lt,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:ee?`Deleting…`:`Delete`})]}),(0,Z.jsx)(fC,{count:de}),(0,Z.jsx)(dC,{})]})]}):(0,Z.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2 px-4 py-2.5 border-b bg-muted/20 shrink-0`,children:[ve,A&&(0,Z.jsxs)(`button`,{type:`button`,onClick:A,className:`shrink-0 flex items-center gap-1.5 px-2.5 py-1 text-xs border rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground`,title:`Save as canvas`,children:[(0,Z.jsx)(vn,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`hidden sm:inline`,children:`Save as canvas`})]}),(0,Z.jsx)(fC,{count:de}),(0,Z.jsx)(dC,{})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:[me,fe||(0,Z.jsx)(Ty,{documents:a,isLoading:o,folders:he,onOpenFolder:ge,contextPath:n,treeName:r,workspaceId:i,totalCount:s,viewMode:`table`,allowViewToggle:!0,currentPage:c,pageSize:l,onPageChange:u,onPageSizeChange:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:_,onCopyDocuments:v,onCutDocuments:y,onPasteDocuments:b,onImportDocuments:x,onSelectionChange:S,pastedDocumentIds:C,onPurgeDocuments:w,disablePurgeDocuments:T,backendSearchQueries:L,onBackendSearch:te,serverSort:z,onServerSortChange:re,onRemoveBackendQuery:ne,scope:ie,onScopeChange:ae,canSaveChanges:!_e&&oe,isSavingChanges:se,onSaveChanges:B,linkTree:ue})]})]})}var hC=[{id:`todos`,label:`Todos`},{id:`notes`,label:`Notes`}],gC={id:`default`,name:`All`,kind:`documents`};function _C(){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 vC(e){let t=e?.views;if(!Array.isArray(t))return[gC];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`&&hC.some(e=>e.id===t.app)});return n.length>0?n:[gC]}function yC({views:e,activeId:t,onSelect:n,onSave:r,readOnly:i=!1,className:a,accentColor:o,onOpenToSide:s}){let c=o?(pp(o)??0)>.5?`text-black`:`text-white`:``,[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(``),[p,m]=(0,X.useState)(!1),[h,g]=(0,X.useState)(null),[_,v]=(0,X.useState)(null),y=()=>{g(null),v(null)},b=()=>{if(h&&_&&h!==_.id){let t=e.find(e=>e.id===h),n=e.filter(e=>e.id!==h),i=n.findIndex(e=>e.id===_.id);t&&i>=0&&(n.splice(_.before?i:i+1,0,t),n.some((t,n)=>t.id!==e[n].id)&&r(n))}y()},x=()=>{if(!l)return;let t=d.trim();t&&r(e.map(e=>e.id===l?{...e,name:t}:e)),u(null)},S=(t,n)=>{m(!1);let i=`view-${Date.now().toString(36)}`,a=t===`columns`?`Board`:t===`app`?hC.find(e=>e.id===n)?.label??`App`:`View ${e.length+1}`,o=t===`columns`?{id:i,name:a,kind:t,columns:_C()}:t===`app`?{id:i,name:a,kind:t,app:n}:{id:i,name:a,kind:t};r([...e,o],i),u(i),f(a)},C=n=>{let i=e.filter(e=>e.id!==n);r(i.length>0?i:[gC],n===t?i[0]?.id??gC.id:void 0)};return(0,Z.jsxs)(`div`,{className:K(`flex min-w-0 items-end`,a),children:[(0,Z.jsx)(`div`,{className:`flex min-w-0 items-end gap-0.5 overflow-x-auto pt-1`,children:e.map(r=>{let a=r.id===t;return l===r.id?(0,Z.jsx)(`input`,{autoFocus:!0,value:d,onChange:e=>f(e.target.value),onBlur:x,onKeyDown:e=>{e.key===`Enter`&&x(),e.key===`Escape`&&u(null)},className:`relative z-[1] h-8 w-28 rounded-t-md border border-b-0 border-input bg-background px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`},r.id):(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(r.id),onDoubleClick:()=>{i||(u(r.id),f(r.name))},title:i?r.name:`${r.name}: double-click to rename, drag to reorder`,draggable:!i,onDragStart:e=>{e.dataTransfer.setData(`text/plain`,r.name),e.dataTransfer.effectAllowed=`move`,g(r.id)},onDragOver:e=>{if(!h||h===r.id)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),n=e.clientX<t.left+t.width/2;v(e=>e?.id===r.id&&e.before===n?e:{id:r.id,before:n})},onDrop:e=>{e.preventDefault(),b()},onDragEnd:y,className:K(`group flex h-8 shrink-0 items-center gap-1.5 rounded-t-md px-3 text-xs transition-colors`,a?K(`relative z-[1] border border-b-0 font-medium`,o?c:`border-border bg-background text-foreground`):`mb-[3px] border border-b-0 border-transparent bg-muted/40 text-muted-foreground hover:bg-accent/60 hover:text-foreground`,h===r.id&&`opacity-50`,_?.id===r.id&&(_.before?`border-l-2 border-l-primary`:`border-r-2 border-r-primary`)),style:a&&o?{backgroundColor:o,..._?.id===r.id?{}:{borderColor:o}}:void 0,children:[r.kind===`columns`?(0,Z.jsx)(P,{className:`h-3 w-3 shrink-0`}):r.kind===`app`?r.app===`todos`?(0,Z.jsx)(On,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(xn,{className:`h-3 w-3 shrink-0`}):(0,Z.jsx)(ht,{className:`h-3 w-3 shrink-0`}),(0,Z.jsx)(`span`,{className:`max-w-32 truncate`,children:r.name}),s&&(0,Z.jsx)(se,{className:`h-3 w-3 shrink-0 opacity-0 transition-opacity hover:opacity-100 group-hover:opacity-60`,"aria-label":`Open to the side`,onClick:e=>{e.stopPropagation(),s(r.id)}}),!i&&e.length>1&&(0,Z.jsx)(Me,{className:K(`h-3 w-3 shrink-0 transition-opacity hover:text-destructive`,a?`opacity-60 hover:opacity-100`:`opacity-0 group-hover:opacity-100`),onClick:e=>{e.stopPropagation(),C(r.id)}})]},r.id)})}),!i&&(p?(0,Z.jsxs)(`span`,{className:`relative z-[1] mb-1.5 ml-1 flex shrink-0 items-center gap-1`,children:[!e.some(e=>e.id===gC.id)&&(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>{m(!1),r([{...gC},...e],gC.id)},className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(ht,{className:`h-3 w-3`}),` All`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`documents`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(ht,{className:`h-3 w-3`}),` List`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`columns`),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[(0,Z.jsx)(P,{className:`h-3 w-3`}),` Board`]}),hC.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>S(`app`,e.id),className:`flex h-7 items-center gap-1.5 rounded-md border px-2 text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:[e.id===`todos`?(0,Z.jsx)(On,{className:`h-3 w-3`}):(0,Z.jsx)(xn,{className:`h-3 w-3`}),` `,e.label]},e.id)),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!1),className:`p-1 text-muted-foreground hover:text-foreground`,"aria-label":`Cancel`,children:(0,Z.jsx)(Me,{className:`h-3 w-3`})})]}):(0,Z.jsx)(`button`,{type:`button`,onClick:()=>m(!0),title:`Add view`,"aria-label":`Add view`,className:`relative z-[1] mb-1.5 ml-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:(0,Z.jsx)(U,{className:`h-3.5 w-3.5`})}))]})}var bC=`data/schema/note`;function xC(e,t,n,r,i){let a=`${e}\0${t}\0${n}\0${r}\0${i??``}`,[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null);(0,X.useEffect)(()=>{let o=!1;return Yi(e,n,t,{limit:200,allOf:[r],...i?{sortBy:i,order:`asc`}:{}}).then(e=>{o||l({key:a,docs:e.payload||[]})}).catch(()=>{o||l({key:a,docs:[]})}),()=>{o=!0}},[a,o]);let u=c?.key===a?c.docs:[],d=c?.key!==a;return(0,X.useEffect)(()=>{let e=()=>s(e=>e+1);return window.addEventListener(`workspace:documents:refresh`,e),()=>window.removeEventListener(`workspace:documents:refresh`,e)},[]),{docs:u,isLoading:d,refresh:(0,X.useCallback)(()=>s(e=>e+1),[])}}function SC({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i,refresh:a}=xC(e,t,n,hi,`tasks`),[o,s]=(0,X.useState)(!1),c=o?r.filter(e=>e.data?.status!==`completed`):r,l=r.filter(e=>{let t=e.data?.status;return t!==`completed`&&t!==`cancelled`}).length;return(0,Z.jsxs)(`div`,{className:`mx-auto flex h-full w-full max-w-3xl flex-col p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-2 flex shrink-0 items-center justify-between gap-2`,children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[l,` open`]}),(0,Z.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-muted-foreground`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),`hide done`]})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto`,children:i?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`Loading…`}):c.length===0?(0,Z.jsx)(`p`,{className:`py-4 text-sm text-muted-foreground`,children:`No todos here.`}):c.map(t=>(0,Z.jsx)(Qy,{doc:t,workspaceId:e,readOnly:!1,onChanged:a},t.id))})]})}function CC({workspaceId:e,treeName:t,path:n}){let{docs:r,isLoading:i}=xC(e,t,n,bC);return(0,Z.jsx)(`div`,{className:`h-full overflow-y-auto p-4`,children:(0,Z.jsx)(Ty,{documents:r,isLoading:i,contextPath:n,treeName:t,workspaceId:e,totalCount:r.length,viewMode:`card`})})}function wC({app:e,...t}){return e===`todos`?(0,Z.jsx)(SC,{...t}):(0,Z.jsx)(CC,{...t})}var TC=[{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 EC(e,t){return t.some(t=>e.schema===t||e.schema.startsWith(`${t}/`))}function DC({documents:e,workspaceId:t,columns:n,onColumnsChange:r,readOnly:i=!1}){let[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)({}),[d,f]=(0,X.useState)({}),p=(0,X.useRef)(null),[m,h]=(0,X.useState)(!1),g=(0,X.useCallback)(()=>{let e=p.current;e&&h(e.scrollWidth-e.clientWidth-e.scrollLeft>8)},[]);(0,X.useEffect)(()=>{let e=p.current;if(!e)return;let t=new ResizeObserver(()=>g());return t.observe(e),()=>t.disconnect()},[g]);let _=(e,t)=>{e.preventDefault();let i=e.currentTarget.parentElement;if(!i)return;let a=e.clientX,o=i.getBoundingClientRect().width,s=o,c=e=>{s=Math.min(900,Math.max(220,o+e.clientX-a)),f(e=>({...e,[t]:s}))},l=()=>{window.removeEventListener(`pointermove`,c),window.removeEventListener(`pointerup`,l),r(n.map(e=>e.id===t?{...e,width:Math.round(s)}:e))};window.addEventListener(`pointermove`,c),window.addEventListener(`pointerup`,l)},v=e=>{f(t=>{let n={...t};return delete n[e],n}),r(n.map(t=>t.id===e?{...t,width:void 0}:t))},y=e=>{let t=l[e];if(t===void 0)return;let i=n.find(t=>t.id===e);i&&(i.filter||``)!==t&&r(n.map(n=>n.id===e?{...n,filter:t||void 0}:n))},b=TC.filter(e=>!n.some(t=>t.id===e.id));return(0,Z.jsxs)(`div`,{className:`relative h-full`,children:[(0,Z.jsx)(`div`,{ref:p,onScroll:g,className:`flex h-full snap-x snap-mandatory gap-3 overflow-x-auto overscroll-x-contain p-2`,"data-testid":`schema-columns-board`,children:n.map(t=>{let a=(l[t.id]??t.filter??``).toLowerCase(),s=e.filter(e=>EC(e,t.schemas)).filter(e=>{if(!a)return!0;let t=Ui(e);return`${t.title}\n${t.preview}\n${t.subtitle}`.toLowerCase().includes(a)}),c=d[t.id]??t.width;return(0,Z.jsxs)(`div`,{className:`relative flex h-full min-h-0 min-w-0 shrink-0 grow-0 basis-full snap-start flex-col rounded-lg border bg-muted/20 ${c?`sm:basis-[var(--col-w)]`:`sm:basis-[48%] lg:basis-[32%] xl:basis-[24%]`}`,style:c?{"--col-w":`${c}px`}:void 0,children:[!i&&(0,Z.jsx)(`div`,{onPointerDown:e=>_(e,t.id),onDoubleClick:()=>v(t.id),title:`Drag to resize; double-click to reset`,className:`absolute right-0 inset-y-0 z-10 w-2 cursor-col-resize touch-none rounded-r-lg transition-colors hover:bg-primary/25 active:bg-primary/40 max-sm:hidden`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 pb-1 pt-2.5 max-sm:pr-10`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:t.label}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:s.length}),(0,Z.jsx)(`span`,{className:`flex-1`}),!i&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(n.filter(e=>e.id!==t.id)),title:`Remove column`,className:`rounded-sm p-0.5 text-muted-foreground hover:text-destructive`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(`div`,{className:`px-3 pb-2`,children:(0,Z.jsx)(`input`,{value:l[t.id]??t.filter??``,onChange:e=>u(n=>({...n,[t.id]:e.target.value})),onBlur:()=>y(t.id),onKeyDown:e=>{e.key===`Enter`&&y(t.id)},placeholder:`Filter…`,readOnly:i,className:`h-7 w-full rounded-md border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})}),(0,Z.jsxs)(`div`,{className:`flex-1 space-y-1.5 overflow-y-auto px-2 pb-2`,children:[s.map(e=>{let t=Ui(e);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>o(e),className:`w-full min-w-0 rounded-md border bg-card px-2.5 py-2 text-left transition-colors hover:bg-accent/50`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(Dp,{document:e,size:3.5}),(0,Z.jsx)(`span`,{className:`truncate text-xs font-medium`,title:t.title,children:t.title})]}),t.preview&&(0,Z.jsx)(`p`,{className:`mt-1 line-clamp-2 break-words text-[11px] leading-snug text-muted-foreground`,children:t.preview}),(0,Z.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground/70`,children:new Date(e.updatedAt||e.createdAt).toLocaleDateString()})]},e.id)}),s.length===0&&(0,Z.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground/60`,children:`Empty`})]})]},t.id)})}),(!i&&b.length>0||m)&&(0,Z.jsxs)(`div`,{className:`pointer-events-none absolute inset-y-0 right-0 z-20 flex w-7 flex-col items-end bg-gradient-to-l from-background via-background/60 to-transparent py-2`,children:[!i&&b.length>0&&(0,Z.jsxs)(`div`,{className:`pointer-events-auto relative`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(e=>!e),title:`Add column`,"aria-label":`Add column`,className:`flex h-7 w-6 items-center justify-center rounded-l-md border border-r-0 bg-background text-muted-foreground shadow-elevation-1 hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(U,{className:`h-3.5 w-3.5`})}),s&&(0,Z.jsxs)(`div`,{className:`absolute right-0 top-8 w-44 rounded-lg border bg-background p-2 shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`px-2 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground`,children:`Add column`}),b.map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{c(!1),r([...n,{...e}])},className:`w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-accent/50 hover:text-foreground`,children:e.label},e.id)),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>c(!1),className:`mt-1 w-full rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground/60 hover:bg-accent/50`,children:`Cancel`})]})]}),m&&(0,Z.jsx)(Ye,{className:`my-auto h-4 w-4 self-center text-muted-foreground/70`,"aria-label":`More columns`})]}),(0,Z.jsx)(N_,{document:a,isOpen:a!==null,onClose:()=>o(null),workspaceId:t})]})}var OC=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:null;function kC(e){return`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`}function AC(e,t,n){if(e==null)return[];if(Array.isArray(e))return e.flatMap(e=>AC(e,t,n));if(typeof e==`string`)return[{tree:null,kind:t,path:kC(e)}];let r=OC(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:kC(e)}))}function jC(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 MC(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 NC(e,t,n=new Map){let r=OC(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:kC(n)}],ids:jC(r),unknown:!1}:{targets:[],ids:[],unknown:!0}}let i=[...AC(r.context,`context`,n),...AC(r.directory,`directory`,n)],a=OC(r.changed);a&&i.push(...AC(a.context,`context`,n),...AC(a.directory,`directory`,n));let o=jC(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 PC(e,t){return e===t||e===`/`||t===`/`||e.startsWith(`${t}/`)||t.startsWith(`${e}/`)}function FC(e,t){return e.kind&&e.kind!==t.kind||e.tree&&e.tree!==t.tree?!1:PC(e.path,t.path)}function IC(e,t,n){if(e.unknown||e.targets.length&&(t.wholeWorkspace||e.targets.some(e=>FC(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 LC=(0,X.createContext)(null);function RC(){let e=(0,X.useContext)(LC);if(!e)throw Error(`useCanvasPins must be used within a CanvasPinsProvider`);return e}function zC(e,t,n={}){return id.request(Wu,{workspace:e,specs:t,opts:n})}function BC(e,t,n){return id.request(Gu,{sessionId:e,label:t,spec:n})}function VC(e){return id.request(Ku,{sessionId:e})}function HC(e,t={}){return id.request(qu,{sessionId:e,...t})}function UC(e){return id.request(Ju,{sessionId:e})}function WC(e){return id.on(Yu,e)}var GC=100;function KC({workspaceRef:e,specs:t,opts:n,enabled:r=!0}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(0),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(null),f=(0,X.useRef)([]),p=(0,X.useRef)(new Map),m=(0,X.useRef)(null),h=(0,X.useRef)(null),g=(0,X.useRef)(null),_=(0,X.useRef)({}),v=(0,X.useRef)(null),y=(0,X.useMemo)(()=>JSON.stringify(t),[t]),b=(0,X.useMemo)(()=>JSON.stringify(n??{}),[n]),x=(0,X.useCallback)(()=>{let e=p.current;a(f.current.map(t=>e.get(t)).filter(Boolean))},[]),S=(0,X.useCallback)(async e=>{let t=h.current;if(!t||e.length===0)return[];let n=[];for(let r=0;r<e.length;r+=GC){let i=e.slice(r,r+GC),a=await so(t,`/`,[],{ids:i,scope:`workspace`,limit:i.length});n.push(...a.payload||[])}return n},[]),C=(0,X.useCallback)(async(e,t,n)=>{if(t.length>0){let e=new Set(t);f.current=f.current.filter(t=>!e.has(t));for(let t of e)p.current.delete(t)}let r=e.filter(e=>!p.current.has(e)),i=new Set(f.current);for(let t of e)i.has(t)||(f.current.push(t),i.add(t));if(n!==null&&s(n),x(),r.length===0)return;let a=await S(r);for(let e of a)p.current.set(e.id,e);let o=new Set(a.map(e=>e.id)),c=r.filter(e=>!o.has(e));if(c.length>0){let e=new Set(c);f.current=f.current.filter(t=>!e.has(t))}x()},[S,x]),w=(0,X.useCallback)(async(e,t)=>{let n=e??[],r=new Set(n);f.current=f.current.filter(e=>r.has(e));for(let e of p.current.keys())r.has(e)||p.current.delete(e);let i=new Set(f.current),a=n.filter(e=>!i.has(e));await C(a,[],t)},[C]);(0,X.useEffect)(()=>{if(h.current=e??null,!r||!e)return;let t=!1,n=null,i=async()=>{try{let r=await zC(e,JSON.parse(y),JSON.parse(b));if(t){UC(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=id.on(`connect`,()=>{i()});return()=>{t=!0,o?.();let e=n??m.current;e&&UC(e).catch(()=>{}),m.current=null,f.current=[],p.current=new Map,l(null),a([]),s(0)}},[e,y,b,r]),(0,X.useEffect)(()=>{if(!c)return;let e=WC(e=>{if(e.sessionId===c){if(g.current!==null){v.current?.(g.current,_.current);return}e.ids===void 0?C(e.added??[],e.removed??[],e.count):w(e.ids,e.count)}});return()=>{e?.()}},[c,C,w]);let T=(0,X.useCallback)(async()=>{let e=m.current;if(e)try{let t=await VC(e);await w(t.ids,t.count)}catch{}},[w]),E=(0,X.useCallback)(async(e,t)=>{let n=m.current;if(!n)throw Error(`No open query session`);let r=await BC(n,e,t);if(g.current!==null){await v.current?.(g.current,_.current);return}await w(r.ids,r.count)},[w]),D=(0,X.useCallback)(async(e,t={})=>{let n=m.current;if(!n)throw Error(`No open query session`);if(g.current=e,_.current=t,e===null){await T();return}let r=await HC(n,{match:e,...t});for(let e of r.documents)p.current.set(e.id,e);f.current=r.ids,s(r.totalCount),x()},[x,T]);(0,X.useEffect)(()=>{v.current=D},[D]);let O=(0,X.useCallback)(async(e,t,n={})=>{let r=m.current;if(!r)throw Error(`No open query session`);let i=await HC(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 BC(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 qC=`canvas:query-debug`,JC=`canvas:query-debug-changed`;function YC(){try{return localStorage.getItem(qC)===`1`}catch{return!1}}function XC(e){try{e?localStorage.setItem(qC,`1`):localStorage.removeItem(qC)}catch{}window.dispatchEvent(new CustomEvent(JC,{detail:e}))}function ZC(){let[e,t]=(0,X.useState)(YC);return(0,X.useEffect)(()=>{let e=()=>t(YC());return window.addEventListener(JC,e),window.addEventListener(`storage`,e),()=>{window.removeEventListener(JC,e),window.removeEventListener(`storage`,e)}},[]),e}function QC({data:e,className:t}){let[n,r]=(0,X.useState)(!0),{rows:i,gapIndex:a,span:o}=(0,X.useMemo)(()=>{let t=[...e.distances].sort((e,t)=>e.distance-t.distance),n=[];for(let e=1;e<t.length;e++)n.push(t[e].distance-t[e-1].distance);let r=n.length?[...n].sort((e,t)=>e-t)[Math.floor(n.length/2)]:0,i=-1,a=0;for(let e=0;e<n.length;e++)n[e]>a&&(a=n[e],i=e+1);let o=i>0&&a>=Math.max(r*4,1e-6),s=t[0]?.distance??0,c=t[t.length-1]?.distance??0;return{rows:t,gapIndex:o?i:-1,span:{first:s,last:c,biggest:a,median:r}}},[e.distances]);if(i.length===0)return(0,Z.jsxs)(`div`,{className:K(`rounded-md border border-dashed border-border px-3 py-2 text-xs text-muted-foreground`,t),children:[`Query debug: no image distances for “`,e.query,`”. The dense side returned nothing: either no photos are embedded in this scope, or the image space is not ready.`]});let s=a>0?i[a].distance:null;return(0,Z.jsxs)(`div`,{className:K(`rounded-md border border-border bg-muted/30 text-xs`,t),children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`flex w-full items-center gap-1.5 px-3 py-2 text-left font-medium`,children:[n?(0,Z.jsx)(Ge,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Ye,{className:`h-3.5 w-3.5`}),`Query debug`,(0,Z.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`: image distances for “`,e.query,`” (`,i.length,` nearest, unfloored)`]})]}),n&&(0,Z.jsxs)(`div`,{className:`space-y-2 border-t border-border px-3 py-2`,children:[(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Best-first cosine distance (0 = identical). Scroll to where the photos stop being relevant and set the image relevance floor just above that value in Settings → Database → Search tuning.`,s===null?(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`span`,{className:`text-amber-600 dark:text-amber-500`,children:`No boundary in this window`}),`; the distances step evenly (typical Δ`,o.median.toFixed(4),`), so there is nothing here to set a floor from. Relevance probably ends further down the list than this window reaches, or the model is not separating this query at all.`]}):(0,Z.jsxs)(Z.Fragment,{children:[` A jump at `,(0,Z.jsx)(`span`,{className:`font-mono`,children:s.toFixed(4)}),` (Δ`,o.biggest.toFixed(4),`, vs typical Δ`,o.median.toFixed(4),`) stands out (a likely boundary).`]})]}),(0,Z.jsx)(`div`,{className:`max-h-56 overflow-y-auto`,children:(0,Z.jsx)(`table`,{className:`w-full font-mono text-[11px]`,children:(0,Z.jsx)(`tbody`,{children:i.map((e,t)=>(0,Z.jsxs)(`tr`,{className:K(`border-b border-border/40 last:border-0`,t===a&&`border-t-2 border-t-amber-500/70`),children:[(0,Z.jsx)(`td`,{className:`py-0.5 pr-3 text-muted-foreground`,children:t+1}),(0,Z.jsxs)(`td`,{className:`py-0.5 pr-3`,children:[`#`,e.id]}),(0,Z.jsx)(`td`,{className:`py-0.5 tabular-nums`,children:e.distance.toFixed(4)}),t===a&&(0,Z.jsx)(`td`,{className:`py-0.5 pl-2 font-sans text-[10px] text-amber-600 dark:text-amber-500`,children:`← biggest gap`})]},e.id))})})}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[`Range `,o.first.toFixed(4),` – `,o.last.toFixed(4),` (spread `,(o.last-o.first).toFixed(4),`) over `,i.length,` rows. Absolute values shift with the model and are not comparable across models. After a re-embed every floor has to be picked again. A spread this narrow relative to the range means ranking is doing the work, not distance.`]})]})]})}var $C=[`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`],ew=new Map;function tw(e,t){let n=ew.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=$C.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)Sa(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return id.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)Sa(e,t);a.forEach(([e,t])=>id.off(e,t))}},ew.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),ew.delete(e))}}function nw(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 rw=new Map;function iw(e,t,n){return`${e}\0${t}\0${n}`}function aw(e,t,n,r,i,a,o=``,s=``,c=`path`){return`${iw(e,t,n)}\0${r}\0${i}\0${a}\0${o}\0${s}\0${c}`}function ow(e,t,n){let r=iw(e,t,n);for(let e of rw.keys())e.startsWith(r)&&rw.delete(e)}function sw(e,t){let n=`${e}\0`;for(let[e,r]of rw){if(!e.startsWith(n))continue;let[,i,a,,,,,,o=`path`]=e.split(`\0`);IC(t,{tree:i,kind:lo(i),path:a,wholeWorkspace:o.startsWith(`workspace`)},r.documents.map(e=>Number(e.id)))&&rw.delete(e)}}function cw(e,t){if(!t?.treeName)return;let n=t.workspaceName??e,r=t.path?iw(n,t.treeName,t.path):`${n}\0${t.treeName}\0`;for(let e of rw.keys())e.startsWith(r)&&rw.delete(e)}function lw(){let{workspaceName:e}=ll();return e?(0,Z.jsx)(lC,{workspaceName:e,children:(0,Z.jsx)(uw,{})}):null}function uw(){let{workspaceName:e,treeName:t}=ll(),n=nl(),r=al(),{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]:[]})(),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(!0),[p,m]=(0,X.useState)([]),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(0),y=ZC(),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(y);S!==y&&(C(y),y||x(null));let[w,T]=(0,X.useState)(`path`),[E,D]=(0,X.useState)(!1),[O,k]=(0,X.useState)(null),[A,j]=(0,X.useState)(null),[M,N]=(0,X.useState)(``),[P,ee]=(0,X.useState)(!1),[F,I]=(0,X.useState)(!1),[L,R]=(0,X.useState)(!1),[te,ne]=(0,X.useState)(null),[z,re]=(0,X.useState)(1),[ie,ae]=(0,X.useState)(50),[oe,se]=(0,X.useState)(s),[B,ce]=(0,X.useState)(null),{state:V,saveFilters:le,toggleView:ue,setSort:de,setAccentColor:fe,setMapDocuments:pe,hasActiveFilters:me}=Os(),he=V.filters.features.allOf,ge=V.filters.features.anyOf,_e=V.filters.features.noneOf,ve=V_(V.filters.timeline),ye=R_(V.filters.geo),H=z_(V.filters.lens,V.filters.geo.includeUnlocated),be=V.filters.lens.ids,U=[...ve,...ye,...H],xe=V.filters.sort??F_,Se=JSON.stringify({a:he,b:ge,c:_e,d:U,i:be,s:xe}),Ce=JSON.stringify({a:he,b:ge,c:_e,d:U,s:xe}),W=nb(n.pathname).path,G=t??`context`,we=G===`backends`,[Te,Ee]=(0,X.useState)([]);(0,X.useEffect)(()=>{!we||!e||Ta(e).then(Ee).catch(()=>Ee([]))},[we,e]);let De=we?no(W,Te):null,[Oe,ke]=(0,X.useState)(!1),Ae=`${G}\0${W}`,[je,Me]=(0,X.useState)(Ae);je!==Ae&&(Me(Ae),ke(!1));let Ne=o.get(`layer`)===`1`,Pe=o.get(`layerId`)||null,[Fe,Ie]=(0,X.useState)(null),[Le,Re]=(0,X.useState)(null),ze=(0,X.useRef)(null);(0,X.useEffect)(()=>{ze.current=Le},[Le]);let[Be,Ve]=(0,X.useState)(`left`),[He,Ue]=(0,X.useState)([]),{openM2Drawer:We}=zS(),Ge=Jm(),[Ke,qe]=(0,X.useState)([]),Je=(0,X.useMemo)(()=>{if(!Fe||W===`/`||Ne)return null;let e=W.split(`/`).filter(Boolean),t=Fe;for(let n of e)if(t=t?.children?.find(e=>e.name===n)??null,!t)return null;return t},[Fe,W,Ne]),Ye=Je?.type===`canvas`?`canvas`:null,Xe=(0,X.useRef)(null);(0,X.useEffect)(()=>{!e||!Fe||Ne||Xe.current===`${e}/${G}`&&(W!==`/`&&!Je||fS(e,G,W))},[e,Fe,Ne,W,Je,G]);let Ze=(0,X.useMemo)(()=>Ne||w===`workspace`||oe.length>0||lo(G)!==`directory`?[]:nw(Fe,W),[Fe,W,G,Ne,w,oe]),$e=Ne?null:W===`/`?Fe:Je,et=`${G}\0${W}`,[tt,nt]=(0,X.useState)(null),rt=tt?.key===et?tt.views:vC($e?.metadata),it=tt?.key===et?tt.activeId:rt[0]?.id??gC.id,at=rt.find(e=>e.id===it)??rt[0]??gC,ot=e=>nt({key:et,views:rt,activeId:e}),st=(t,n)=>{nt({key:et,views:t,activeId:n??it}),ia(e,W,{metadata:{...$e?.metadata??{},views:t}},G).catch(()=>{i({title:`View not saved`,description:`Could not persist views to the layer`,variant:`destructive`})})},ct=Ye===`canvas`&&typeof Je?.querySpec?.query==`string`?Je.querySpec.query:``,lt=Ye===`canvas`?{label:Je?.label,description:Je?.description,color:Je?.color}:null,{isPinned:ut,pin:dt,unpin:ft,pins:pt}=RC(),mt=l?.name,ht=(0,X.useMemo)(()=>mt&&Ye===`canvas`&&!Ne?{workspaceName:mt,treeName:G,path:W}:null,[mt,Ye,Ne,G,W]),gt=ht?ut(ht):!1,_t=Je?.id,vt=Je?.label,yt=(0,X.useCallback)(async()=>{if(ht)try{let e=pt.find(e=>e.workspaceName===ht.workspaceName&&e.treeName===ht.treeName&&e.path===ht.path);e?await ft(e.id):await dt({...ht,layerId:_t,label:vt})}catch(e){console.error(`Failed to update home pins:`,e)}},[ht,pt,dt,ft,_t,vt]),bt=e?`${e}://${W===`/`?``:W.replace(/^\//,``)}`:``,xt=hp(l?.color)||null;(0,X.useEffect)(()=>(fe(xt),()=>fe(null)),[xt,fe]);let St=(0,X.useCallback)(async t=>{let n=be;if(t?.anyOf?.length&&ge.length&&(n=((await Yi(e,W,G,{limit:0,anyOf:ge,ids:be,applyCanvasSpec:!1})).payload||[]).map(e=>e.id),!n.length))return{payload:[],count:0,totalCount:0};let r=await Yi(e,W,G,{limit:t?.limit,offset:t?.offset,page:t?.page,sortBy:t?.sortBy,order:t?.order,allOf:[...he,...t?.allOf??[]],anyOf:t?.anyOf?.length?t.anyOf:ge,noneOf:_e,filters:U,ids:n,queries:[...oe,...t?.queries??[],...t?.q?[t.q]:[]],applyCanvasSpec:!1});return{payload:r.payload||[],count:r.count??void 0,totalCount:r.totalCount??void 0}},[e,W,G,Se,oe]);(0,X.useEffect)(()=>{e&&(async()=>{f(!0);try{let t=await J.get(`${Sr.workspaces}/${e}`),n;n=t&&`workspace`in t?t.workspace:t,u(n)}catch(t){let n=t instanceof Error?t.message:`Failed to fetch workspace ${e}`;i({title:`Error`,description:n,variant:`destructive`}),u(null)}finally{f(!1)}})()},[e,i]),(0,X.useEffect)(()=>{let e=e=>{let t=e.detail?.workspace;t&&u(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 Ct=(be?.length??0)>0&&!Ne&&!(Oe&&De)&&oe.length<=1,{documents:wt,count:Tt,ready:Et,setCue:Dt,resync:Ot,rank:kt}=KC({workspaceRef:e,specs:(0,X.useMemo)(()=>{let e={features:{allOf:he,anyOf:ge,noneOf:_e},filters:U};return w!==`workspace`&&(lo(G)===`directory`?e.directory={tree:G,path:W}:e.context=W),[{label:`scope`,spec:e}]},[Ce,W,G,w]),opts:(0,X.useMemo)(()=>({mode:`live`,debounceMs:150}),[]),enabled:Ct}),At=Ct&&Et,jt=(0,X.useRef)(!1);(0,X.useEffect)(()=>{jt.current=At},[At]);let Mt=oe.length===1?oe[0].trim():``;(0,X.useEffect)(()=>{Et&&kt(Mt?{text:Mt}:null,{limit:ie,offset:(z-1)*ie}).catch(()=>{})},[Et,Mt,ie,z,kt]);let Nt=(be??[]).join(`,`);(0,X.useEffect)(()=>{Et&&Dt(`lens`,{ids:be??[]}).catch(()=>{})},[Et,Nt,Dt,be]);let Pt=At?wt:p,Ft=At?Tt:_,It=(0,X.useRef)(new Set);(0,X.useEffect)(()=>{It.current=new Set(Pt.map(e=>Number(e.id)))},[Pt]);let Lt=V.geoSelection;(0,X.useEffect)(()=>{pe(Pt,l?.name??null)},[Pt,l?.name,pe]),(0,X.useEffect)(()=>()=>pe([]),[pe]);let Rt=(0,X.useMemo)(()=>Lt?Pt.filter(e=>O_(e,Lt,V.filters.geo.includeUnlocated)):Pt,[Pt,Lt,V.filters.geo.includeUnlocated]),zt=(0,X.useRef)(0),Bt=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>{zt.current++,Bt.current=null},[]);let Vt=(0,X.useRef)(``),Ht=(0,X.useCallback)(async t=>{if(!e)return;if(rv(G,W)){zt.current++,Bt.current=null,Vt.current=``,m([]),v(0),g(!1);return}if(jt.current)return;let n=Oe&&De?`${w}:unfiled`:w,r=(be?.length??0)>0,a=aw(e,G,W,z,ie,oe.join(`␟`),Ce,Ne&&Pe?Pe:``,n),o=r&&a===Vt.current;Vt.current=a;let s=aw(e,G,W,z,ie,oe.join(`␟`),Se,Ne&&Pe?Pe:``,n),c=`${s}\0${y}`;if(t?.silent&&Bt.current?.key===c){Bt.current.refreshPending=!0;return}let l=++zt.current,u=t?.silent||r||y?void 0:rw.get(s);if(u){Bt.current=null,m(u.documents),v(u.totalCount),g(!1);return}(t?.silent??o)||g(!0);let d={key:c,refreshPending:!1};Bt.current=d;try{let t;t=Oe&&De?await Va(e,De.driver,De.address,{linked:!1,limit:ie,offset:(z-1)*ie}):Ne&&Pe&&w!==`workspace`?await Wa(e,G,Pe,{limit:ie,page:z,queries:oe,allOf:he,anyOf:ge,noneOf:_e,filters:U,ids:be,sortBy:xe.sortBy||void 0,order:xe.order}):await so(e,W,he,{limit:ie,page:z,treeName:G,treeType:G===`directory`||G===`backends`?`directory`:`context`,queries:oe,anyOf:ge,noneOf:_e,filters:U,ids:be,sortBy:xe.sortBy||void 0,order:xe.order,scope:w,debug:y&&oe.length>0,debugLimit:200});let n=t.payload||[],i=t.totalCount||t.count||0;if(!r&&!d.refreshPending&&rw.set(s,{documents:n,totalCount:i}),l!==zt.current)return;let a=t.debug,c=a?.imageDistances??a?.distances??null;x(c?{query:oe[oe.length-1]??``,distances:c}:null),m(o?e=>e.length===n.length&&e.every((e,t)=>e.id===n[t].id)?e:n:n),v(i)}catch(e){if(l!==zt.current)return;let t=e instanceof Error?e.message:`Failed to fetch documents`;i({title:`Error`,description:t,variant:`destructive`}),m([]),v(0)}finally{Bt.current===d&&(Bt.current=null),l===zt.current&&g(!1),l===zt.current&&d.refreshPending&&Ht({silent:!0})}},[e,W,G,Pe,Ne,z,ie,l?.status,oe,Se,w,Oe,y]);(0,X.useEffect)(()=>{Ht()},[Ht]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;!n||n.workspaceName!==e||(Re({treeName:n.treeName||`context`,path:eb(n.path||`/`)}),Ve(`left`))};return window.addEventListener(`workspace:open-to-side`,t),()=>window.removeEventListener(`workspace:open-to-side`,t)},[e,G,W]),(0,X.useEffect)(()=>{let t=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||(e&&cw(e,n),!(n?.treeName&&n.treeName!==G)&&(n?.path&&n.path!==W||(e&&ow(e,G,W),Ht({silent:!0}))))};return window.addEventListener(`workspace:documents:refresh`,t),()=>window.removeEventListener(`workspace:documents:refresh`,t)},[Ht,e,W,G]);let Ut=l?.name,Wt=l?.id;(0,X.useEffect)(()=>{if(!e||!Ut&&!Wt)return;let t=[Ut,Wt].filter(Boolean).map(e=>`workspace:${e}`),n=()=>t.forEach(e=>id.emit(`subscribe`,{channel:e}));n();let r=id.on(`connect`,n),i=new Map,a=!1,o=()=>{Fa(e).then(e=>{a||(i=MC(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,jt.current){Ot();return}Ht({silent:!0})}},f=t=>n=>{(t.startsWith(`tree.created`)||t.startsWith(`tree.renamed`))&&o();let r=NC(t,n,i);sw(e,r);let a={tree:G,kind:lo(G),path:W,wholeWorkspace:w===`workspace`},f=ze.current;f&&IC(r,{tree:f.treeName,kind:lo(f.treeName),path:f.path})&&(u=f),IC(r,a,It.current)&&(l=!0),!(!l&&!u)&&(s||=setTimeout(d,Math.max(200,c+1500-Date.now())))},p=[`document.inserted`,`document.updated`,`document.removed`,`document.deleted`,`document.removed.batch`,`document.deleted.batch`,`document.linked`,`document.unlinked`,`document.linked.batch`,`document.unlinked.batch`,`tree.document.inserted`,`tree.document.inserted.batch`,`tree.document.removed`,`tree.document.removed.batch`,`tree.document.deleted`,`tree.document.deleted.batch`,`tree.layer.merged`,`tree.layer.subtracted`,`tree.created`,`tree.renamed`].map(e=>[e,f(e)]);return p.forEach(([e,t])=>id.on(e,t)),()=>{a=!0,s&&clearTimeout(s),r?.(),p.forEach(([e,t])=>id.off(e,t))}},[e,Wt,Ut,G,W,w,Ht,Ot]);let Gt=`${W}\0${G}\0${Pe??``}\0${w}`,[Kt,qt]=(0,X.useState)(Gt);Kt!==Gt&&(qt(Gt),re(1),ce(null));let Jt=`${W}\0${G}\0${Pe??``}`,[Yt,Xt]=(0,X.useState)(Jt);Yt!==Jt&&(Xt(Jt),T(`path`));let Zt=(e,t)=>{let n=e===`/`?`canvas`:e.split(`/`).pop()||`canvas`;N(n),j({parentPath:e,captureView:t})},Qt=o.get(`createCanvas`)===`1`,[$t,en]=(0,X.useState)(!1);$t!==Qt&&(en(Qt),Qt&&Zt(W,!1)),(0,X.useEffect)(()=>{if(!Qt)return;let e=new URLSearchParams(n.search);e.delete(`createCanvas`);let t=e.toString();r(`${n.pathname}${t?`?${t}`:``}`,{replace:!0})},[Qt,W]);let tn=(0,X.useCallback)(e=>{let t=new URLSearchParams(n.search);t.delete(`q`),t.delete(`search`);for(let n of e)t.append(`q`,n);let i=t.toString();r(`${n.pathname}${i?`?${i}`:``}`)},[n.pathname,n.search,r]),nn=s.join(`␟`),[rn,an]=(0,X.useState)(nn);rn!==nn&&(an(nn),se(s),re(1));let on=`${nn}\0${Ye??``}\0${ct}\0${W}\0${B??``}`,[sn,cn]=(0,X.useState)(on);sn!==on&&(cn(on),s.length>0||Ye!==`canvas`||B===W||(se(ct?[ct]:[]),re(1)));let ln=(0,X.useCallback)(e=>{let t=e.trim();t&&(ce(null),se(e=>{if(e.includes(t))return e;let n=[...e,t];return tn(n),re(1),n}))},[tn,ce,se,re]),un=(0,X.useCallback)(e=>{se(t=>{let n=e<0?[]:t.filter((t,n)=>n!==e);return n.length===0&&ce(W),tn(n),re(1),n})},[tn,W,ce,se,re]),dn=oe.join(` `).trim(),fn=!!V.activeContextType&&(V.isDirty||dn!==(Ye===`canvas`?ct:V.savedSearchQuery||``));!e&&Fe!==null&&Ie(null),(0,X.useEffect)(()=>{let t=!1;if(!e)return;let n=0,r=!1,i=(i=!1)=>{let a=++n;i&&Sa(e,G),Gi(e,G).then(i=>{!t&&a===n&&(r=!0,Xe.current=`${e}/${G}`,Ie(i))}).catch(()=>{!t&&a===n&&!r&&Ie(null)})};i(!1);let a=t=>{let n=t.detail;n?.workspaceName&&n.workspaceName!==e||n?.treeName&&n.treeName!==G||i(!n?.cacheInvalidated)};window.addEventListener(`workspace:tree:refresh`,a);let o=tw(e,Wt);return()=>{t=!0,o(),window.removeEventListener(`workspace:tree:refresh`,a)}},[e,G,Wt]),!(e&&Ye===`canvas`&&!Ne)&&te!==null&&ne(null),(0,X.useEffect)(()=>{let t=!1;if(!(!e||Ye!==`canvas`||Ne))return _i(e,W,G).then(e=>{t||ne(e)}).catch(()=>{t||ne(null)}),()=>{t=!0}},[e,W,G,Ye,Ne]);let pn=async()=>{if(l){D(!0);try{let t=await Ua(e||l.id);u(t),i({title:`Success`,description:`Workspace started successfully`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){let t=e instanceof Error?e.message:`Failed to start workspace`;i({title:`Error`,description:t,variant:`destructive`})}finally{D(!1)}}},mn=async t=>{if(l)try{await Ki(e||l.id,[t],W,[],G,Sn,{trashIfOrphaned:!0}),ow(e||l.id,G,W),m(e=>e.filter(e=>e.id!==t)),v(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document removed from workspace path.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove document`,variant:`destructive`})}},hn=async t=>{if(l)try{await ho(e||l.id,[t],W,[],G,Sn),ow(e||l.id,G,W),m(e=>e.filter(e=>e.id!==t)),v(e=>Math.max(0,e-1)),i({title:`Success`,description:`Document deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete document`,variant:`destructive`})}},gn=async t=>{if(l)try{await Ki(e||l.id,t,W,[],G,Sn,{trashIfOrphaned:!0}),ow(e||l.id,G,W),m(e=>e.filter(e=>!t.includes(e.id))),v(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},_n=async t=>{if(l)try{await ho(e||l.id,t,W,[],G,Sn),ow(e||l.id,G,W),m(e=>e.filter(e=>!t.includes(e.id))),v(e=>Math.max(0,e-t.length)),i({title:`Success`,description:`${t.length} document(s) deleted.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},vn=async t=>{if(l)try{let n=await ni(e||l.id,[t]);if(n.failed?.length){i({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}m(e=>e.filter(e=>e.id!==t)),v(e=>Math.max(0,e-1)),i({title:`Destroyed`,description:`Document removed from all backends.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy document`,variant:`destructive`})}},yn=async t=>{if(l)try{let n=await ni(e||l.id,t),r=new Set(n.successful?.filter(e=>e.docDeleted).map(e=>e.id)??[]);m(e=>e.filter(e=>!r.has(e.id))),v(e=>Math.max(0,e-r.size));let a=[n.successful?.length?`${n.successful.length} destroyed`:null,n.failed?.length?`${n.failed.length} failed`:null].filter(Boolean).join(`, `);i({title:`Done`,description:a||`No documents destroyed`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},bn=e=>{k({documentIds:e,operation:`copy`,sourcePath:W,sourceTreeName:G}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}})),i({title:`Copied`,description:`${e.length} document(s) copied to clipboard`})},xn=e=>{k({documentIds:e,operation:`cut`,sourcePath:W,sourceTreeName:G}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}})),i({title:`Cut`,description:`${e.length} document(s) cut to clipboard`})},Sn=lo(G),Cn=async(t,n,r={})=>{if(!e)return!1;let i=r.targetTreeName??G,o=r.targetTreeType??Sn,s=r.move||O?.operation===`cut`,c=a({title:s?`Moving…`:`Pasting…`,description:`${n.length} document(s) → "${t}"`});try{let a=await li(e,t,n,i,o);if(a){ow(e,i,t);let a=r.sourceTreeName||O?.sourceTreeName,o=r.sourcePath||O?.sourcePath;if((r.move||O?.operation===`cut`)&&o&&a){let t=lo(a);await Ki(e,n,o,[],a,t),ow(e,a,o),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:o,treeName:a}}))}c.done({title:`Success`,description:`${n.length} document(s) ${s?`moved`:`pasted`} to "${t}"`}),k(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}));let l=performance.now();await Ht(),console.info(`[paste] list refresh ${Math.round(performance.now()-l)} ms`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:i}}))}else c.done();return a}catch(e){return c.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},wn=async(t,n)=>{if(!e)return!1;try{let r=(await io(e,n,t,G,Sn)).length>0;return r&&(window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:G}})),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}},Tn=async()=>{if(!(!l||_===0)&&window.prompt(`Type PURGE to permanently delete all ${_} matching documents.`)===`PURGE`)try{let t=await Si(e||l.id,W,[],[],{},G);await Ht(),i({title:`Success`,description:`${t.deleted} document(s) purged.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to purge documents`,variant:`destructive`})}},En=()=>Zt(W,!0),Dn=async()=>{if(!(!e||!A||!M.trim())){ee(!0);try{let t=M.trim(),n=A.parentPath,i=n===`/`?`/${t}`:`${n}/${t}`;await bo(e,i,G,A.captureView?{metadata:{toolbox:V.filters},querySpec:{features:V.filters.features,filters:[...V_(V.filters.timeline),...R_(V.filters.geo)],query:dn||void 0,sort:V.filters.sort?.sortBy?V.filters.sort:null}}:{}),j(null),Sa(e,G);try{let t=await Gi(e,G,{force:!0});Ie(t)}catch{}window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e}})),r(rb(e,i,G))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create canvas`,variant:`destructive`})}finally{ee(!1)}}},On=async()=>{if(!(!e||Ye!==`canvas`)){I(!0);try{let t=te||await ra(e,W,G);ne(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)}}},kn=async()=>{if(te){I(!0);try{await vo(te.code),ne(null),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:G}})),i({title:`Canvas unshared`,description:`The public link no longer works.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to unshare canvas`,variant:`destructive`})}finally{I(!1)}}},An=async()=>{if(!e||Ye!==`canvas`||W===`/`)return;let t=lt?.label||W.split(`/`).pop()||`canvas`,n=te?` Its public link will stop working.`:``;if(window.confirm(`Delete canvas "${t}"? This cannot be undone.${n}`)){R(!0);try{if(te)await vo(te.code),ne(null);else if(Je?.locked){i({title:`Canvas is locked`,description:`Unlock it before deleting.`,variant:`destructive`});return}await Xi(e,W,!1,G);let n=W.split(`/`).filter(Boolean);n.pop();let a=n.length?`/${n.join(`/`)}`:`/`;window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:G}})),r(rb(e,a,G)),i({title:`Canvas deleted`,description:`"${t}" was removed.`})}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete canvas`,variant:`destructive`})}finally{R(!1)}}},jn=(0,X.useCallback)(async t=>{if(!e||!Le)return;let n={treeName:G,path:W},r=Be===`left`?n:Le,o=Be===`left`?Le:n,s=Be===`left`?He:Ke;if(s.length===0){i({title:`Nothing selected`,description:`Tick documents in the focused pane first.`});return}let c=lo(o.treeName),l=a({title:t?`Moving…`:`Copying…`,description:`${s.length} document(s) → "${o.path}"`});try{if(!await li(e,o.path,s,o.treeName,c)){l.done();return}if(ow(e,o.treeName,o.path),t){let t=lo(r.treeName);await Ki(e,s,r.path,[],r.treeName,t),ow(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,Le,Be,G,W,He,Ke,i,a]);if((0,X.useEffect)(()=>{if(!Le)return;let e=e=>{if(e.key!==`F5`&&e.key!==`F6`)return;let t=e.target;t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&(e.preventDefault(),jn(e.key===`F6`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Le,jn]),d)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,Z.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Z.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading workspace...`})]})});if(!l)return(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-full text-muted-foreground`,children:`Workspace not found.`});let Mn=Ye===`canvas`&&!Ne&&!!Je,Nn=rv(G,W)?(0,Z.jsx)(sC,{workspace:e||l.id,path:W,onNavigate:t=>r(rb(e,t,`backends`))},e):(0,Z.jsx)(mC,{urlType:Ne?lo(G)===`directory`?`${G}-layer`:`context-layer`:Ye===`canvas`?`canvas`:lo(G)===`directory`?G:`context`,urlDisplay:bt,contextPath:W,treeName:G,workspaceId:e||l.id,documents:Rt,isLoading:h,totalCount:Ft,currentPage:z,pageSize:ie,onPageChange:re,onPageSizeChange:e=>{ae(e),re(1)},onRemoveDocument:W===`/`?void 0:mn,onDeleteDocument:hn,onDestroyDocument:vn,onRemoveDocuments:W===`/`?void 0:gn,onDeleteDocuments:_n,onDestroyDocuments:yn,onCopyDocuments:bn,onCutDocuments:xn,onPasteDocuments:we?void 0:Cn,onImportDocuments:we?void 0:wn,onSelectionChange:Ue,selectedCount:He.length,onBrowseTree:()=>We(`workspaces`,`detail`,e??null),onNavigatePath:t=>r(rb(e,t,G)),folders:Ze,onOpenFolder:t=>r(rb(e,eb(t),G)),scope:w,onScopeChange:T,pastedDocumentIds:O?.documentIds,linkTree:Fe,onPurgeDocuments:we?void 0:Tn,disablePurgeDocuments:!1,canvasInfo:lt??void 0,isCanvasPinned:gt,onTogglePinCanvas:ht?yt:void 0,onSaveAsCanvas:Fe&&Ye!==`canvas`&&!Ne&&!we?En:void 0,onShareCanvas:Ye===`canvas`&&!Ne?On:void 0,onUnshareCanvas:te?kn:void 0,onDeleteCanvas:Ye===`canvas`&&!Ne?An:void 0,isSharingCanvas:F,isDeletingCanvas:L,isCanvasShared:!!te,isCanvasLocked:!!Je?.locked,backendSearchQueries:oe,onBackendSearch:ln,serverSort:V.filters.sort,onServerSortChange:de,onRemoveBackendQuery:un,canSaveChanges:fn,isSavingChanges:V.isSaving,onSaveChanges:le,contentBanner:y&&b?(0,Z.jsx)(QC,{data:b,className:`mb-3`}):null,children:Mn&&Je?(0,Z.jsx)(Eb,{workspaceId:e||l.id,treeName:G,path:W,layerId:Je.id,querySpec:Je.querySpec,metadata:Je.metadata,isLocked:!!Je.locked,fetchDocuments:V.isDirty?St:void 0}):!we&&at.kind===`columns`?(0,Z.jsx)(DC,{documents:Rt,workspaceId:e||l.id,columns:at.columns??[],onColumnsChange:e=>st(rt.map(t=>t.id===at.id?{...t,columns:e}:t))}):!we&&at.kind===`app`&&at.app?(0,Z.jsx)(wC,{app:at.app,workspaceId:e||l.id,treeName:G,path:W}):null});return(0,Z.jsxs)(`div`,{className:`relative flex flex-col h-full min-h-0`,children:[(0,Z.jsx)(uC,{workspaceId:l.id,workspaceName:l.label||l.name},l.id),(0,Z.jsxs)(`div`,{className:`relative shrink-0 max-sm:border-b`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border max-sm:hidden`,style:hp(l.color)?{backgroundColor:hp(l.color)}:void 0}),!Mn&&!we&&$e&&(0,Z.jsxs)(`div`,{className:`relative px-2 pt-1.5 sm:hidden`,children:[(0,Z.jsx)(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-0 h-[3px] bg-border`,style:hp(l.color)?{backgroundColor:hp(l.color)}:void 0}),(0,Z.jsx)(yC,{accentColor:hp(l.color),views:rt,activeId:it,onSelect:ot,onSave:st,readOnly:!1})]}),(0,Z.jsxs)(`div`,{className:`flex h-12 items-center gap-3 px-4`,children:[(0,Z.jsx)(tS,{title:Ge?`Back to workspace tree`:`Back to workspaces`,onBack:()=>Ge?We(`workspaces`,`detail`,e||l.id):r(`/workspaces`)}),(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0 ${l.status===`active`?`bg-success`:l.status===`error`?`bg-destructive`:`bg-muted-foreground`}`,title:l.status}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>We(`workspaces`,`detail`,e||l.id),title:`Browse workspace tree`,className:`flex min-w-0 items-center gap-1.5 truncate rounded px-1 -mx-1 text-left text-sm font-medium transition-colors hover:bg-accent`,children:[(0,Z.jsx)(c,{icon:l.icon||`ph:stack-fill`,width:16,height:16,color:hp(l.color),className:K(`shrink-0`,!hp(l.color)&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`truncate`,children:l.label||l.name})]}),!Mn&&!we&&$e?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(yC,{className:`min-w-0 flex-1 self-stretch max-sm:hidden`,accentColor:hp(l.color),views:rt,activeId:it,onSelect:ot,onSave:st,onOpenToSide:e=>{Re({treeName:G,path:W,viewId:e}),Ve(`right`)},readOnly:!1}),(0,Z.jsx)(`div`,{className:`flex-1 sm:hidden`})]}):(0,Z.jsx)(`div`,{className:`flex-1`}),De&&(0,Z.jsx)(`button`,{onClick:()=>{ke(!Oe),re(1)},className:K(`flex items-center gap-1.5 px-3 py-1 text-xs border rounded-md transition-colors`,Oe?`bg-warning/15 border-warning/40 text-warning`:`hover:bg-accent text-muted-foreground hover:text-foreground`),title:`Show only documents not filed into any context/directory tree (safe to purge from the backend)`,children:`Unfiled only`}),l.status===`active`?(0,Z.jsx)(`button`,{onClick:()=>ue(`tools`),className:K(`flex h-7 w-7 items-center justify-center border rounded-md transition-colors touch-target`,me?`border-info bg-info text-info-foreground hover:bg-info/90`:V.t1Open&&V.t1View===`tools`?`bg-accent text-foreground`:`hover:bg-accent text-muted-foreground hover:text-foreground`),"aria-label":`Filters`,title:me?`Toolbox filters are active and narrow this view`:`Open the toolbox filters`,children:(0,Z.jsx)(Qe,{className:`h-3.5 w-3.5`})}):(0,Z.jsx)(`button`,{onClick:pn,disabled:E,className:`px-3 py-1 text-xs border rounded-md hover:bg-accent disabled:opacity-50 touch-target`,children:E?`Starting…`:`Start`}),(0,Z.jsx)(eS,{})]})]}),A&&(0,Z.jsx)(`div`,{className:`shrink-0 px-2 pt-2`,children:(0,Z.jsx)(aS,{title:`New canvas`,onClose:()=>j(null),children:(0,Z.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Dn()},className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`canvas-name`,className:`mb-1 block text-sm font-medium`,children:`Name`}),(0,Z.jsx)(`input`,{id:`canvas-name`,className:`w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`Canvas name…`,value:M,onChange:e=>N(e.target.value),onKeyDown:e=>{e.key===`Escape`&&j(null)},autoFocus:!0})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`span`,{className:`mb-1 block text-sm font-medium`,children:`Parent path`}),(0,Z.jsx)(`div`,{className:`flex h-10 items-center rounded-md bg-muted px-3 font-mono text-sm text-muted-foreground`,children:A.parentPath===`/`?`/`:A.parentPath})]})]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2 text-sm`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,className:`mt-0.5`,checked:A.captureView,onChange:e=>j({...A,captureView:e.target.checked})}),(0,Z.jsxs)(`span`,{children:[`Capture the current view`,(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:`Freezes the active filters, search and sort into the canvas.`})]})]}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(Y,{type:`submit`,disabled:!M.trim()||P,children:P?`Creating…`:`Create canvas`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,onClick:()=>j(null),children:`Cancel`})]})]})})}),(0,Z.jsxs)(`div`,{"data-canvas-panes":!0,className:`flex-1 min-h-0 flex gap-2 p-2 bg-muted/20`,children:[(0,Z.jsx)(`div`,{"data-canvas-pane":!0,className:K(`flex-1 min-w-0 rounded-lg border bg-background overflow-hidden`,Le&&(Be===`left`?`ring-2 ring-primary`:`ring-1 ring-primary/20`)),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||Ve(`left`)},children:Nn}),Le&&e&&(0,Z.jsx)(fw,{workspaceName:e,pane:Le,isFocused:Be===`right`,clipboard:O,setClipboard:k,onFocus:()=>Ve(`right`),onSelectionChange:qe,onNavigate:e=>Re(t=>t&&{...t,path:e,viewId:void 0}),onClose:()=>{Re(null),Ve(`left`),qe([])}})]})]})}function dw(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 fw({workspaceName:e,pane:t,isFocused:n=!1,clipboard:r,setClipboard:i,onFocus:a,onSelectionChange:o,onNavigate:s,onClose:c}){let{showToast:l,showProgress:u}=Vr(),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)([]),[h,g]=(0,X.useState)(!1),[_,v]=(0,X.useState)(0),[y,b]=(0,X.useState)(1),[x,S]=(0,X.useState)(50),C=lo(t.treeName),w=dw(d,t.path),T=w?.type===`canvas`,E=(0,X.useMemo)(()=>C===`directory`?nw(d,t.path):[],[d,t.path,C]),D=t.viewId?vC(w?.metadata).find(e=>e.id===t.viewId)??null:null,O=`${e}://${t.path===`/`?``:t.path.replace(/^\//,``)}`,k=(0,X.useCallback)(async()=>{if(rv(t.treeName,t.path)){m([]),v(0),g(!1);return}let n=aw(e,t.treeName,t.path,y,x,``,``),r=rw.get(n);if(r){m(r.documents),v(r.totalCount);return}g(!0);try{let r=await so(e,t.path,[],{limit:x,page:y,treeName:t.treeName,treeType:C}),i=r.payload||[],a=r.totalCount||r.count||0;m(i),v(a),rw.set(n,{documents:i,totalCount:a})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to fetch side pane documents`,variant:`destructive`}),m([]),v(0)}finally{g(!1)}},[e,t.path,t.treeName,C,x,y,l]);(0,X.useEffect)(()=>{let n=!1,r=0,i=!1,a=(a=!1)=>{let o=++r;a&&Sa(e,t.treeName),Gi(e,t.treeName).then(e=>{!n&&o===r&&(i=!0,f(e))}).catch(()=>{!n&&o===r&&!i&&f(null)})};a(!1);let o=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||r?.treeName&&r.treeName!==t.treeName||a(!r?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,o),()=>{n=!0,window.removeEventListener(`workspace:tree:refresh`,o)}},[e,t.treeName]),(0,X.useEffect)(()=>{k()},[k]),(0,X.useEffect)(()=>{let n=n=>{let r=n.detail;r?.workspaceName&&r.workspaceName!==e||(cw(e,r),!(r?.treeName&&r.treeName!==t.treeName)&&(r?.path&&r.path!==t.path||(ow(e,t.treeName,t.path),k())))};return window.addEventListener(`workspace:documents:refresh`,n),()=>window.removeEventListener(`workspace:documents:refresh`,n)},[k,e,t.treeName,t.path]);let A=(0,X.useCallback)(async(n,a,o={})=>{let s=o.targetTreeName??t.treeName,c=o.targetTreeType??C,l=o.move||r?.operation===`cut`,d=u({title:l?`Moving…`:`Pasting…`,description:`${a.length} document(s) → "${n}"`});try{let t=await li(e,n,a,s,c);if(t){ow(e,s,n);let t=o.sourcePath||r?.sourcePath,c=o.sourceTreeName||r?.sourceTreeName;if((o.move||r?.operation===`cut`)&&t&&c){let n=lo(c);await Ki(e,a,t,[],c,n),ow(e,c,t),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:t,treeName:c}}))}d.done({title:`Success`,description:`${a.length} document(s) ${l?`moved`:`pasted`} to "${n}"`}),i(null),await k(),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,path:n,treeName:s}}))}else d.done();return t}catch(e){return d.fail({title:`Error`,description:e instanceof Error?e.message:`Failed to paste documents`,variant:`destructive`}),!1}},[e,t.treeName,C,k,u,r,i]),j=(0,X.useCallback)(()=>{ow(e,t.treeName,t.path),k()},[e,t.treeName,t.path,k]),M=(0,X.useCallback)(async n=>{try{await Ki(e,n,t.path,[],t.treeName,C),j(),l({title:`Removed`,description:`${n.length} document(s) removed from "${t.path}"`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to remove documents`,variant:`destructive`})}},[e,t.path,t.treeName,C,j,l]),N=(0,X.useCallback)(async n=>{try{await ho(e,n,t.path,[],t.treeName,C),j(),l({title:`Deleted`,description:`${n.length} document(s) deleted.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to delete documents`,variant:`destructive`})}},[e,t.path,t.treeName,C,j,l]),P=(0,X.useCallback)(async t=>{try{let n=await ni(e,t);if(n.failed?.length&&!n.successful?.length){l({title:`Error`,description:n.failed[0].reason,variant:`destructive`});return}j(),l({title:`Destroyed`,description:`${n.successful?.length??t.length} document(s) removed from all backends.`})}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Failed to destroy documents`,variant:`destructive`})}},[e,j,l]);return(0,Z.jsxs)(`div`,{className:K(`relative flex-1 min-w-0 rounded-lg border bg-background overflow-hidden`,n?`ring-2 ring-primary`:`ring-1 ring-primary/20`),onMouseDown:e=>{e.target.closest(`button,input,textarea,select,a`)||a()},children:[c&&(0,Z.jsx)(`button`,{type:`button`,onClick:c,className:`absolute right-2 top-2 z-10 px-2 py-1 text-xs rounded-md border bg-background/90 hover:bg-accent`,children:`Close`}),rv(t.treeName,t.path)?(0,Z.jsx)(sC,{workspace:e,path:t.path,onNavigate:s||(()=>{})}):(0,Z.jsx)(mC,{urlType:T?`canvas`:C===`directory`?t.treeName:`context`,urlDisplay:O,contextPath:t.path,treeName:t.treeName,workspaceId:e,documents:p,isLoading:h,totalCount:_,currentPage:y,pageSize:x,onPageChange:b,onPageSizeChange:e=>{S(e),b(1)},onRemoveDocument:t.path===`/`?void 0:e=>M([e]),onRemoveDocuments:t.path===`/`?void 0:M,onDeleteDocument:e=>N([e]),onDeleteDocuments:N,onDestroyDocument:e=>P([e]),onDestroyDocuments:P,onCopyDocuments:e=>{i({documentIds:e,operation:`copy`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`copy`}}))},onCutDocuments:e=>{i({documentIds:e,operation:`cut`,sourcePath:t.path,sourceTreeName:t.treeName}),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:{documentIds:e,operation:`cut`}}))},onPasteDocuments:t.treeName===`backends`?void 0:A,onSelectionChange:o,pastedDocumentIds:r?.documentIds,linkTree:d,folders:E,onOpenFolder:s,onNavigatePath:s,canvasInfo:T?{label:w?.label,description:w?.description,color:w?.color}:void 0,children:D?.kind===`columns`?(0,Z.jsx)(DC,{documents:p,workspaceId:e,columns:D.columns??[],onColumnsChange:()=>{},readOnly:!0}):D?.kind===`app`&&D.app?(0,Z.jsx)(wC,{app:D.app,workspaceId:e,treeName:t.treeName,path:t.path}):null})]})}function pw(){let{workspaceName:e}=ll();return e?(0,Z.jsx)(lC,{workspaceName:e,children:(0,Z.jsx)(mw,{})}):(0,Z.jsx)(`p`,{role:`alert`,className:`p-6`,children:`Workspace not specified.`})}function mw(){let{workspaceName:e=``,documentId:t=``,algo:n=``,checksum:r=``}=ll(),i=!!n&&!!r,a=i?`${n}/${r}`:t,o=JSON.stringify([e,t,n,r]),s=Number(t),c=/^\d+$/.test(t)&&Number.isSafeInteger(s)&&s>0,l=i||c,[u,d]=(0,X.useState)(0),[f,p]=(0,X.useState)(null),m=f?.identity===o?f:null,h=l&&(!m||m.revision!==u);return(0,X.useEffect)(()=>{let t=!1;if(l)return(i?ya(e,n,r):qr(e,s)).then(e=>{t||p({identity:o,revision:u,document:e||null,missing:!e,error:``})}).catch(e=>{t||p({identity:o,revision:u,document:null,missing:e?.statusCode===404,error:e instanceof Error?e.message:`Unable to retrieve this document.`})}),()=>{t=!0}},[e,s,o,u,l,i,n,r]),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`header`,{className:`flex shrink-0 flex-wrap items-center justify-between gap-3 border-b p-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`h1`,{className:`truncate text-lg font-semibold`,children:m?.document?Ui(m.document).title:`Document ${a}`}),(0,Z.jsxs)(`p`,{className:`break-all text-xs text-muted-foreground`,children:[`Workspace: `,e,` · `,i?`Checksum: ${a}`:`ID: ${t}`,m?.document&&` · ${i?`ID: ${m.document.id} · `:``}${m.document.schema}`]})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Z.jsx)(Su,{className:`text-sm underline`,to:`/workspaces/${encodeURIComponent(e)}`,children:`Workspace`}),(0,Z.jsx)(Y,{variant:`outline`,disabled:!l||h,onClick:()=>d(e=>e+1),children:`Refresh`})]})]}),m?.document?(0,Z.jsx)(j_,{document:m.document,workspaceId:e,onChanged:()=>d(e=>e+1)},o):h?(0,Z.jsx)(`p`,{role:`status`,className:`p-6 text-sm text-muted-foreground`,children:`Loading document…`}):(0,Z.jsxs)(`div`,{role:`alert`,className:`space-y-2 p-6 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium`,children:m?.missing?`Document ${a} not found`:`Unable to load document`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:l?m?.missing?`This record is no longer available in this workspace. Subtree exports skip missing records and report their IDs.`:m?.error:`Document ID must be a positive integer.`})]})]})}function hw(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 gw={id:`sketch`,label:`Sketch`,icon:rt,schemas:[Pa],canCreate:!0,canEdit:e=>e.schema===Pa,createUrl(e){let t=hw(e);return t.set(`add`,`1`),`/apps/sketch?${t.toString()}`},editUrl(e,t){let n=hw(t);return n.set(`doc`,String(e.id)),`/apps/sketch?${n.toString()}`}},_w=[{kind:`message`,label:`New Message`,icon:It},{kind:`note`,label:`Note`,icon:xn},{kind:`link`,label:`Link`,icon:Xt},{kind:`todo`,label:`Todo`,icon:On},{kind:`identity`,label:`Identity`,icon:Ze},{kind:`sketch`,label:`Sketch`,icon:rt},{kind:`file`,label:`File`,icon:te},{kind:`photo`,label:`Photo/Video`,icon:z},{kind:`existing`,label:`Existing document`,icon:Ot},{kind:`folder`,label:`Folder`,icon:ut}];function vw(){return typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia?_w:_w.filter(e=>e.kind!==`photo`)}function yw({onSelect:e,variant:t=`list`,omit:n}){let r=vw().filter(e=>!n?.includes(e.kind));return t===`stack`?(0,Z.jsx)(Z.Fragment,{children:r.map(({kind:t,label:n,icon:r})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex items-center gap-2 rounded-full bg-card px-3 py-1.5 text-sm font-medium shadow-elevation-3 transition-transform hover:scale-105`,children:[n,(0,Z.jsx)(r,{className:`h-3.5 w-3.5`})]},t))}):(0,Z.jsx)(`div`,{className:`p-2`,children:r.map(({kind:t,label:n,icon:r})=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>e(t),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted`,children:[(0,Z.jsx)(r,{className:`h-4 w-4 text-muted-foreground`}),n]},t))})}var bw=`data/schema/note`,xw=`2.0`;function Sw(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)([]),[c,l]=(0,X.useState)(!1),u=Ch(),d=n.trim().length>0&&!c;async function f(t){l(!0);try{let r=await u.capture(),a={schema:bw,schemaVersion:xw,...i.trim()?{comment:i.trim()}:{},data:{...e.trim()?{title:e.trim()}:{},content:n},metadata:{features:Kp(o),...r?{geo:r}:{}}};return await cs(t,[a])}finally{l(!1)}}return{title:e,setTitle:t,content:n,setContent:r,comment:i,setComment:a,tags:o,setTags:s,saving:c,canSave:d,save:f,geotag:u}}function Cw(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 ww({geotag:e,idPrefix:t=`geotag`}){let[n,r]=(0,X.useState)(!1),i=!e.supported||e.permission===`denied`,a=!e.manual&&(!e.supported||e.permission===`denied`||!!e.error);return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Z.jsxs)(`div`,{role:`switch`,"aria-checked":e.enabled,"aria-disabled":i,"aria-label":`Geotag this document`,"aria-describedby":`${t}-hint`,tabIndex:i?-1:0,onClick:()=>!i&&e.setEnabled(!e.enabled),onKeyDown:t=>{i||(t.key===` `||t.key===`Enter`)&&(t.preventDefault(),e.setEnabled(!e.enabled))},className:K(`flex flex-1 items-center justify-between gap-3 select-none outline-none rounded focus-visible:ring-2 focus-visible:ring-ring`,i?`cursor-not-allowed opacity-50`:`cursor-pointer`),children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm text-foreground`,children:[e.busy?(0,Z.jsx)(Mt,{className:`h-4 w-4 shrink-0 animate-spin text-muted-foreground`}):(0,Z.jsx)(yt,{className:K(`h-4 w-4 shrink-0`,e.enabled?`text-info`:`text-muted-foreground`)}),`Geotag`]}),(0,Z.jsx)(`div`,{className:K(`relative h-5 w-10 shrink-0 rounded-full transition-colors`,e.enabled?`bg-info`:`bg-muted-foreground/30`),children:(0,Z.jsx)(`div`,{className:K(`absolute top-[2px] h-4 w-4 rounded-full bg-background shadow-elevation-1 transition-transform`,e.enabled?`translate-x-[22px]`:`translate-x-[2px]`)})})]}),(0,Z.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>r(!0),title:`Pick a point on the map`,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,children:[(0,Z.jsx)(en,{className:`h-3.5 w-3.5`}),e.manual?`Change pin`:`Pick on map`]}),e.manual&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>e.setManual(null),"aria-label":`Remove custom pin`,title:`Remove custom pin`,className:`rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.jsx)(`p`,{id:`${t}-hint`,className:K(`text-xs`,a?`text-warning`:`text-muted-foreground`),children:Cw(e)}),n&&(0,Z.jsx)(nm,{initial:e.manual??e.fix??null,onPick:t=>e.setManual(t),onClose:()=>r(!1)})]})}function Tw(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 Ew({title:e,icon:t,onClose:n,onSave:r,navigateAfterSave:i=!1,canSave:a=!1,saving:o=!1,saveProgress:s,successMessage:c=`Saved`,lockedWorkspaceName:l,fillParent:u=!1,fullWidthContent:d=!1,relationSubjectId:f,frame:p,children:m}){let h=al(),[g,_]=(0,X.useState)(`portrait`),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(!1),[S,C]=(0,X.useState)(!1),[w,T]=(0,X.useState)(!1),E=o||w;Ff(()=>x(!1),b&&!E),Ff(()=>y(!1),v&&!b);let D=(0,X.useRef)(null),O=Jm(),{showSuccessToast:k,showErrorToast:A}=Wr(),j=O&&!u&&!v,[M,N]=(0,X.useState)(!1),P=!u&&!v&&!p&&!M;(0,X.useEffect)(()=>{b&&D.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[b]);let ee=async(e,t)=>{if(!(!r||E)){T(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>li(t.workspaceName,e,a,t.treeName,t.treeType))),k(c),n(),i&&h(Tw({...t,path:e[0]}),{replace:!0})}catch(e){A(e instanceof Error?e.message:`Failed to save`)}finally{T(!1)}}},F=async e=>{if(!(!f||!l||e.targetIds.length===0)){C(!0);try{await Ca(l,f,e.predicate,e.targetIds,e.direction),k(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),Dm(),x(!1)}catch(e){A(e instanceof Error?e.message:`Failed to create relations`)}finally{C(!1)}}},I=v?b?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:j?void 0:g===`portrait`?{aspectRatio:`0.707 / 1`,height:`calc(var(--viewport-h) * 0.85)`,width:`auto`,maxWidth:`min(90vw, 100%)`,flexShrink:0}:{aspectRatio:`1 / 0.707`,width:`min(90vw, 900px)`,maxWidth:`100%`,height:`auto`,maxHeight:`calc(var(--viewport-h) * 0.85)`,flexShrink:0},L=!!(f&&l),R=r&&b&&(0,Z.jsx)(Bp,{onClose:()=>x(!1),onConfirm:ee,fixedWorkspaceName:l,saving:E||S,savingContent:s,tabs:L?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:L?F:void 0,relationWorkspaceName:l,relationExcludeIds:L?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}),te=(0,Z.jsxs)(`div`,{style:p&&!v?{width:`100%`,height:`100%`,minWidth:0}:I,onAnimationEnd:e=>{P&&e.target===e.currentTarget&&N(!0)},className:K(`flex flex-col overflow-hidden`,p&&!v?`strip-document-card`:`rounded-2xl border bg-card shadow-elevation-4 transition-[width,height]`,u&&!v&&!p&&`w-full md:w-[var(--document-card-width,min(560px,90vw))]`,j&&`fixed inset-2 z-40 shadow-elevation-5`,P&&`animate-card-in`),children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,Z.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>_(e=>e===`portrait`?`landscape`:`portrait`),className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground max-md:hidden touch-target`,"aria-label":`Toggle orientation`,title:`Toggle orientation`,children:(0,Z.jsx)(ar,{className:`h-4 w-4`})}),r&&(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>x(!0),disabled:!a||E,children:E?`Saving…`:`Save / Link to…`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>p&&!v?p.onToggleExpanded():y(e=>!e),className:K(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,!v&&!p&&`max-md:hidden`),"aria-label":p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,title:p&&!v?p.expanded?`Card size`:`Expand to full width`:v?`Restore`:`Maximize`,children:v||p?.expanded?(0,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,disabled:E,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":`Close`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]})]}),(0,Z.jsx)(Om.Provider,{value:()=>y(e=>!e),children:(0,Z.jsx)(`div`,{className:K(`min-h-0 flex-1 overflow-y-auto`,v&&!d&&`mx-auto w-full max-w-3xl`),children:p&&R?R:m})})]});return v?(0,Mf.createPortal)((0,Z.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[te,R&&(0,Z.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:R})]}),document.body):(0,Z.jsxs)(Z.Fragment,{children:[te,!p&&R&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!E&&x(!1),"aria-hidden":!0}),(0,Z.jsx)(`div`,{ref:D,className:`relative shrink-0 md:z-panel md:ml-2 max-md:fixed max-md:bottom-2 max-md:left-2 max-md:right-2 max-md:top-2 max-md:z-card-overlay max-md:animate-fade-in`,children:R})]})]})}function Dw({onClose:e,initialData:t}){let n=Sw();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setContent(t.content)},[]),(0,Z.jsx)(Ew,{title:`New Note`,icon:xn,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Note created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`qa-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-note-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(Pu,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(Io,{kind:`markdown`,value:n.content,onChange:n.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(ww,{geotag:n.geotag,idPrefix:`qa-note-geotag`})]})})}var Ow=`data/schema/tab`,kw=`2.0`;function Aw(e){try{return new URL(e),!0}catch{return!1}}function jw(){let[e,t]=(0,X.useState)(``),[n,r]=(0,X.useState)(``),[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),c=Ch(),l=e.trim(),u=Aw(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:Ow,schemaVersion:kw,data:{url:l,...n.trim()?{title:n.trim()}:{},...r.length?{tags:r}:{}},metadata:{features:Kp(i),...t?{geo:t}:{}}};return await cs(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 Mw({onClose:e,initialData:t}){let n=jw();return(0,X.useEffect)(()=>{t?.url&&n.setUrl(t.url),t?.title&&n.setTitle(t.title)},[]),(0,Z.jsx)(Ew,{title:`New Link`,icon:Xt,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Link created`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`qa-link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`qa-link-url`,value:n.url,onChange:e=>n.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),n.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`qa-link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`qa-link-title`,value:n.title,onChange:e=>n.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsx)(ww,{geotag:n.geotag,idPrefix:`qa-link-geotag`})]})})}function Nw({onClose:e,initialData:t}){let n=Nh();return(0,X.useEffect)(()=>{t?.title&&n.setTitle(t.title),t?.content&&n.setDescription(t.content)},[]),(0,Z.jsx)(Ew,{title:`New Todo`,icon:On,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Todo created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(Ig,{...n,idPrefix:`qa-todo`}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`qa-todo-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`qa-todo-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`Optional context`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]}),(0,Z.jsx)(ww,{geotag:n.geotag,idPrefix:`qa-todo-geotag`})]})})}function Pw({onClose:e,initialData:t}){let n=Gg();return(0,X.useEffect)(()=>{t?.title&&n.setDisplayName(t.title)},[]),(0,Z.jsx)(Ew,{title:`New Identity`,icon:Ze,onClose:e,onSave:e=>n.save({mode:`workspace`,...e}),canSave:n.canSave,saving:n.saving,successMessage:`Identity created`,children:(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsx)(Xg,{idPrefix:`qa-identity`,...n,emailValid:n.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:n.tags,onChange:n.setTags})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`qa-identity-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`qa-identity-comment`,value:n.comment,onChange:e=>n.setComment(e.target.value),rows:3,placeholder:`How you know them, where they came from…`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring`})]})]})})}var Fw=3;function Iw(e){return`${e.name}:${e.size}:${e.lastModified}`}function Lw(e=[]){let[t,n]=(0,X.useState)(()=>e.map(e=>({id:Iw(e),file:e,status:`queued`,progress:0}))),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(t),o=(0,X.useRef)(null),s=(0,X.useRef)(null);(0,X.useEffect)(()=>()=>s.current?.abort(),[]);let c=(0,X.useCallback)(e=>{a.current=e,n(e)},[]),l=(0,X.useCallback)((e,t)=>{let r=a.current.map(n=>n.id===e?{...n,...t}:n);a.current=r,n(r)},[]),u=(0,X.useCallback)(e=>{let t=new Set(a.current.map(e=>e.id)),n=e.filter(e=>!t.has(Iw(e))).map(e=>({id:Iw(e),file:e,status:`queued`,progress:0}));n.length&&c([...a.current,...n])},[c]),d=(0,X.useCallback)(e=>{c(a.current.filter(t=>t.id!==e))},[c]),f=(0,X.useCallback)(()=>{s.current?.abort(),s.current=null,c([]),i(!1)},[c]),p=(0,X.useCallback)(()=>{s.current?.abort()},[]);return{items:t,running:r,addFiles:u,removeItem:d,reset:f,start:(0,X.useCallback)(async(e,t)=>{if(!e)throw Error(`No active workspace or context to add to`);let{workspaceName:n,treeName:r,path:u}=await xs(e),d=r===`backends`?await vs(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(Fw,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:is(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 Ss(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(Fw,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 cs(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`)&&os(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 Rw(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function zw(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 Rw(e.file.size)}}function Bw({item:e}){switch(e.status){case`done`:return(0,Z.jsx)($e,{className:`h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-500`});case`error`:return(0,Z.jsx)(ve,{className:`h-3.5 w-3.5 shrink-0 text-destructive`});case`queued`:return(0,Z.jsx)(bt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`});default:return(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground`})}}function Vw({item:e}){if(e.status===`queued`)return null;let t=e.status===`done`||e.status===`error`||e.status===`linking`?1:e.status===`checking`?0:e.progress;return(0,Z.jsx)(`div`,{className:`h-1 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:K(`h-full rounded-full transition-[width] duration-200`,e.status===`error`?`bg-destructive`:e.status===`done`?`bg-green-600 dark:bg-green-500`:`bg-primary`),style:{width:`${Math.round(t*100)}%`}})})}function Hw({items:e,running:t,onRemove:n}){let r=e.filter(e=>e.status===`done`).length,i=e.filter(e=>e.status===`error`).length;return(0,Z.jsx)(Z.Fragment,{children:e.length>0&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(Pu,{children:[e.length,` file(s)`,r>0&&(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground`,children:[`— `,r,` done`,i>0?`, ${i} failed`:``]})]}),(0,Z.jsx)(`ul`,{className:`max-h-48 space-y-1 overflow-y-auto`,children:e.map(e=>(0,Z.jsxs)(`li`,{className:`flex flex-col gap-1 rounded border border-input px-2 py-1 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Bw,{item:e}),(0,Z.jsx)(`span`,{className:`flex-1 truncate`,title:e.file.name,children:e.file.name}),(0,Z.jsx)(`span`,{className:K(`shrink-0 text-xs`,e.status===`error`?`text-destructive`:`text-muted-foreground`),title:e.status===`error`?e.error:void 0,children:zw(e)}),!t&&e.status!==`done`&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${e.file.name}`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsx)(Vw,{item:e})]},e.id))})]})})}function Uw({items:e,running:t,onCancel:n}){return(0,Z.jsxs)(`div`,{className:`space-y-4 overflow-y-auto p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-medium`,children:`Uploading files`}),!t&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:`Preparing / finishing upload…`}),(0,Z.jsx)(Hw,{items:e,running:!0,onRemove:()=>{}}),(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,disabled:!t,onClick:n,children:`Cancel upload`})]})}function Ww(e){let[t,n]=(0,X.useState)(null);return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return si(e).then(r=>{t||n({workspace:e,tags:r})}).catch(()=>{}),()=>{t=!0}},[e]),t&&t.workspace===e?t.tags:[]}var Gw=`data/schema/file`,Kw=`3.0`;function qw(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(``);return{tags:t,setTags:n,comment:r,setComment:i,suggestions:Ww(e),geotag:Ch()}}function Jw(e,t,n={}){let r=Kp(n.tags??[]),i=n.comment?.trim();return{schema:Gw,schemaVersion:Kw,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 Yw=`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 Xw({fields:e,idPrefix:t=`file`,multiple:n=!1}){return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:e.tags,onChange:e.setTags,suggestions:e.suggestions})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`${t}-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`${t}-comment`,value:e.comment,onChange:t=>e.setComment(t.target.value),rows:3,placeholder:`Optional; searchable, and the only text a photo has`,className:Yw}),n&&e.tags.length+e.comment.trim().length>0&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Applied to every file in this upload`})]}),(0,Z.jsx)(ww,{geotag:e.geotag,idPrefix:`${t}-geotag`})]})}var Zw={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 Qw(e){return/^(image|video)\//.test(e.type)}async function $w(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
|
|
@@ -23,7 +23,7 @@ Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}
|
|
|
23
23
|
`).trim():``:``}function $T(e){if(!e)return;let t=QT(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 eE(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 tE(e=[]){return e.filter(e=>e?.role===`user`||e?.role===`assistant`).map(e=>({role:e.role,content:ZT(e),timestamp:eE(e.timestamp),...e.role===`assistant`?{metadata:$T(e)}:{}})).filter(e=>e.content||e.metadata?.reasoning)}function nE(e){return{mode:e?.mode,sessionId:e?.sessionId,sessionFile:e?.sessionFile,thinkingLevel:e?.thinkingLevel,model:e?.model,messages:tE(e?.messages||[])}}function rE(e){return{current:nE(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 XT(e)}catch(e){console.warn(`WebSocket fallback not available:`,e)}}registerAgent(e){if(e.type===`anthropic`){let t=new YT(e.apiKey||``,e.endpoint||`${Rr}/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 J.stream(`${Rr}/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 J.get(`${Rr}/agents`)).agents||[]}catch(e){return console.error(`Failed to fetch available agents:`,e),[]}}async createAgent(e){let t=await J.post(`${Rr}/agents`,e);return this.registerAgent(t),t}dispose(){this.connectors.clear(),this.messageCallbacks.clear(),this.wsService&&this.wsService.disconnect()}};async function iE(e){return await J.get(`${Rr}/agents/${e}/access`)||null}async function aE(e,t){return await J.put(`${Rr}/agents/${e}/access`,t)}async function oE(e){return await J.post(`${Rr}/agents/${e}/access/token`)}async function sE(e){await J.delete(`${Rr}/agents/${e}/access`)}async function cE(e){return await J.get(`${Rr}/agents/${e}/tools`)||{tools:[],config:{}}}async function lE(){try{return await J.get(`${Rr}/agents`)||[]}catch(e){return console.error(`Failed to list agents:`,e),[]}}async function uE(e){return await J.get(`${Rr}/agents/${e}`)}async function dE(e){return nE(await J.get(`${Rr}/agents/${e}/session`))}async function fE(e){return await J.get(`${Rr}/agents/${e}/sessions`)}async function pE(e,t){return rE(await J.post(`${Rr}/agents/${e}/sessions`,t))}async function mE(e,t){return rE(await J.put(`${Rr}/agents/${e}/session`,t))}async function hE(e,t,n){return rE(await J.patch(`${Rr}/agents/${e}/sessions/${t}`,n))}async function gE(e,t){return rE(await J.delete(`${Rr}/agents/${e}/sessions/${t}`))}async function _E(e){return await J.get(`${Rr}/agents/${e}/skills`)||[]}async function vE(e,t){return await J.post(`${Rr}/agents/${e}/skills`,t)||[]}async function yE(e,t){return await J.delete(`${Rr}/agents/${e}/skills/${encodeURIComponent(t)}`)||[]}async function bE(e){return await J.post(`${Rr}/agents`,e)}async function xE(e,t){return await J.put(`${Rr}/agents/${e}`,t)}async function SE(e){await J.delete(`${Rr}/agents/${e}`)}async function CE(e){return await J.post(`${Rr}/agents/${e}/start`)}async function wE(e){return await J.post(`${Rr}/agents/${e}/stop`)}async function TE(e){return await J.get(`${Rr}/agents/${e}/status`)}async function EE(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 J.stream(`${Rr}/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(`
|
|
24
24
|
|
|
25
25
|
`);f=t.pop()||``;for(let e of t){let t=e.split(`
|
|
26
|
-
`).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||{},...$T(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function DE(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 J.post(`${Rr}/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:ZT(i),metadata:$T(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function OE(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function kE(){return await J.get(`${Rr}/voice/status`)}async function AE(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 J.post(`${Rr}/agents/${e}/voice${o}`,r)}var jE=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:VT,load:async()=>(await Xr()).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:WT,load:async()=>(await ns()).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:KT,load:async()=>(await lE()).map(e=>({id:e.id,label:e.label||e.name}))}];function ME({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(Su,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(qn,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function NE({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>_S(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(ME,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function PE(){let{state:e}=zS(),[t,n]=(0,X.useState)(``),r=hS.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>_S(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=jE.some(e=>e.sections.some(n=>_S(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)($x,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(ME,{to:e.path,...e},e.path))})]},e.id)),jE.map(e=>(0,Z.jsx)(NE,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(ME,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var FE=[{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`}],IE=`/wallpapers`;function LE(e){return FE.find(t=>t.id===e)}function RE(e,t={}){let n=typeof e==`string`?LE(e):e;if(!n)return null;let{base:r=IE,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 zE(e,t=IE){let n=typeof e==`string`?LE(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var BE=[{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`}],VE=`canvas:wallpaper`,HE=`canvas-wallpaper`,UE=`settings`,WE=`builtin:`,GE=FE;function KE(e){return zE(e)??``}function qE(e){return`${WE}${e}`}function JE(e){return e?.startsWith(WE)?e.slice(8):null}function YE(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 XE(){try{let e=localStorage.getItem(VE);if(e){let t=YE(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var ZE=XE(),QE=null;function $E(){return ZE}async function eD(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(HE,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(UE),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(UE,e?`readwrite`:`readonly`),a=i.objectStore(UE),o=e?a.put(e,VE):a.get(VE);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function tD(){try{localStorage.removeItem(VE)}catch{}}function nD(){return QE||=(async()=>{try{let e=YE(await eD());e?ZE=e:await eD(ZE),tD()}catch{}return uD(ZE),ZE})(),QE.then(()=>ZE)}async function rD(e){await nD(),await eD(e),ZE=e,tD(),uD(e)}function iD(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 aD=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function oD(e){if(!e)return null;let t=JE(e);if(t===null)return`url("${e}")`;let n=LE(t);if(!n)return null;let r=`url("${RE(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!aD||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${RE(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function sD(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var cD=null;function lD(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 uD(e=$E()){let t=document.documentElement.style,n=cD,r=e.image;if(r?.startsWith(`data:`))try{cD?.dataUrl!==r&&(cD={dataUrl:r,objectUrl:URL.createObjectURL(lD(r))}),r=cD.objectUrl}catch{cD=null,r=null}else cD=null;let i=oD(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,sD(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==cD&&URL.revokeObjectURL(n.objectUrl)}var dD=[{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.`}],fD=`canvas:treeStyle`;function pD(){try{let e=localStorage.getItem(fD);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var mD=pD(),hD=new Set;function gD(){return mD}function _D(e){try{e===`cards`?localStorage.removeItem(fD):localStorage.setItem(fD,e)}catch{}mD=e;for(let e of hD)e()}function vD(e){hD.add(e);let t=t=>{(t.key===fD||t.key===null)&&(mD=pD(),e())};return window.addEventListener(`storage`,t),()=>{hD.delete(e),window.removeEventListener(`storage`,t)}}function yD(){return(0,X.useSyncExternalStore)(vD,gD,()=>`cards`)}function bD(){let e=yD(),t=Jm();return e===`accordion`||e===`accordion-mobile`&&t}var xD=[{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)`]}],SD=xD.map(e=>e.id),CD=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],wD=[{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`}],TD={theme:`canvas`,scheme:`light`,density:`auto`},ED=`canvas.ui.theme`;function DD(e){return typeof e==`string`&&SD.includes(e)}function OD(e){return e===`light`||e===`dark`||e===`system`}function kD(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function AD(e){let t=typeof e==`object`&&e?e:{};return{theme:DD(t.theme)?t.theme:TD.theme,scheme:OD(t.scheme)?t.scheme:TD.scheme,density:kD(t.density)?t.density:TD.density}}var jD=`(prefers-color-scheme: dark)`;function MD(){return typeof document<`u`}function ND(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(jD).matches}function PD(e){return e===`system`?ND()?`dark`:`light`:e}function FD(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(jD),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function ID(e){return FD(e)}function LD(){return ND()?`dark`:`light`}function RD(){return`light`}function zD(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 BD(e,t=MD()?document.documentElement:void 0){let n=PD(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,zD(t),n):n}function VD(e,t=MD()?document.documentElement:void 0){if(!t||typeof window>`u`)return BD(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=BD(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function HD(e){let t=e??GD();if(!t)return TD;try{let e=t.getItem(ED);return e?AD(JSON.parse(e)):TD}catch{return TD}}function UD(e,t){let n=t??GD();if(n)try{n.setItem(ED,JSON.stringify(e))}catch{}}function WD(e){let t=e??GD();if(t)try{t.removeItem(ED)}catch{}}function GD(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function KD({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...HD(n),...t})),o=(0,X.useSyncExternalStore)(ID,LD,RD),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{VD({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&UD(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?LD():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{WD(n),a(TD)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(js.Provider,{value:p,children:e})}var qD={system:fe,light:Gn,dark:Pn};function JD(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Ms(),c=Im(),l=DS(),u=yD(),d=IS();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:xD.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)($e,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)($D,{options:CD.map(e=>{let t=qD[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)($D,{options:wD.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:wD.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)($D,{options:vS.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:TS}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:vS.find(e=>e.id===l)?.description}),l===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)($D,{options:OS.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:PS}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[OS.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)($D,{options:dD.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:_D}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:dD.find(e=>e.id===u)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)($D,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:Pm}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,Z.jsx)(YD,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),Pm(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function YD(){let[e,t]=(0,X.useState)($E),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=!1;return nD().then(()=>{e||(t($E()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await iD(n)}:e;await rD(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&&JE(e.image)===null,f=oD(e.image);return(0,Z.jsx)(`section`,{children:(0,Z.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,Z.jsx)(QD,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(ZD,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),GE.map(t=>(0,Z.jsx)(ZD,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:JE(e.image)===t.id,onSelect:()=>l({...e,image:qE(t.id)}),children:(0,Z.jsx)(`img`,{src:KE(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,Z.jsx)(ZD,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(XD,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:sD(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.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,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,Z.jsx)($D,{options:BE.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function XD(){let e=GE.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function ZD({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)($e,{className:`size-3`})})]})}function QD({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function $D({options:e,value:t,onChange:n}){return(0,Z.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function eO(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`Appearance`,onBack:jT(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(JD,{})]})}var tO={previousTree:`Alt+Q`,nextTree:`Alt+W`},nO=`canvas:key-bindings`,rO=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function iO(){try{let e=JSON.parse(localStorage.getItem(nO)||`{}`),t={...tO};for(let n of Object.keys(t))(e[n]===``||rO.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...tO}:t}catch{return{...tO}}}function aO(e){localStorage.setItem(nO,JSON.stringify(e))}function oO(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 sO(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function cO(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function lO(){let[e,t]=(0,X.useState)(iO),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{aO(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`Key bindings`,onBack:jT(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||tO[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||tO[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...tO}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var uO=`offline-content-v1`,dO=`offline-api-v1`,fO=1073741824,pO={enabled:!1,budgetBytes:4*fO,excludedWorkspaces:[]},mO=1e3;function hO(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function gO(e,t,n){return`${e}:${t}:${hO(n)}`}var _O=`canvas-offline`,vO=2,yO=null;function bO(){return yO||(yO=new Promise((e,t)=>{let n=indexedDB.open(_O,vO);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(),yO=null},e(n.result)},n.onerror=()=>{yO=null,t(n.error)}}),yO)}function xO(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function SO(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function CO(e,t){return SO((await bO()).transaction(e).objectStore(e).get(t))}async function wO(e){return SO((await bO()).transaction(e).objectStore(e).getAll())}async function TO(e,t,n){let r=(await bO()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),xO(r)}async function EO(e,t){let n=(await bO()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),xO(n)}async function DO(e){let t=(await bO()).transaction(e,`readwrite`);return t.objectStore(e).clear(),xO(t)}async function OO(){try{let e=await CO(`config`,`settings`);return e?{...pO,...e}:pO}catch{return pO}}async function kO(e){await TO(`config`,e,`settings`)}async function AO(e,t){let n=(await bO()).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 xO(n)}async function jO(e){let t=await wO(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-mO)),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(dO),caches.open(uO)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await EO(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await EO(`entries`,e.url)})])}async function MO(){let e=await wO(`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 NO(){await Promise.all([caches.delete(uO),caches.delete(dO)]),await DO(`entries`),await DO(`scopes`)}async function PO(){return wO(`scopes`)}async function FO(e){return CO(`scopes`,e)}async function IO(e){await TO(`scopes`,e)}async function LO(e){let t=await CO(`scopes`,e);await EO(`scopes`,e),t?.urls.length&&await RO(t.urls)}async function RO(e){let t=await wO(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await AO(r,!1)}var zO=3,BO=`data/schema/file`,VO=128;async function HO({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await OO();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=gO(e,n,t),s=hO(t),c=await FO(o),l=((await so(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===BO),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(zO,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await bi(e,t.id);d+=n.size,u.push(`${Sr.workspaces}/${e}/documents/${t.id}/content`);try{await Ii(e,t.id,VO),u.push(`${Sr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${VO}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await AO(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 IO(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await RO(t)}return g}var UO=[{label:`1 GB`,bytes:1*fO},{label:`2 GB`,bytes:2*fO},{label:`4 GB`,bytes:4*fO},{label:`8 GB`,bytes:8*fO}];function WO(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/fO).toFixed(2)} GB`}function GO(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function KO(){let{showSuccessToast:e,showErrorToast:t}=Wr(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{OO().then(r).catch(()=>{}),MO().then(a).catch(()=>{}),PO().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Xr().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await kO(e),GO(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),jO(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 NO(),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=gO(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await HO(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${WO(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${WO(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},w=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},T=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),E=async e=>{await LO(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(qO,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(C,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,Z.jsx)($e,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:UO.map(e=>(0,Z.jsx)(Y,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[WO(i.contentBytes),` of `,WO(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${WO(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,Z.jsx)(Mt,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(qO,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(Y,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(R,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,Z.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${WO(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[WO(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>S(T(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(we,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>E(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(qO,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(vt,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(Y,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(Hp,{onClose:()=>_(!1),children:(0,Z.jsx)(Bp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:w,onClose:()=>_(!1)})})]}):null}function qO({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function JO(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`Offline`,onBack:jT(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(KO,{})]})}function YO(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 XO({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function ZO(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return J.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 ${YO(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`About`,onBack:jT(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(XO,{name:`Canvas Web`,detail:`this interface`,version:`v2.20.3`}),e?.version&&(0,Z.jsx)(XO,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(XO,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var QO=[`onnx`,`clip`,`blip`,`openai`],$O=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],ek=[{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`}],tk=e=>`${Sr.workspaces}/${encodeURIComponent(e)}/inferd`;function nk(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 rk(e){return await J.get(`${tk(e)}/status`)}async function ik(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await J.post(`${tk(e)}/summarize/images`,n)}async function ak(e){return await J.post(`${tk(e)}/summarize/images/stop`,{})}async function ok(e){return await J.get(`${tk(e)}/config`)}async function sk(e,t){return await J.put(`${tk(e)}/config`,t)}async function ck(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 J.post(`${tk(e)}/reindex`,n)}async function lk(e){return await J.get(`${tk(e)}/vector-tables`)}async function uk(e,t){return await J.delete(`${tk(e)}/vector-tables/${encodeURIComponent(t)}`)}async function dk(){return await J.get(`${Sr.inferd}/config`)}async function fk(e){return await J.put(`${Sr.inferd}/config`,e)}async function pk(){return await J.get(`${Sr.inferd}/defaults`)}async function mk(e){return await J.put(`${Sr.inferd}/defaults`,e)}async function hk(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await J.post(`${Sr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function gk(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await J.post(`${Sr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var _k=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,vk=`font-semibold uppercase tracking-[0.08em]`,yk={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`}},bk=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],xk=[{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.`}],Sk=12e4;function Ck(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 wk({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,vk),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function Tk({overridden:e,source:t}){return e?(0,Z.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function Ek({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(Tk,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function Dk({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(Tk,{overridden:n})]})}function Ok({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(Tk,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,Z.jsx)(q,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(U,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function kk({open:e,onClick:t,label:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(Ge,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var Ak={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function jk({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,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?yk[i.type]?.url?.key:void 0,o=a?Ck(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await hk(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 gk(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?yk[i]?.url?.key:void 0;if(!a)continue;let o=Ck(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),L=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),R=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(nk(f,m)),h(new Set)},te=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(wk,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,Ak[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,vk),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(_e,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(kk,{open:m,onClick:()=>te(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(Tk,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:_k,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(Ek,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(Ek,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,Z.jsx)(Ek,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(Dk,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(Dk,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(U,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(wk,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=$O.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?yk[l]:void 0,d=u?.url?Ck(n[u.url.key]):null,p={...r,...n},h=bk.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(kk,{open:s,onClick:()=>te(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(Tk,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:_k,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),QO.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!QO.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(Ek,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,Z.jsx)(Ek,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(Tk,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:_k,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),xk.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:xk.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(Ek,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??Sk,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,Z.jsx)(Ok,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(U,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),ek.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:L?`default`:`outline`,onClick:R,disabled:s||!L||I.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!L,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):L?`Unsaved changes`:`Everything saved`})]})]})}function Mk(){let{showToast:e}=Vr(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>dk().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)($x,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:jT(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(we,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(we,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(jk,{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 fk(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 Nk(){let e=nl(),{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,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await J.get(e,{skipAuth:!0,headers:_()});d(t);let n=await J.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)($x,{onBack:jT(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(Y,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(td,{className:`mt-8`})]})}function Pk(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 Fk(){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 Ik={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?`${Sr.admin.users}?${n}`:Sr.admin.users;return await J.get(r)},async getUser(e){return await J.get(`${Sr.admin.users}/${e}`)},async createUser(e){return await J.post(Sr.admin.users,e)},async updateUser(e,t){return await J.put(`${Sr.admin.users}/${e}`,t)},async deleteUser(e){await J.delete(`${Sr.admin.users}/${e}`)}},Lk={async listAllWorkspaces(){return await J.get(Sr.admin.workspaces)},async createWorkspace(e){return await J.post(Sr.admin.workspaces,e)},async deleteWorkspace(e){await J.delete(`${Sr.admin.workspaces}/${e}`)}},Rk={async getLogs(e={}){return(await J.get(`${Sr.admin.logs}${Pk(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${Sr.admin.logsStream}${Pk(e)}`,{method:`GET`,headers:Fk(),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(`
|
|
26
|
+
`).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||{},...$T(t)||{}})}else e.type===`error`&&a&&a(Error(e.error||`Prompt stream failed`))}catch{}}}},onError:a,onComplete:o})}async function DE(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 J.post(`${Rr}/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:ZT(i),metadata:$T(i)};return r&&r(d.content,!0,d.metadata),a&&a(),d}catch(e){throw i&&i(e),e}}function OE(e){return e.map(e=>({...e,timestamp:typeof e.timestamp==`string`?e.timestamp:new Date().toISOString()}))}async function kE(){return await J.get(`${Rr}/voice/status`)}async function AE(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 J.post(`${Rr}/agents/${e}/voice${o}`,r)}var jE=[{id:`workspace`,label:`Workspace`,path:`workspaces`,description:`Files, search, devices and sharing for one workspace. These settings override account defaults.`,sections:VT,load:async()=>(await Xr()).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:WT,load:async()=>(await ns()).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:KT,load:async()=>(await lE()).map(e=>({id:e.id,label:e.label||e.name}))}];function ME({to:e,label:t,description:n,icon:r}){return(0,Z.jsxs)(Su,{to:e,className:`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors hover:border-primary/50 hover:bg-accent/30 focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,children:[(0,Z.jsx)(r,{className:`mt-0.5 h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-semibold`,children:t}),(0,Z.jsx)(`span`,{className:`mt-1 block text-sm leading-relaxed text-muted-foreground`,children:n})]}),(0,Z.jsx)(qn,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-primary`})]})}function NE({group:e,query:t}){let[n,r]=(0,X.useState)([]),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(`loading`),[c,l]=(0,X.useState)(0);(0,X.useEffect)(()=>{let t=!1;return e.load().then(e=>{t||(r(e),s(`ready`))}).catch(()=>{t||s(`error`)}),()=>{t=!0}},[e,c]);let u=e.sections.filter(n=>_S(t,e.label,n.label,n.description));return u.length?(0,Z.jsxs)(`section`,{id:e.id,className:`scroll-mt-6 space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`label`,{className:`block max-w-md text-sm font-medium`,children:[`Choose a `,e.label.toLowerCase(),(0,Z.jsxs)(`select`,{className:`mt-2 h-10 w-full rounded-md border bg-background px-3 text-sm`,value:i,disabled:o!==`ready`||!n.length,onChange:e=>a(e.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:o===`loading`?`Loading…`:o===`error`?`Unable to load list`:n.length?`Select ${e.label.toLowerCase()}…`:`No ${e.path} available`}),n.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),o===`error`&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`The list could not be loaded. `,(0,Z.jsx)(`button`,{type:`button`,className:`underline`,onClick:()=>{s(`loading`),l(e=>e+1)},children:`Retry`})]}),(0,Z.jsxs)(`details`,{open:!!(i||t.trim()),children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer py-2 text-sm text-muted-foreground`,children:i?`Settings for ${n.find(e=>e.id===i)?.label||i}`:`What you can configure (${u.length})`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:u.map(t=>i?(0,Z.jsx)(ME,{to:`/${e.path}/${encodeURIComponent(i)}/settings/${t.id}`,...t},t.id):(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-4`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:t.label}),(0,Z.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:t.description})]},t.id))})]})]}):null}function PE(){let{state:e}=zS(),[t,n]=(0,X.useState)(``),r=hS.filter(t=>t.id!==`server`||e.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(n=>_S(t,e.label,n.label,n.description))})).filter(e=>e.items.length),i=jE.some(e=>e.sections.some(n=>_S(t,e.label,n.label,n.description)));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-6xl space-y-8 pb-8 max-md:pb-rail-stack`,children:[(0,Z.jsx)($x,{title:`Settings`,description:`Start with what you want to change. Each section explains where your changes apply.`}),(0,Z.jsx)(q,{type:`search`,className:`max-w-xl`,"aria-label":`Search all settings`,placeholder:`Find a setting: offline, folders, models, sharing…`,value:t,onChange:e=>n(e.target.value)}),r.filter(e=>e.id===`device`||e.id===`account`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(ME,{to:e.path,...e},e.path))})]},e.id)),jE.map(e=>(0,Z.jsx)(NE,{group:e,query:t},e.id)),r.filter(e=>e.id===`server`||e.id===`information`).map(e=>(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold`,children:e.label}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.description}),(0,Z.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))] gap-3`,children:e.items.map(e=>(0,Z.jsx)(ME,{to:e.path,...e},e.path))})]},e.id)),!r.length&&!i&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm text-muted-foreground`,children:[`No settings match “`,t,`”. Try a shorter phrase or clear the search.`]})]})}var FE=[{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`}],IE=`/wallpapers`;function LE(e){return FE.find(t=>t.id===e)}function RE(e,t={}){let n=typeof e==`string`?LE(e):e;if(!n)return null;let{base:r=IE,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 zE(e,t=IE){let n=typeof e==`string`?LE(e):e;return n?`${t.replace(/\/$/,``)}/${n.thumb}`:null}var BE=[{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`}],VE=`canvas:wallpaper`,HE=`canvas-wallpaper`,UE=`settings`,WE=`builtin:`,GE=FE;function KE(e){return zE(e)??``}function qE(e){return`${WE}${e}`}function JE(e){return e?.startsWith(WE)?e.slice(8):null}function YE(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 XE(){try{let e=localStorage.getItem(VE);if(e){let t=YE(JSON.parse(e));if(t)return t}}catch{}return{image:null,fit:`cover`}}var ZE=XE(),QE=null;function $E(){return ZE}async function eD(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(HE,1),r=!1;n.onupgradeneeded=()=>n.result.createObjectStore(UE),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(UE,e?`readwrite`:`readonly`),a=i.objectStore(UE),o=e?a.put(e,VE):a.get(VE);i.oncomplete=()=>n(o.result),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}finally{t.close()}}function tD(){try{localStorage.removeItem(VE)}catch{}}function nD(){return QE||=(async()=>{try{let e=YE(await eD());e?ZE=e:await eD(ZE),tD()}catch{}return uD(ZE),ZE})(),QE.then(()=>ZE)}async function rD(e){await nD(),await eD(e),ZE=e,tD(),uD(e)}function iD(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 aD=typeof CSS<`u`&&CSS.supports(`background-image`,`image-set(url("a.avif") type("image/avif"))`);function oD(e){if(!e)return null;let t=JE(e);if(t===null)return`url("${e}")`;let n=LE(t);if(!n)return null;let r=`url("${RE(n,{types:[n.sources[n.sources.length-1].type]})}")`;return!aD||n.sources.length===1?r:`image-set(${n.sources.map(e=>`url("${RE(n,{types:[e.type]})}") type("${e.type}")`).join(`, `)})`}function sD(e){return e===`fill`?`100% 100%`:e===`center`?`auto`:`cover`}var cD=null;function lD(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 uD(e=$E()){let t=document.documentElement.style,n=cD,r=e.image;if(r?.startsWith(`data:`))try{cD?.dataUrl!==r&&(cD={dataUrl:r,objectUrl:URL.createObjectURL(lD(r))}),r=cD.objectUrl}catch{cD=null,r=null}else cD=null;let i=oD(r);i?(t.setProperty(`--wallpaper-image`,i),t.setProperty(`--wallpaper-size`,sD(e.fit))):(t.removeProperty(`--wallpaper-image`),t.removeProperty(`--wallpaper-size`)),n&&n!==cD&&URL.revokeObjectURL(n.objectUrl)}var dD=[{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.`}],fD=`canvas:treeStyle`;function pD(){try{let e=localStorage.getItem(fD);return e===`accordion`||e===`accordion-mobile`?e:`cards`}catch{return`cards`}}var mD=pD(),hD=new Set;function gD(){return mD}function _D(e){try{e===`cards`?localStorage.removeItem(fD):localStorage.setItem(fD,e)}catch{}mD=e;for(let e of hD)e()}function vD(e){hD.add(e);let t=t=>{(t.key===fD||t.key===null)&&(mD=pD(),e())};return window.addEventListener(`storage`,t),()=>{hD.delete(e),window.removeEventListener(`storage`,t)}}function yD(){return(0,X.useSyncExternalStore)(vD,gD,()=>`cards`)}function bD(){let e=yD(),t=Jm();return e===`accordion`||e===`accordion-mobile`&&t}var xD=[{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)`]}],SD=xD.map(e=>e.id),CD=[{id:`system`,name:`System`},{id:`light`,name:`Light`},{id:`dark`,name:`Dark`}],wD=[{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`}],TD={theme:`canvas`,scheme:`light`,density:`auto`},ED=`canvas.ui.theme`;function DD(e){return typeof e==`string`&&SD.includes(e)}function OD(e){return e===`light`||e===`dark`||e===`system`}function kD(e){return e===`auto`||e===`compact`||e===`comfortable`||e===`touch`}function AD(e){let t=typeof e==`object`&&e?e:{};return{theme:DD(t.theme)?t.theme:TD.theme,scheme:OD(t.scheme)?t.scheme:TD.scheme,density:kD(t.density)?t.density:TD.density}}var jD=`(prefers-color-scheme: dark)`;function MD(){return typeof document<`u`}function ND(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(jD).matches}function PD(e){return e===`system`?ND()?`dark`:`light`:e}function FD(e){if(typeof window>`u`||typeof window.matchMedia!=`function`)return()=>{};let t=window.matchMedia(jD),n=t=>e(t.matches?`dark`:`light`);return t.addEventListener(`change`,n),()=>t.removeEventListener(`change`,n)}function ID(e){return FD(e)}function LD(){return ND()?`dark`:`light`}function RD(){return`light`}function zD(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 BD(e,t=MD()?document.documentElement:void 0){let n=PD(e.scheme);return t?(t.dataset.theme=e.theme,t.dataset.scheme=n,t.dataset.density=e.density,zD(t),n):n}function VD(e,t=MD()?document.documentElement:void 0){if(!t||typeof window>`u`)return BD(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=BD(e,t);return window.getComputedStyle(n).opacity,document.head.removeChild(n),r}function HD(e){let t=e??GD();if(!t)return TD;try{let e=t.getItem(ED);return e?AD(JSON.parse(e)):TD}catch{return TD}}function UD(e,t){let n=t??GD();if(n)try{n.setItem(ED,JSON.stringify(e))}catch{}}function WD(e){let t=e??GD();if(t)try{t.removeItem(ED)}catch{}}function GD(){try{return typeof localStorage<`u`?localStorage:void 0}catch{return}}function KD({children:e,initial:t,storage:n,persist:r=!0}){let[i,a]=(0,X.useState)(()=>({...HD(n),...t})),o=(0,X.useSyncExternalStore)(ID,LD,RD),s=i.scheme===`system`?o:i.scheme;(0,X.useEffect)(()=>{VD({...i,scheme:s})},[i,s]),(0,X.useEffect)(()=>{r&&UD(i,n)},[i,r,n]);let c=(0,X.useCallback)(e=>{a(t=>t.theme===e?t:{...t,theme:e})},[]),l=(0,X.useCallback)(e=>{a(t=>t.scheme===e?t:{...t,scheme:e})},[]),u=(0,X.useCallback)(e=>{a(t=>t.density===e?t:{...t,density:e})},[]),d=(0,X.useCallback)(()=>{a(e=>({...e,scheme:(e.scheme===`system`?LD():e.scheme)===`dark`?`light`:`dark`}))},[]),f=(0,X.useCallback)(()=>{WD(n),a(TD)},[n]),p=(0,X.useMemo)(()=>({...i,resolvedScheme:s,setTheme:c,setScheme:l,setDensity:u,toggleScheme:d,reset:f}),[i,s,c,l,u,d,f]);return(0,Z.jsx)(js.Provider,{value:p,children:e})}var qD={system:fe,light:Gn,dark:Pn};function JD(){let{theme:e,scheme:t,density:n,resolvedScheme:r,setTheme:i,setScheme:a,setDensity:o,reset:s}=Ms(),c=Im(),l=DS(),u=yD(),d=IS();return(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Theme`,description:`Palette, shape and typography. Each theme defines its own light and dark variants.`}),(0,Z.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:xD.map(t=>{let n=t.id===e;return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>i(t.id),"aria-pressed":n,className:K(`focus-ring group flex flex-col gap-3 rounded-lg border p-4 text-left transition-colors`,n?`border-primary bg-accent`:`border-border hover:border-muted-foreground/40 hover:bg-accent/50`),children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:t.name}),n&&(0,Z.jsx)($e,{className:`size-4 shrink-0 text-primary`})]}),(0,Z.jsx)(`div`,{className:`flex gap-1.5`,"aria-hidden":!0,children:t.swatches.map(e=>(0,Z.jsx)(`span`,{className:`size-6 rounded-full border border-border`,style:{backgroundColor:e}},e))}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t.description})]},t.id)})})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Colour scheme`,description:t===`system`?`Following your system setting, currently ${r}.`:`Overrides your system setting.`}),(0,Z.jsx)($D,{options:CD.map(e=>{let t=qD[e.id];return{id:e.id,label:e.name,icon:(0,Z.jsx)(t,{className:`size-4 shrink-0`})}}),value:t,onChange:a})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Density`,description:`Controls row height, hit-target size and shell spacing across the whole app.`}),(0,Z.jsx)($D,{options:wD.map(e=>({id:e.id,label:e.name,title:e.description})),value:n,onChange:o}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:wD.find(e=>e.id===n)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Layout`,description:`How menus and content share the screen. Device-local, like the wallpaper.`}),(0,Z.jsx)($D,{options:vS.map(e=>({id:e.id,label:e.name,title:e.description})),value:l,onChange:TS}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:vS.find(e=>e.id===l)?.description}),l===`strip`&&(0,Z.jsxs)(`div`,{className:`mt-4`,children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Navigation keys`}),(0,Z.jsx)($D,{options:OS.map(e=>({id:e.id,label:e.name,title:e.description})),value:d,onChange:PS}),(0,Z.jsxs)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:[OS.find(e=>e.id===d)?.description,` `,`Left and right walk the columns, up and down switch pin rows.`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Tree style`,description:`How workspace and context trees are drawn in the menu. Device-local.`}),(0,Z.jsx)($D,{options:dD.map(e=>({id:e.id,label:e.name,title:e.description})),value:u,onChange:_D}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:dD.find(e=>e.id===u)?.description})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(QD,{title:`Open documents`,description:`Choose how documents open from lists, tiles and boards. Saved on this device.`}),(0,Z.jsx)($D,{options:[{id:`modal`,label:`Modal`},{id:`side`,label:`Side reading pane`}],value:c,onChange:Pm}),(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`The reading pane opens beside the content and updates as you select another document. On small screens it opens as a drawer.`})]}),(0,Z.jsx)(YD,{}),(0,Z.jsx)(`section`,{children:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{s(),Pm(`modal`)},className:`focus-ring rounded-md text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline`,children:`Reset to defaults`})})]})}function YD(){let[e,t]=(0,X.useState)($E),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(!0),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=!1;return nD().then(()=>{e||(t($E()),a(!1))}),()=>{e=!0}},[]);let l=async(e,n)=>{if(!c.current){c.current=!0,s(!0);try{let i=n?{...e,image:await iD(n)}:e;await rD(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&&JE(e.image)===null,f=oD(e.image);return(0,Z.jsx)(`section`,{children:(0,Z.jsxs)(`fieldset`,{disabled:i||o,className:`min-w-0`,children:[(0,Z.jsx)(QD,{title:`Wallpaper`,description:`Background image for the desk behind all panels. Without one, the theme's desk color shows (the default).`}),(0,Z.jsxs)(`div`,{role:`radiogroup`,"aria-label":`Wallpaper`,className:`grid grid-cols-3 gap-3 sm:grid-cols-4 lg:grid-cols-6`,children:[(0,Z.jsx)(ZD,{label:`None`,isActive:e.image===null,onSelect:()=>l({...e,image:null}),children:(0,Z.jsx)(`span`,{className:`flex size-full items-center justify-center surface-desk text-xs text-muted-foreground`,style:{backgroundImage:`none`},children:`None`})}),GE.map(t=>(0,Z.jsx)(ZD,{label:t.title,title:`${t.title} — suits the ${t.scheme} scheme`,isActive:JE(e.image)===t.id,onSelect:()=>l({...e,image:qE(t.id)}),children:(0,Z.jsx)(`img`,{src:KE(t),alt:``,loading:`lazy`,className:`size-full object-cover`,style:{backgroundColor:t.background}})},t.id)),d&&(0,Z.jsx)(ZD,{label:`Your image`,isActive:!0,onSelect:()=>{},children:(0,Z.jsx)(`img`,{src:e.image??void 0,alt:``,className:`size-full object-cover`})})]}),(0,Z.jsx)(XD,{}),(0,Z.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`div`,{className:`h-20 w-32 shrink-0 rounded-md border surface-desk`,style:f?{backgroundImage:f,backgroundSize:sD(e.fit),backgroundPosition:`center`,backgroundRepeat:`no-repeat`}:void 0,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Z.jsxs)(`label`,{className:`focus-ring inline-flex cursor-pointer items-center rounded-md border px-3 py-1.5 text-sm hover:bg-accent/50`,children:[d?`Change image…`:`Use your own image…`,(0,Z.jsx)(`input`,{type:`file`,accept:`image/*,.gif`,className:`hidden`,onChange:e=>{u(e.target.files?.[0]),e.target.value=``}})]}),e.image&&(0,Z.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,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Images and animated GIFs up to 10 MB. Stored on this device.`}),(0,Z.jsx)($D,{options:BE.map(e=>({id:e.id,label:e.label,title:e.description})),value:e.fit,onChange:t=>l({...e,fit:t})}),n&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:n}),o&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-muted-foreground`,children:`Saving wallpaper…`})]})]})]})})}function XD(){let e=GE.filter(e=>e.author!==`Canvas`);return e.length===0?null:(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:e.map((e,t)=>(0,Z.jsxs)(`span`,{children:[t>0&&` · `,e.title,` © `,e.author,e.source&&(0,Z.jsxs)(Z.Fragment,{children:[` `,(0,Z.jsx)(`a`,{href:e.source,target:`_blank`,rel:`noreferrer noopener`,className:`focus-ring underline underline-offset-2 hover:text-foreground`,children:new URL(e.source).hostname})]})]},e.id))})}function ZD({label:e,title:t,isActive:n,onSelect:r,children:i}){return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":n,"aria-label":e,title:t??e,onClick:r,className:K(`focus-ring group relative aspect-video overflow-hidden rounded-md border transition-colors`,n?`border-primary ring-1 ring-primary`:`border-border hover:border-muted-foreground/40`),children:[i,n&&(0,Z.jsx)(`span`,{className:`absolute right-1 top-1 rounded-full bg-primary p-0.5 text-primary-foreground`,children:(0,Z.jsx)($e,{className:`size-3`})})]})}function QD({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function $D({options:e,value:t,onChange:n}){return(0,Z.jsx)(`div`,{role:`radiogroup`,className:`inline-flex flex-wrap gap-1 rounded-lg bg-muted p-1`,children:e.map(e=>{let r=e.id===t;return(0,Z.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":r,title:e.title,onClick:()=>n(e.id),className:K(`focus-ring flex h-control items-center gap-2 rounded-md px-3 text-sm transition-colors`,r?`bg-card text-foreground shadow-elevation-1`:`text-muted-foreground hover:text-foreground`),children:[e.icon,e.label]},e.id)})})}function eO(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`Appearance`,onBack:jT(),description:`Theme, colour scheme and density. Changes apply immediately and are remembered on this device.`}),(0,Z.jsx)(JD,{})]})}var tO={previousTree:`Alt+Q`,nextTree:`Alt+W`},nO=`canvas:key-bindings`,rO=/^(Alt|Alt\+Shift|Ctrl\+Shift|Meta\+Shift)\+[A-Z]$/;function iO(){try{let e=JSON.parse(localStorage.getItem(nO)||`{}`),t={...tO};for(let n of Object.keys(t))(e[n]===``||rO.test(e[n]))&&(t[n]=e[n]);return t.previousTree&&t.previousTree===t.nextTree?{...tO}:t}catch{return{...tO}}}function aO(e){localStorage.setItem(nO,JSON.stringify(e))}function oO(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 sO(e,t,n){return e[(Math.max(0,e.indexOf(t))+n+e.length)%e.length]}function cO(e,t){return Math.abs(e)>=48&&Math.abs(e)>Math.abs(t)*1.5?e<0?1:-1:0}function lO(){let[e,t]=(0,X.useState)(iO),[n,r]=(0,X.useState)(``),i=e=>{if(e.previousTree&&e.previousTree===e.nextTree){r(`Choose a different shortcut: that combination is already assigned.`);return}try{aO(e),t(e),r(`Saved on this device.`)}catch{r(`Could not save shortcuts in this browser.`)}};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`Key bindings`,onBack:jT(),description:`Web UI shortcuts, saved on this device and available offline.`}),(0,Z.jsxs)(`section`,{className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`font-medium`,children:`Tree navigation`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Cycle the open workspace menu’s tabs in their displayed order, including Pins and Layers. Swipe left for next or right for previous over the tab bar. Shortcuts pause while typing or using a dialog.`}),[`previousTree`,`nextTree`].map(t=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Z.jsx)(`label`,{htmlFor:t,className:`min-w-32 text-sm`,children:t===`previousTree`?`Previous tree`:`Next tree`}),(0,Z.jsxs)(`select`,{id:t,className:`rounded-md border bg-background p-2 text-sm`,value:e[t].split(`+`).slice(0,-1).join(`+`),onChange:n=>i({...e,[t]:n.target.value?`${n.target.value}+${e[t].slice(-1)||tO[t].slice(-1)}`:``}),children:[(0,Z.jsx)(`option`,{value:``,children:`Disabled`}),[`Alt`,`Alt+Shift`,`Ctrl+Shift`,`Meta+Shift`].map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]}),(0,Z.jsx)(`select`,{"aria-label":`${t===`previousTree`?`Previous`:`Next`} tree key`,disabled:!e[t],className:`rounded-md border bg-background p-2 text-sm disabled:opacity-50`,value:e[t].slice(-1)||tO[t].slice(-1),onChange:n=>i({...e,[t]:`${e[t].split(`+`).slice(0,-1).join(`+`)}+${n.target.value}`}),children:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`.split(``).map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))})]},t)),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Browsers and operating systems may reserve combinations. Choose another if a shortcut does not reach Canvas. Letters refer to physical keyboard positions (Q/W on a US keyboard); Meta is Command on Mac.`}),(0,Z.jsx)(`button`,{type:`button`,className:`rounded-md border px-3 py-2 text-sm hover:bg-accent`,onClick:()=>i({...tO}),children:`Restore defaults`}),(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:n})]})]})}var uO=`offline-content-v1`,dO=`offline-api-v1`,fO=1073741824,pO={enabled:!1,budgetBytes:4*fO,excludedWorkspaces:[]},mO=1e3;function hO(e){return(e.startsWith(`/`)?e:`/${e}`).replace(/\/+$/,``)||`/`}function gO(e,t,n){return`${e}:${t}:${hO(n)}`}var _O=`canvas-offline`,vO=2,yO=null;function bO(){return yO||(yO=new Promise((e,t)=>{let n=indexedDB.open(_O,vO);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(),yO=null},e(n.result)},n.onerror=()=>{yO=null,t(n.error)}}),yO)}function xO(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function SO(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}async function CO(e,t){return SO((await bO()).transaction(e).objectStore(e).get(t))}async function wO(e){return SO((await bO()).transaction(e).objectStore(e).getAll())}async function TO(e,t,n){let r=(await bO()).transaction(e,`readwrite`);return r.objectStore(e).put(t,n),xO(r)}async function EO(e,t){let n=(await bO()).transaction(e,`readwrite`);return n.objectStore(e).delete(t),xO(n)}async function DO(e){let t=(await bO()).transaction(e,`readwrite`);return t.objectStore(e).clear(),xO(t)}async function OO(){try{let e=await CO(`config`,`settings`);return e?{...pO,...e}:pO}catch{return pO}}async function kO(e){await TO(`config`,e,`settings`)}async function AO(e,t){let n=(await bO()).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 xO(n)}async function jO(e){let t=await wO(`entries`),n=t.filter(e=>e.kind===`api`).sort((e,t)=>e.lastAccess-t.lastAccess),r=n.slice(0,Math.max(0,n.length-mO)),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(dO),caches.open(uO)]);await Promise.all([...r.map(async e=>{await c.delete(e.url),await EO(`entries`,e.url)}),...s.map(async e=>{await l.delete(e.url),await EO(`entries`,e.url)})])}async function MO(){let e=await wO(`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 NO(){await Promise.all([caches.delete(uO),caches.delete(dO)]),await DO(`entries`),await DO(`scopes`)}async function PO(){return wO(`scopes`)}async function FO(e){return CO(`scopes`,e)}async function IO(e){await TO(`scopes`,e)}async function LO(e){let t=await CO(`scopes`,e);await EO(`scopes`,e),t?.urls.length&&await RO(t.urls)}async function RO(e){let t=await wO(`scopes`),n=new Set(t.flatMap(e=>e.urls)),r=e.filter(e=>!n.has(e));r.length&&await AO(r,!1)}var zO=3,BO=`data/schema/file`,VO=128;async function HO({workspaceRef:e,path:t,treeName:n,treeType:r},i){let a=await OO();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=gO(e,n,t),s=hO(t),c=await FO(o),l=((await so(e,s,[],{limit:1e4,treeName:n,treeType:r})).payload??[]).filter(e=>e.schema===BO),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(zO,l.length)},async()=>{for(;h<l.length;){let t=l[h++];if(d>=a.budgetBytes*.9){p=!0;return}try{let{blob:n}=await bi(e,t.id);d+=n.size,u.push(`${Sr.workspaces}/${e}/documents/${t.id}/content`);try{await Ii(e,t.id,VO),u.push(`${Sr.workspaces}/${e}/documents/${t.id}/thumbnail?size=${VO}`)}catch{}}catch{}f+=1,i?.({done:f,total:m,bytes:d})}})),await AO(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 IO(g),c){let e=new Set(u),t=c.urls.filter(t=>!e.has(t));t.length&&await RO(t)}return g}var UO=[{label:`1 GB`,bytes:1*fO},{label:`2 GB`,bytes:2*fO},{label:`4 GB`,bytes:4*fO},{label:`8 GB`,bytes:8*fO}];function WO(e){return e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/fO).toFixed(2)} GB`}function GO(){navigator.serviceWorker?.controller?.postMessage({type:`OFFLINE_SETTINGS_CHANGED`})}function KO(){let{showSuccessToast:e,showErrorToast:t}=Wr(),[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)([]),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)({}),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!1),v=(0,X.useCallback)(()=>{OO().then(r).catch(()=>{}),MO().then(a).catch(()=>{}),PO().then(e=>d(e.sort((e,t)=>e.id.localeCompare(t.id)))).catch(()=>{}),navigator.storage?.persisted?.().then(s).catch(()=>{})},[]);(0,X.useEffect)(()=>{v(),Xr().then(e=>l(e.map(e=>e.name).filter(Boolean).sort())).catch(()=>{})},[v]);let y=async e=>{r(e),await kO(e),GO(),e.enabled&&navigator.storage?.persist?.().then(s).catch(()=>{}),jO(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 NO(),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=gO(n.workspaceRef,n.treeName,n.path);p(e=>({...e,[r]:{done:0,total:0,bytes:0}}));try{let t=await HO(n,e=>p(t=>({...t,[r]:e})));e(t.truncated?`Pinned ${WO(t.bytes)} — stopped at the size budget`:`Pinned ${t.workspaceRef}:/${t.path} (${WO(t.bytes)})`)}catch(e){t(e instanceof Error?e.message:`Failed to pin`)}finally{p(e=>{let{[r]:t,...n}=e;return n}),v()}},w=(e,t)=>{_(!1);for(let n of e)S({workspaceRef:t.workspaceName,path:n,treeName:t.treeName,treeType:t.treeType})},T=e=>({workspaceRef:e.workspaceRef,path:e.path,treeName:e.treeName||`context`,treeType:e.treeType||`context`}),E=async e=>{await LO(e),v()};return n?(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(qO,{title:`Offline cache`,description:`Keep documents you open (and scopes you pin) readable without a connection. Cached on this device only; least-recently-used files are evicted when the size budget fills. Video streaming is not cached.`}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>y({...n,enabled:!n.enabled}),"aria-pressed":n.enabled,className:K(`focus-ring flex items-center gap-3 rounded-lg border p-4 text-left transition-colors`,n.enabled?`border-primary bg-accent`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(C,{className:`h-5 w-5 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:n.enabled?`Enabled`:`Disabled`}),(0,Z.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:n.enabled?o===!1?`Storage is not persistent — the browser may still evict the cache under disk pressure`:`Documents are cached as you browse`:`Nothing is cached for offline use`})]}),n.enabled&&(0,Z.jsx)($e,{className:`h-4 w-4 shrink-0 text-primary`})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:`Size budget`}),(0,Z.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:UO.map(e=>(0,Z.jsx)(Y,{variant:n.budgetBytes===e.bytes?`default`:`outline`,size:`sm`,onClick:()=>y({...n,budgetBytes:e.bytes}),children:e.label},e.bytes))})]}),i&&(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between text-sm`,children:[(0,Z.jsxs)(`span`,{children:[WO(i.contentBytes),` of `,WO(n.budgetBytes),` used`]}),(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.contentCount,` file(s)`,i.pinnedBytes>0?`, ${WO(i.pinnedBytes)} pinned`:``]})]}),(0,Z.jsx)(`div`,{className:`h-2 w-full overflow-hidden rounded-full bg-muted`,children:(0,Z.jsx)(`div`,{className:`h-full rounded-full bg-primary`,style:{width:`${Math.min(100,i.contentBytes/n.budgetBytes*100)}%`}})})]}),(0,Z.jsx)(`div`,{children:(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,onClick:x,disabled:m,children:[m?(0,Z.jsx)(Mt,{className:`mr-1.5 h-3.5 w-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`mr-1.5 h-3.5 w-3.5`}),`Clear offline cache`]})})]})]})]}),n.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(qO,{title:`Pinned scopes`,description:`A pinned scope — a workspace, or one of its tree paths — is downloaded up front and never evicted. Scopes resolve fresh on every re-warm, so moved contexts and reorganized trees are picked up; documents that left a scope return to normal eviction.`}),(0,Z.jsx)(`div`,{className:`mb-3`,children:(0,Z.jsxs)(Y,{size:`sm`,onClick:()=>_(!0),disabled:!!Object.keys(f).length,children:[(0,Z.jsx)(R,{className:`mr-1.5 h-3.5 w-3.5`}),`Pin a path…`]})}),(0,Z.jsxs)(`ul`,{className:`space-y-1`,children:[u.map(e=>{let t=f[e.id];return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsxs)(`span`,{className:`flex-1 truncate font-mono text-xs sm:text-sm`,children:[e.workspaceRef,`://`,e.path.replace(/^\//,``),e.treeName&&e.treeName!==`context`&&(0,Z.jsx)(`span`,{className:`ml-1.5 rounded bg-muted px-1 py-0.5 font-sans text-[10px] text-muted-foreground`,children:e.treeName})]}),t?(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 animate-spin`}),t.total>0?`${t.done}/${t.total} · ${WO(t.bytes)}`:`listing…`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[WO(e.bytes),e.truncated?` (partial)`:``]}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>S(T(e)),"aria-label":`Re-warm ${e.id}`,title:`Re-warm: re-resolve the scope and download anything new`,children:(0,Z.jsx)(we,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{variant:`ghost`,size:`sm`,onClick:()=>E(e.id),"aria-label":`Unpin ${e.id}`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]})]},e.id)}),u.length===0&&(0,Z.jsx)(`li`,{className:`rounded-md border border-dashed border-input px-3 py-4 text-center text-sm text-muted-foreground`,children:`Nothing pinned — everything relies on browse-caching and LRU`})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(qO,{title:`Workspace caching`,description:`Excluded workspaces are never cached — not even as you browse — and are not served from cache.`}),(0,Z.jsx)(`ul`,{className:`space-y-1`,children:c.map(e=>{let t=n.excludedWorkspaces.includes(e);return(0,Z.jsxs)(`li`,{className:`flex items-center gap-3 rounded-md border border-input px-3 py-2 text-sm`,children:[(0,Z.jsx)(`span`,{className:K(`flex-1 truncate`,t&&`text-muted-foreground line-through`),children:e}),t&&(0,Z.jsx)(vt,{className:`h-3.5 w-3.5 text-muted-foreground`}),(0,Z.jsx)(Y,{variant:t?`outline`:`ghost`,size:`sm`,onClick:()=>b(e),children:t?`Include`:`Exclude`})]},e)})})]})]}),g&&(0,Z.jsx)(Hp,{onClose:()=>_(!1),children:(0,Z.jsx)(Bp,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:[`context`,`directory`],title:`Pin for offline…`,confirmLabel:`Pin path`,onConfirm:w,onClose:()=>_(!1)})})]}):null}function qO({title:e,description:t}){return(0,Z.jsxs)(`div`,{className:`mb-4`,children:[(0,Z.jsx)(`h2`,{className:`text-base font-semibold`,children:e}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t})]})}function JO(){return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`Offline`,onBack:jT(),description:`Per-device offline cache: browse notes, files, photos and saved websites without a connection.`}),(0,Z.jsx)(KO,{})]})}function YO(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 XO({name:e,version:t,detail:n}){return(0,Z.jsxs)(`div`,{className:`flex items-baseline justify-between gap-4 px-4 py-2.5`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:e}),n&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate`,children:n})]}),(0,Z.jsx)(`code`,{className:`text-xs text-muted-foreground shrink-0`,children:t})]})}function ZO(){let[e,t]=(0,X.useState)(null),[n,r]=(0,X.useState)(null);(0,X.useEffect)(()=>{let e=!0;return J.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 ${YO(e.uptime)}`:null].filter(Boolean).join(` · `),a=Object.entries(e?.components??{}).sort(([e],[t])=>e.localeCompare(t));return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl`,children:[(0,Z.jsx)($x,{className:`mb-6`,title:`About`,onBack:jT(),description:`Versions of every Canvas component this installation is running.`}),(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`section`,{className:`rounded-md border border-border divide-y divide-border`,children:[(0,Z.jsx)(XO,{name:`Canvas Web`,detail:`this interface`,version:`v2.20.4`}),e?.version&&(0,Z.jsx)(XO,{name:e.productName||e.appName||`Canvas Server`,detail:i||void 0,version:`v${e.version}`})]}),a.length>0&&(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(`h2`,{className:`mb-2 px-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:`Server components`}),(0,Z.jsx)(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(([e,t])=>(0,Z.jsx)(XO,{name:e,version:`v${t}`},e))})]}),n&&(0,Z.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Server details unavailable: `,n]}),e?.sourceUrl&&(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[e.license?`Licensed ${e.license}. `:``,(0,Z.jsx)(`a`,{href:e.sourceUrl,target:`_blank`,rel:`noreferrer`,className:`underline underline-offset-2 hover:text-foreground`,children:`Get the source code`}),`.`]})]})]})}var QO=[`onnx`,`clip`,`blip`,`openai`],$O=[`onnx`,`clip`,`blip`,`ollama`,`vllm`],ek=[{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`}],tk=e=>`${Sr.workspaces}/${encodeURIComponent(e)}/inferd`;function nk(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 rk(e){return await J.get(`${tk(e)}/status`)}async function ik(e,t={}){let n={};return t.force!==void 0&&(n.force=t.force),await J.post(`${tk(e)}/summarize/images`,n)}async function ak(e){return await J.post(`${tk(e)}/summarize/images/stop`,{})}async function ok(e){return await J.get(`${tk(e)}/config`)}async function sk(e,t){return await J.put(`${tk(e)}/config`,t)}async function ck(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 J.post(`${tk(e)}/reindex`,n)}async function lk(e){return await J.get(`${tk(e)}/vector-tables`)}async function uk(e,t){return await J.delete(`${tk(e)}/vector-tables/${encodeURIComponent(t)}`)}async function dk(){return await J.get(`${Sr.inferd}/config`)}async function fk(e){return await J.put(`${Sr.inferd}/config`,e)}async function pk(){return await J.get(`${Sr.inferd}/defaults`)}async function mk(e){return await J.put(`${Sr.inferd}/defaults`,e)}async function hk(e,t){let n={...e};return delete n.apiKeySet,delete n.headerNames,(await J.post(`${Sr.inferd}/test`,{provider:n,...t?{model:t}:{},probe:!0})).cached??null}async function gk(e,t,n=`text`){let r={...e};return delete r.apiKeySet,delete r.headerNames,await J.post(`${Sr.inferd}/test`,{provider:r,...t?{model:t}:{},modality:n})}var _k=`h-8 w-full rounded-md border bg-background px-2 text-sm outline-none focus:ring-2 focus:ring-ring`,vk=`font-semibold uppercase tracking-[0.08em]`,yk={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`}},bk=[`baseUrl`,`host`,`apiKey`,`cacheDir`,`imageInput`,`timeoutMs`],xk=[{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.`}],Sk=12e4;function Ck(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 wk({title:e,hint:t}){return(0,Z.jsxs)(`div`,{className:`mb-2`,children:[(0,Z.jsx)(`h3`,{className:K(`text-[11px] text-muted-foreground`,vk),children:e}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:t})]})}function Tk({overridden:e,source:t}){return e?(0,Z.jsx)(`span`,{className:`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,title:`Set on this layer; it wins over anything inherited`,children:`overridden`}):(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground`,title:t?`Inherited: ${t}`:`Inherited from a lower config layer`,children:`inherited`})}function Ek({label:e,value:t,inheritedValue:n,onChange:r,type:i=`text`,placeholder:a,disabled:o,hint:s,error:c,mono:l}){let u=t!==void 0&&t!==``;return(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:e}),(0,Z.jsx)(Tk,{overridden:u,source:n===void 0?void 0:String(n)}),u&&!o&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(``),className:`text-[10px] text-muted-foreground underline hover:text-foreground`,title:`Clear the override and fall back to the inherited value`,children:`reset`})]}),(0,Z.jsx)(q,{type:i,value:t??``,disabled:o,onChange:e=>r(e.target.value),placeholder:a??(n===void 0?`—`:String(n)),className:K(`h-8 text-sm`,l&&`font-mono`,c&&`border-destructive focus-visible:ring-destructive`)}),c&&(0,Z.jsx)(`p`,{className:`text-[11px] font-medium text-destructive`,children:c}),s&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:s})]})}function Dk({label:e,checked:t,overridden:n,disabled:r,onChange:i}){return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,disabled:r,checked:t,onChange:e=>i(e.target.checked)}),e,(0,Z.jsx)(Tk,{overridden:n})]})}function Ok({storedNames:e,value:t,disabled:n,onChange:r}){let i=t!==void 0,[a,o]=(0,X.useState)([]),s=e=>{o(e),r(Object.fromEntries(e.filter(([e])=>e.trim()!==``)))};return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Custom headers`}),i?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will replace stored`}),!n&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{o([]),r(void 0)},className:`text-[10px] text-muted-foreground underline hover:text-foreground`,children:`cancel`})]}):(0,Z.jsx)(Tk,{overridden:!1,source:e?.join(`, `)})]}),!i&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:e?.length?(0,Z.jsxs)(Z.Fragment,{children:[`Stored: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:e.join(`, `)}),` (values are never sent back)`]}):`None set.`}),!n&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>{o([[``,``]]),r({})},children:e?.length?`Replace headers`:`Add headers`})]}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Saving replaces every stored header, so re-enter the ones you want to keep.`}),a.map(([e,t],r)=>(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:e,disabled:n,placeholder:`X-Tenant`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[e.target.value,t[1]]:t))}),(0,Z.jsx)(q,{value:t,disabled:n,placeholder:`value`,className:`h-8 font-mono text-sm`,onChange:e=>s(a.map((t,n)=>n===r?[t[0],e.target.value]:t))}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,"aria-label":`Remove header ${e||r+1}`,onClick:()=>s(a.filter((e,t)=>t!==r)),children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]},r)),!n&&(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>s([...a,[``,``]]),children:[(0,Z.jsx)(U,{className:`mr-1.5 h-3.5 w-3.5`}),`Add header`]})]})]})}function kk({open:e,onClick:t,label:n}){return(0,Z.jsx)(`button`,{type:`button`,onClick:t,"aria-expanded":e,title:n,"aria-label":n,className:`flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground`,children:(0,Z.jsx)(Ge,{className:K(`h-4 w-4 transition-transform motion-reduce:transition-none`,e&&`rotate-180`)})})}var Ak={configured:`bg-success`,"needs-fill":`bg-warning`,unresolved:`bg-destructive`,unset:`bg-muted-foreground/30`};function jk({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,X.useState)(()=>structuredClone(e)),[m,h]=(0,X.useState)(new Set),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),E=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.spaces||{}),...Object.keys(f.spaces||{})])].sort(),[t.spaces,f.spaces]),D=(0,X.useMemo)(()=>[...new Set([...Object.keys(t.providers||{}),...Object.keys(f.providers||{})])].sort(),[t.providers,f.providers]),O=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`dim`||t===`maxLength`||t===`dimensions`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},k=(e,t,n)=>{p(r=>{let i={...r.spaces||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,spaces:i}})},A=(e,t,n)=>{t===`apiKey`&&h(t=>{let r=new Set(t);return n===``?r.delete(e):r.add(e),r}),p(r=>{let i={...r.providers||{}},a={...i[e]||{}};if(n===``)delete a[t];else if(t===`timeoutMs`){let e=Number(n);if(Number.isNaN(e))return r;a[t]=e}else a[t]=n;return Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},j=(e,t,n)=>{p(r=>{let i={...r.providers||{}},a={...i[e]||{}};return n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,{...r,providers:i}})},M=e=>{p(t=>{let n={...t.providers||{}};return delete n[e],{...t,providers:n}}),h(t=>{let n=new Set(t);return n.delete(e),n})},N=()=>{let e=S.trim();if(e){if(E.includes(e)){d({title:`Space exists`,description:`'${e}' already has a row below.`,variant:`destructive`});return}p(t=>({...t,spaces:{...t.spaces||{},[e]:{}}})),C(``),T(`space:${e}`)}},P=(e,t)=>{if(e){if(D.includes(e)){d({title:`Backend exists`,description:`'${e}' is already declared. Open it below to edit.`,variant:`destructive`});return}p(n=>({...n,providers:{...n.providers||{},[e]:{type:`openai`,...t?{baseUrl:t}:{}}}})),x(``),T(`provider:${e}`)}},ee=e=>({...t.providers?.[e]||{},...f.providers?.[e]||{}}),F=async e=>{let n=f.spaces?.[e]?.provider??t.spaces?.[e]?.provider,r=f.spaces?.[e]?.model??t.spaces?.[e]?.model;if(!n){d({title:`No backend`,description:`Space '${e}' has no backend to test.`,variant:`destructive`});return}let i=ee(n),a=i.type?yk[i.type]?.url?.key:void 0,o=a?Ck(i[a]):null;if(o){d({title:`Backend '${n}'`,description:o,variant:`destructive`});return}_(e);try{try{await hk(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 gk(i,r,e),a=f.spaces?.[e]?.dim??t.spaces?.[e]?.dim,o=n.dim>0&&a!==void 0&&n.dim!==a;(o||n.dim>0&&a===void 0)&&O(e,`dim`,String(n.dim)),d({title:o?`Backend answered; dimensions corrected`:`Backend answered`,description:o?`Returned ${n.dim}-d but '${e}' was set to ${a}-d. Dimensions updated to ${n.dim}; save to apply. (${n.latencyMs} ms)`:`${n.dim}-d in ${n.latencyMs} ms`})}catch(e){d({title:`Test failed`,description:e instanceof Error?e.message:`Backend unreachable`,variant:`destructive`})}finally{_(null),y(!1)}},I=(0,X.useMemo)(()=>{let e=[];for(let[n,r]of Object.entries(f.providers||{})){let i=r.type??t.providers?.[n]?.type,a=i?yk[i]?.url?.key:void 0;if(!a)continue;let o=Ck(r[a]);o&&e.push(`${n}: ${o}`)}return e},[f.providers,t.providers]),L=(0,X.useMemo)(()=>JSON.stringify(f)!==JSON.stringify(e)||m.size>0,[f,e,m]),R=async()=>{if(I.length>0){d({title:`Fix the endpoint first`,description:I.join(` · `),variant:`destructive`});return}await u(nk(f,m)),h(new Set)},te=e=>T(t=>t===e?null:e);return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[i&&(0,Z.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive-subtle p-3 text-xs`,children:[(0,Z.jsx)(at,{className:`mt-0.5 h-4 w-4 shrink-0 text-destructive`}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Stored config does not resolve; defaults are standing in`}),(0,Z.jsx)(`p`,{className:`mt-0.5 font-mono text-[11px] text-muted-foreground`,children:i})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(wk,{title:`Search models`,hint:`Choose a provider and model for each kind of content. After switching models, fill the new index to make existing documents searchable. Previous model indexes are preserved.`}),E.length===0?(0,Z.jsxs)(`div`,{className:`rounded-lg border border-dashed p-6 text-center`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium`,children:`No spaces on this layer`}),(0,Z.jsx)(`p`,{className:`mx-auto mt-1 max-w-sm text-xs text-muted-foreground`,children:`A space needs a backend, a model and a dimension count. Add one below to start embedding.`})]}):(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:E.map(e=>{let s=f.spaces?.[e]||{},l=t.spaces?.[e]||{},u=n.spaces?.[e]||{},d=r?.[e],p=`space:${e}`,m=w===p,h=s.model??l.model,_=s.provider??l.provider,y=s.dim??l.dim,b=s.chunk??l.chunk??!1,x=a?.includes(e)??!1;return(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(`span`,{className:K(`absolute inset-y-0 left-0 w-[3px]`,Ak[i?`unresolved`:x?`needs-fill`:h?`configured`:`unset`]),"aria-hidden":!0}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 py-3 pl-4 pr-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:K(`text-[11px]`,vk),children:e}),(0,Z.jsx)(`span`,{className:`truncate font-mono text-sm`,children:h||`no model set`}),_&&(0,Z.jsxs)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground`,children:[`via `,_]}),y!==void 0&&(0,Z.jsxs)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:[y,`-d`]}),b&&(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`chunked`})]}),r&&h&&(0,Z.jsxs)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,title:`Vector table backing this space`,children:[`└─ `,d?.table??(0,Z.jsx)(`span`,{className:`not-italic`,children:`not created yet`})]}),x&&(0,Z.jsx)(`p`,{className:`mt-1 text-[11px] text-warning`,children:`New table, nothing embedded in it yet; dense search stays thin for this space until it is filled. Reverting the model is still instant.`})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[x&&o&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>o(e),children:`Fill`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:c||g!==null,onClick:()=>F(e),title:`Round-trip a real embedding call against this backend and report the dimensions it returns`,children:[(0,Z.jsx)(_e,{className:`mr-1.5 h-3.5 w-3.5`}),g===e?v?`Downloading…`:`Testing…`:`Test`]}),(0,Z.jsx)(kk,{open:m,onClick:()=>te(p),label:`Edit ${e}`})]})]}),m&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 py-4 pl-4 pr-3`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Backend`}),(0,Z.jsx)(Tk,{overridden:s.provider!==void 0,source:u.provider})]}),(0,Z.jsxs)(`select`,{className:_k,disabled:c,value:s.provider??``,onChange:t=>O(e,`provider`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:l.provider?`inherited: ${l.provider}`:`inherited`}),D.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Z.jsx)(Ek,{label:`Model`,mono:!0,value:s.model,inheritedValue:l.model,onChange:t=>O(e,`model`,t),disabled:c}),(0,Z.jsx)(Ek,{label:`Dimensions`,type:`number`,value:s.dim,inheritedValue:l.dim,onChange:t=>O(e,`dim`,t),disabled:c,hint:`Sizes the vector table. Test asks the backend and fills in what it really returns.`}),(0,Z.jsx)(Ek,{label:`Max length`,type:`number`,value:s.maxLength,inheritedValue:l.maxLength,onChange:t=>O(e,`maxLength`,t),disabled:c})]}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-4`,children:[(0,Z.jsx)(Dk,{label:`Chunk long inputs`,checked:b,overridden:s.chunk!==void 0,disabled:c,onChange:t=>k(e,`chunk`,t)}),(0,Z.jsx)(Dk,{label:`Build ANN index`,checked:s.annIndex??l.annIndex??!0,overridden:s.annIndex!==void 0,disabled:c,onChange:t=>k(e,`annIndex`,t)})]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:S,onChange:e=>C(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),N())},placeholder:`new space name (e.g. audio)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:N,children:[(0,Z.jsx)(U,{className:`mr-1.5 h-3.5 w-3.5`}),`Add space`]})]})]}),(0,Z.jsxs)(`section`,{children:[(0,Z.jsx)(wk,{title:`Model providers`,hint:`Connect a service here, then select it under Search models above. Built-in providers work without an extra connection. Provider changes take effect when you save.`}),(0,Z.jsx)(`div`,{className:`divide-y overflow-hidden rounded-lg border`,children:D.map(e=>{let n=f.providers?.[e]||{},r=t.providers?.[e]||{},i=$O.includes(e),a=f.providers?.[e]!==void 0,o=`provider:${e}`,s=w===o,l=n.type??r.type,u=l?yk[l]:void 0,d=u?.url?Ck(n[u.url.key]):null,p={...r,...n},h=bk.filter(e=>!(n[e]===void 0||e===u?.url?.key||e===`apiKey`&&u?.apiKey||e===`cacheDir`&&u?.cacheDir)),g=E.filter(n=>(f.spaces?.[n]?.provider??t.spaces?.[n]?.provider)===e);return(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-start sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1`,children:[(0,Z.jsx)(`span`,{className:`font-mono text-sm font-semibold`,children:e}),(0,Z.jsx)(`span`,{className:`rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:l??`no type`}),i&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:`built-in`}),p.apiKeySet&&!m.has(e)&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-success`,children:`key set`}),d&&(0,Z.jsx)(`span`,{className:`text-[10px] font-medium text-destructive`,children:`check endpoint`})]}),(0,Z.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground`,children:u?u.where(p):`—`}),g.length>0&&(0,Z.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`used by `,g.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 max-sm:justify-end`,children:[a&&!i&&!c&&(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>M(e),title:`Remove this override`,children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(kk,{open:s,onClick:()=>te(o),label:`Edit ${e}`})]})]}),s&&(0,Z.jsxs)(`div`,{className:`border-t bg-muted/40 px-4 py-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Type`}),(0,Z.jsx)(Tk,{overridden:n.type!==void 0,source:r.type})]}),(0,Z.jsxs)(`select`,{className:_k,disabled:c,value:n.type??``,onChange:t=>A(e,`type`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.type?`inherited: ${r.type}`:`inherited`}),QO.map(e=>(0,Z.jsx)(`option`,{value:e,children:e},e)),l&&!QO.includes(l)&&(0,Z.jsxs)(`option`,{value:l,children:[l,` (legacy)`]})]}),u?.note&&(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:u.note})]}),u?.url&&(0,Z.jsx)(Ek,{label:u.url.label,mono:!0,value:n[u.url.key],inheritedValue:r[u.url.key],onChange:t=>A(e,u.url.key,t),disabled:c,placeholder:r[u.url.key]??u.url.placeholder,hint:u.url.hint,error:d??void 0}),u?.cacheDir&&(0,Z.jsx)(Ek,{label:`Cache directory`,mono:!0,value:n.cacheDir,inheritedValue:r.cacheDir,onChange:t=>A(e,`cacheDir`,t),disabled:c,placeholder:r.cacheDir??`server default`,hint:u.cacheDir}),u?.imageInput&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`Image input shape`}),(0,Z.jsx)(Tk,{overridden:n.imageInput!==void 0,source:r.imageInput})]}),(0,Z.jsxs)(`select`,{className:_k,disabled:c,value:n.imageInput??``,onChange:t=>A(e,`imageInput`,t.target.value),children:[(0,Z.jsx)(`option`,{value:``,children:r.imageInput?`inherited: ${r.imageInput}`:`inherited: data-uri`}),xk.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Z.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:xk.find(e=>e.value===(n.imageInput??r.imageInput??`data-uri`))?.hint})]}),u?.timeoutMs&&(0,Z.jsx)(Ek,{label:`Request timeout (ms)`,type:`number`,value:n.timeoutMs,inheritedValue:r.timeoutMs??Sk,onChange:t=>A(e,`timeoutMs`,t),disabled:c,hint:`How long to wait for a batch before giving up. Raise it for a slow or cold GPU host.`}),u?.apiKey&&(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`label`,{className:`text-xs font-medium`,children:`API key`}),m.has(e)&&(0,Z.jsx)(`span`,{className:`rounded bg-warning-subtle px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:`will be written`})]}),(0,Z.jsx)(q,{type:`password`,autoComplete:`new-password`,disabled:c,value:n.apiKey??``,onChange:t=>A(e,`apiKey`,t.target.value),placeholder:r.apiKeySet?`•••••••• (stored; leave empty to keep)`:`unset`,className:`h-8 text-sm`}),(0,Z.jsxs)(`p`,{className:`text-[11px] text-muted-foreground`,children:[u.apiKey,` Write-only: the stored key is never sent back, and leaving this empty keeps whatever is stored.`]})]})]}),u?.headers&&(0,Z.jsx)(Ok,{disabled:c,storedNames:r.headerNames,value:n.headers,onChange:t=>j(e,`headers`,t)}),h.length>0&&!c&&(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 rounded-md border border-dashed p-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`Not used by type `,(0,Z.jsx)(`span`,{className:`font-mono`,children:l}),`:`,` `,(0,Z.jsx)(`span`,{className:`font-mono`,children:h.join(`, `)})]}),(0,Z.jsx)(`button`,{type:`button`,className:`underline hover:text-foreground`,onClick:()=>h.forEach(t=>A(e,t,``)),children:`clear`})]}),r.headerNames&&r.headerNames.length>0&&(0,Z.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted-foreground`,children:[`Stored custom headers: `,(0,Z.jsx)(`span`,{className:`font-mono`,children:r.headerNames.join(`, `)}),` (values not shown)`]})]})]},e)})}),!c&&(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,Z.jsx)(q,{value:b,onChange:e=>x(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),P(b.trim()))},placeholder:`new backend name (e.g. gpu)`,className:`h-8 w-full max-w-xs text-sm sm:w-auto`}),(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>P(b.trim()),children:[(0,Z.jsx)(U,{className:`mr-1.5 h-3.5 w-3.5`}),`Add backend`]}),ek.filter(e=>!D.includes(e.id)).map(e=>(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>P(e.id,e.baseUrl),title:`Add an openai-type backend '${e.id}' pointed at ${e.baseUrl}`,children:e.label},e.id))]})]}),!c&&(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-4`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:L?`default`:`outline`,onClick:R,disabled:s||!L||I.length>0,children:s?`Saving…`:l}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:s||!L,onClick:()=>{p(structuredClone(e)),h(new Set)},children:`Discard changes`}),(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:I.length>0?(0,Z.jsxs)(`span`,{className:`font-medium text-destructive`,children:[I.length,` endpoint `,I.length===1?`needs`:`need`,` fixing`]}):L?`Unsaved changes`:`Everything saved`})]})]})}function Mk(){let{showToast:e}=Vr(),[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0),[a,o]=(0,X.useState)(!1),[s,c]=(0,X.useState)(null),l=(0,X.useCallback)(()=>dk().then(e=>{n(e),c(null)}).catch(e=>c(e instanceof Error?e.message:`Failed to load embedding defaults`)).finally(()=>i(!1)),[]);(0,X.useEffect)(()=>{l()},[l]);let u=()=>{i(!0),l()};return(0,Z.jsxs)(`div`,{className:`mx-auto max-w-4xl p-6`,children:[(0,Z.jsx)($x,{compact:!0,className:`mb-6`,title:`Search & AI defaults`,onBack:jT(),description:`Your account · Choose the embedding models used for text and image search. Workspace settings override these defaults. Running workspaces adopt new defaults when restarted.`,actions:(0,Z.jsxs)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,disabled:r,children:[(0,Z.jsx)(we,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})}),r?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(we,{className:`h-4 w-4 animate-spin`}),`Loading…`]}):s||!t?(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm`,children:[(0,Z.jsx)(`p`,{className:`font-medium text-destructive`,children:`Embedding defaults unavailable`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s||`No config returned.`})]}),(0,Z.jsx)(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:u,children:`Retry`})]}):(0,Z.jsx)(jk,{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 fk(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 Nk(){let e=nl(),{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,X.useState)(i),[c,l]=(0,X.useState)(a),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(!1),g=(0,X.useMemo)(()=>{try{let e=new URL(o);return e.pathname.includes(`/pub/workspaces/`)?`workspace`:e.pathname.includes(`/pub/contexts/`)?`context`:`unknown`}catch{return`unknown`}},[o]),_=()=>({Authorization:`Bearer ${c.trim()}`}),v=async()=>{if(!(!o||!c)){h(!0);try{let e=r(o),t=await J.get(e,{skipAuth:!0,headers:_()});d(t);let n=await J.get(`${e}/documents`,{skipAuth:!0,headers:_()}),i=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];p(Array.isArray(i)?i:[])}catch(e){let n=o.includes(`/rest/v2/workspaces/`)?`Ensure the URL uses /rest/v2/pub/workspaces/<workspace-id> and the token matches that workspace.`:o.includes(`/rest/v2/contexts/`)?`Ensure the URL uses /rest/v2/pub/contexts/<context-id>.`:void 0;t({title:`Error`,description:`${e instanceof Error?e.message:`Failed to load shared resource`}${n?`: ${n}`:``}`,variant:`destructive`}),d(null),p([])}finally{h(!1)}}},y=(0,X.useRef)(v);return(0,X.useEffect)(()=>{y.current()},[]),(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsx)($x,{onBack:jT(),title:`Shared Resource Viewer`,description:`Open a resource someone shared with you.`}),(0,Z.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[(0,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`Full pub URL`}),(0,Z.jsx)(q,{value:c,onChange:e=>l(e.target.value),placeholder:`Access token (canvas-...)`}),(0,Z.jsx)(Y,{onClick:v,disabled:m||!o||!c,children:`Load`})]}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Type: `,g]}),m?(0,Z.jsx)(`div`,{className:`text-center py-8 text-muted-foreground`,children:`Loading...`}):(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsx)(`h2`,{className:`font-semibold mb-2`,children:`Metadata`}),(0,Z.jsx)(`pre`,{className:`text-xs overflow-auto max-h-80`,children:JSON.stringify(u,null,2)})]}),(0,Z.jsxs)(`div`,{className:`border rounded p-3`,children:[(0,Z.jsxs)(`h2`,{className:`font-semibold mb-2`,children:[`Documents (`,f.length,`)`]}),f.length===0?(0,Z.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:`No documents`}):(0,Z.jsx)(`ul`,{className:`space-y-2 text-sm`,children:f.slice(0,100).map((e,t)=>(0,Z.jsxs)(`li`,{className:`border rounded p-2`,children:[(0,Z.jsx)(`div`,{className:`font-mono text-xs`,children:e.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:e.schema})]},t))})]})]}),(0,Z.jsx)(td,{className:`mt-8`})]})}function Pk(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 Fk(){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 Ik={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?`${Sr.admin.users}?${n}`:Sr.admin.users;return await J.get(r)},async getUser(e){return await J.get(`${Sr.admin.users}/${e}`)},async createUser(e){return await J.post(Sr.admin.users,e)},async updateUser(e,t){return await J.put(`${Sr.admin.users}/${e}`,t)},async deleteUser(e){await J.delete(`${Sr.admin.users}/${e}`)}},Lk={async listAllWorkspaces(){return await J.get(Sr.admin.workspaces)},async createWorkspace(e){return await J.post(Sr.admin.workspaces,e)},async deleteWorkspace(e){await J.delete(`${Sr.admin.workspaces}/${e}`)}},Rk={async getLogs(e={}){return(await J.get(`${Sr.admin.logs}${Pk(e)}`)).logs||[]},async streamLogs(e={},t={}){let{signal:n,onEntry:r,onError:i}=t;try{let t=await fetch(`${Sr.admin.logsStream}${Pk(e)}`,{method:`GET`,headers:Fk(),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(`
|
|
27
27
|
`),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(`
|
|
28
28
|
`));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(`
|
|
29
29
|
|
|
@@ -92,6 +92,6 @@ set -euo pipefail
|
|
|
92
92
|
`)})]})]})}function U2({device:e,linked:t,busy:n,onLink:r,onUnlink:i,onUpdate:a}){let[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(e.name),[u,d]=(0,X.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,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-3 min-w-0`,children:[(0,Z.jsx)(fe,{className:`h-4 w-4 text-muted-foreground mt-0.5 shrink-0`}),(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[o?(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(q,{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,Z.jsx)(q,{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,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium`,children:e.name}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground mt-0.5`,children:e.description})]}),(0,Z.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,Z.jsx)(`span`,{children:e.deviceId}),e.platform&&(0,Z.jsx)(`span`,{children:e.platform}),e.arch&&(0,Z.jsx)(`span`,{children:e.arch}),e.type&&(0,Z.jsx)(`span`,{children:e.type})]})]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[o?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:f,disabled:!c.trim(),children:(0,Z.jsx)($e,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:p,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]}):(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>s(!0),title:`Edit name/description`,children:(0,Z.jsx)(Fe,{className:`h-3.5 w-3.5`})}),t?(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:i,className:`text-destructive hover:text-destructive`,title:`Remove from workspace`,children:(0,Z.jsx)(pe,{className:`h-3.5 w-3.5`})}):(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:r,title:`Link to workspace`,children:(0,Z.jsx)(Gt,{className:`h-3.5 w-3.5`})}),t&&(0,Z.jsx)(`span`,{className:`rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary`,children:`linked`})]})]})})}function W2({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,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(we,{className:`h-4 w-4 animate-spin`}),`Loading devices…`]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.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,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:i,disabled:n,children:[(0,Z.jsx)(we,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),e.length===0?(0,Z.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,Z.jsx)(`span`,{className:`font-mono`,children:`POST /auth/devices/register`}),`.`]}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.map(e=>(0,Z.jsx)(U2,{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 G2({label:e,value:t,mono:n=!1}){return(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-2 border-b last:border-0`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground shrink-0`,children:e}),(0,Z.jsx)(`span`,{className:`text-xs text-right ${n?`font-mono`:``}`,children:t??`—`})]})}function K2({workspaceName:e,current:t,weights:n,floorMode:r,relativeMargin:i,onDone:a}){let[o,s]=(0,X.useState)(t==null?``:String(t)),[c,l]=(0,X.useState)(r??`relative`),[u,d]=(0,X.useState)(i==null?`0.035`:String(i)),[f,p]=(0,X.useState)(n?.fts==null?`2`:String(n.fts)),[m,h]=(0,X.useState)(n?.dense==null?`1`:String(n.dense)),[g,_]=(0,X.useState)(n?.image==null?`2`:String(n.image)),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(null),[S,C]=(0,X.useState)(YC);return(0,Z.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`How photo relevance is decided`}),(0,Z.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,Z.jsx)(`option`,{value:`relative`,children:`Relative to the best match (recommended)`}),(0,Z.jsx)(`option`,{value:`absolute`,children:`Absolute distance cutoff`})]}),(0,Z.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,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Window width (distance from the best match)`}),(0,Z.jsx)(q,{value:u,onChange:e=>d(e.target.value),placeholder:`0.035`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,Z.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,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.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,Z.jsx)(q,{value:o,onChange:e=>s(e.target.value),placeholder:`0.95`,className:`h-8 w-28 font-mono text-xs`,inputMode:`decimal`}),(0,Z.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,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(`label`,{className:`text-xs text-muted-foreground`,children:`Hybrid fusion weights (0 disables a signal)`}),(0,Z.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,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`span`,{className:`block text-[11px] text-muted-foreground`,children:e}),(0,Z.jsx)(q,{value:t,onChange:e=>n(e.target.value),className:`h-8 w-16 font-mono text-xs`,inputMode:`decimal`})]},e))}),(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(Y,{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 oo(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,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:b})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5 border-t border-border pt-3`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>{XC(e.target.checked),C(e.target.checked)}}),(0,Z.jsx)(`span`,{children:`Debug query`})]}),(0,Z.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 q2({stats:e,isLoading:t,onRefresh:n,workspaceName:r}){return t?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,children:[(0,Z.jsx)(we,{className:`h-4 w-4 animate-spin`}),`Loading stats…`]}):(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Live snapshot from synapsd. Click refresh for updated counts.`}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:n,disabled:t,children:[(0,Z.jsx)(we,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),(0,Z.jsx)(X2,{workspaceName:r,vectorSpaces:Object.keys(e?.semantic?.vectorSpaces||{}),onDone:n}),e?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(wt,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Core Index`})]}),(0,Z.jsx)(G2,{label:`Backend`,value:e.dbBackend,mono:!0}),(0,Z.jsx)(G2,{label:`Status`,value:e.status}),(0,Z.jsx)(G2,{label:`Path`,value:e.dbPath,mono:!0}),(0,Z.jsx)(G2,{label:`Documents`,value:e.documentCount?.toLocaleString()}),(0,Z.jsx)(G2,{label:`Metadata entries`,value:e.metadataCount?.toLocaleString()}),(0,Z.jsx)(G2,{label:`Checksum index`,value:e.checksumIndexSize?.toLocaleString()}),(0,Z.jsx)(G2,{label:`Bitmap store`,value:e.bitmapStoreSize?.toLocaleString()}),(0,Z.jsx)(G2,{label:`Bitmap cache`,value:e.bitmapCacheSize?.toLocaleString()}),(0,Z.jsx)(G2,{label:`Deleted (pending GC)`,value:e.deletedDocumentsCount?.toLocaleString()})]}),e.fts&&(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(mt,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Full-Text Search (LanceDB)`})]}),`ready`in e.fts&&(0,Z.jsx)(G2,{label:`Ready`,value:String(e.fts.ready)}),e.fts.rowCount!==void 0&&(0,Z.jsx)(G2,{label:`Row count`,value:e.fts.rowCount?.toLocaleString()}),e.fts.error&&(0,Z.jsx)(G2,{label:`Error`,value:(0,Z.jsx)(`span`,{className:`text-destructive`,children:e.fts.error})})]}),e.semantic&&(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,Z.jsx)(mt,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Semantic / Vector Search`})]}),(0,Z.jsx)(G2,{label:`Enabled`,value:String(e.semantic.enabled)}),e.semantic.enabled&&(0,Z.jsxs)(Z.Fragment,{children:[e.inferd?.routing?Object.entries(e.inferd.routing).map(([e,t])=>(0,Z.jsx)(G2,{label:`Embeds → ${e}`,value:(0,Z.jsx)(`span`,{className:`font-mono text-[11px]`,children:t.join(`, `)})},`route-${e}`)):(0,Z.jsx)(G2,{label:`Text-embeddable (gap default)`,value:e.semantic.embeddableSchemas?.join(`, `)}),e.semantic.vectorSpaces&&Object.entries(e.semantic.vectorSpaces).map(([e,t])=>(0,Z.jsx)(G2,{label:`Space: ${e} (${t.dim??`?`}-d)`,value:t.error?(0,Z.jsx)(`span`,{className:`text-destructive`,children:t.error}):`${(t.embeddedDocs??0).toLocaleString()} docs · ${(t.chunkRows??0).toLocaleString()} vectors`},e)),(0,Z.jsx)(G2,{label:`Photo relevance`,value:e.semantic.imageFloorMode===`absolute`?`absolute cutoff`:`relative ±${e.semantic.imageRelativeMargin??.035}`,mono:!0}),(0,Z.jsx)(G2,{label:e.semantic.imageFloorMode===`absolute`?`Image relevance floor`:`Hard ceiling`,value:e.semantic.imageMaxDistance==null?`off`:e.semantic.imageMaxDistance,mono:!0}),(0,Z.jsx)(G2,{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,Z.jsx)(K2,{workspaceName:r,current:e.semantic.imageMaxDistance,weights:e.semantic.searchWeights,floorMode:e.semantic.imageFloorMode,relativeMargin:e.semantic.imageRelativeMargin,onDone:n})]})]})]}):(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No stats available.`})]})}function J2(){let{workspaceName:e,tab:t}=ll(),[n,r]=Ou(),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,l=n.get(`addRuleKind`),u=n.get(`addRulePath`),d=n.get(`addRuleTarget`),f=n.get(`addRuleStoreTo`),p=n.get(`addRuleStoreFolder`),m=(0,X.useMemo)(()=>l===`store`||l===`download`?!u&&!f&&!p?null:{kind:l,path:u||``,storeTo:f||``,storeFolder:p||``}:u?{kind:`mirror`,path:u,target:d||`dir:/`}:null,[l,u,d,f,p]),h=(0,X.useCallback)(()=>{r(e=>{for(let t of[`addRuleKind`,`addRulePath`,`addRuleTarget`,`addRuleStoreTo`,`addRuleStoreFolder`])e.delete(t);return e},{replace:!0})},[r]),g=al(),{showToast:_}=Vr(),v=Jm(),{openM2Drawer:y}=zS(),b=UT(t);(0,X.useEffect)(()=>{t!==b&&g(`/workspaces/${e}/settings/${b}`,{replace:!0})},[t,b,e,g]);let[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(0),[T,E]=(0,X.useState)(!0),[D,O]=(0,X.useState)(!1),[k,A]=(0,X.useState)(!1),[j,M]=(0,X.useState)(``),[N,P]=(0,X.useState)(``),[ee,F]=(0,X.useState)(`#FFFFFF`),[I,L]=(0,X.useState)(null),[R,te]=(0,X.useState)(null),[ne,z]=(0,X.useState)([]),[re,ie]=(0,X.useState)(null),[ae,oe]=(0,X.useState)([]),[se,B]=(0,X.useState)(null),[ce,V]=(0,X.useState)(null),[le,ue]=(0,X.useState)(!1),[de,fe]=(0,X.useState)([]),[me,he]=(0,X.useState)([]),[ge,_e]=(0,X.useState)(!1),[ve,ye]=(0,X.useState)(null),H=e||x?.id||``,be=(0,X.useRef)(H);(0,X.useEffect)(()=>{be.current=H});let U=(0,X.useCallback)(async e=>{let t=e??be.current;if(t)try{let e=await Wi(t);z(e.publicCanvasShares)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load shares`,variant:`destructive`})}},[_]),xe=(0,X.useCallback)(async e=>{let t=e??be.current;if(t){ue(!0);try{let e=await ta(t);V(e)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to load DB stats`,variant:`destructive`})}finally{ue(!1)}}},[_]),Se=(0,X.useCallback)(async e=>{let t=e??be.current;if(t){_e(!0);try{let[e,n]=await Promise.all([NT(),IT(t)]);fe(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=>{ye(e);try{await LT(H,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{ye(null)}},W=async e=>{ye(e);try{await RT(H,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{ye(null)}},G=async(e,t)=>{ye(`edit:${e}`);try{let n=await PT(e,t);fe(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{ye(null)}},Te=(0,X.useCallback)(async e=>{let t=e??be.current;if(!t)return;let[n,r]=await Promise.all([to(t).catch(()=>null),Ta(t).catch(()=>[])]);ie(n),oe(r.filter(e=>e.kind===`storage`))},[]),Ee=ae.some(e=>e.resyncing);(0,X.useEffect)(()=>{if(!Ee||!H)return;let e=setInterval(()=>{Te()},4e3);return()=>clearInterval(e)},[Ee,H,Te]),(0,X.useEffect)(()=>{async function t(){try{let t=(await Xr()).find(t=>t.name===e||t.id===e);t&&(S(t),M(t.label||``),P(t.description||``),F(t.color||`#FFFFFF`),L(t.icon??null),t.status===`active`&&await Promise.all([U(e||t.id),Te(e||t.id)]))}catch{_({title:`Error`,description:`Failed to load workspace`,variant:`destructive`})}finally{E(!1)}}t()},[e,U,Te,_,C]),(0,X.useEffect)(()=>{let e=()=>w(e=>e+1);return window.addEventListener(`workspaces:refresh`,e),()=>window.removeEventListener(`workspaces:refresh`,e)},[]);let De=(0,X.useRef)(!1),Oe=(0,X.useRef)(!1);(0,X.useEffect)(()=>{De.current=!!ce||le,Oe.current=ge||de.length>0}),(0,X.useEffect)(()=>{x?.status===`active`&&b===`db`&&H&&!De.current&&xe(),x?.status===`active`&&b===`devices`&&H&&!Oe.current&&Se()},[b,H,x?.status,xe,Se]);let ke=async e=>{if(e.preventDefault(),x){O(!0);try{await Ba(H,{label:j.trim(),description:N.trim(),color:ee,icon:I}),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{O(!1)}}},Ae=async()=>{if(x&&window.confirm(`Destroy workspace "${x.label||x.name}"? This cannot be undone.`)){A(!0);try{await pi(H),window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),_({title:`Destroyed`,description:`${x.label||x.name} has been removed`}),g(`/workspaces`)}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Destroy failed`,variant:`destructive`})}finally{A(!1)}}},je=()=>{for(let t of[e,x?.name,x?.id])t&&Sa(t,`backends`);window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:H}}))},Me=async e=>{if(e.config?.supported!==!1){B(`backend:${e.address}`);try{await Ya(H,e.driver,e.address,{enabled:!e.enabled}),await Te(),je(),_({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{B(null)}}},Ne=async(e,t,n)=>{B(`${n}:${e.address}`);try{await Ya(H,e.driver,e.address,t),await Te()}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to update backend`,variant:`destructive`})}finally{B(null)}},Pe=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.`)){B(`remove:${e.address}`);try{await Ri(H,e.driver,e.address),await Te(),je(),_({title:`Removed`,description:`${t} unmounted`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Failed to remove backend`,variant:`destructive`})}finally{B(null)}}},Fe=async e=>{B(`resync:${e.address}`);try{await Ka(H,e.driver,e.address),await Te(),_({title:`Re-syncing`,description:`${e.address} scan started`})}catch(e){_({title:`Error`,description:e instanceof Error?e.message:`Re-sync failed`,variant:`destructive`})}finally{B(null)}},Ie=async e=>{B(`test:${e.address}`);try{await pa(H,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{B(null)}},Le=async e=>{B(`stopsync:${e.address}`);try{await ha(H,e.driver,e.address),await Te(),_({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{B(null)}},Re=async(e,t)=>{B(`service:${e}`);try{t?await Na(H,e):await ci(H,e),await Te(),_({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{B(null)}},ze=async e=>{let t=`${window.location.origin}${e.url}`;await navigator.clipboard?.writeText(t),_({title:`Copied`,description:t})},Be=async e=>{if(x&&window.confirm(`Revoke public share for "${e.path}"?`)){B(`share:${e.code}`);try{await na(H,e.code),await U(H),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:H}})),_({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{B(null)}}},He=VT.find(e=>e.id===b);return T?(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`}):x?(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-5xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)($x,{compact:!0,className:`mb-6 border-b pb-4`,title:`${He.label} - ${x.label||x.name}`,description:`This workspace · ${He.description}`,backTo:`/workspaces/${e}`,onBack:v?()=>y(`workspaces`,`settings`,e??null):void 0}),x.status!==`active`&&b!==`general`&&(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Start this workspace to access these settings. General settings and protection remain available while stopped.`}),b===`general`&&(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`form`,{onSubmit:ke,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ws-label`,className:`text-sm font-medium`,children:`Label`}),(0,Z.jsx)(q,{id:`ws-label`,value:j,onChange:e=>M(e.target.value),placeholder:`Workspace Label`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ws-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`ws-description`,value:N,onChange:e=>P(e.target.value),placeholder:`Description (optional)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Icon & color`}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Pick icon & color`,onClick:e=>te({x:Math.min(e.clientX,window.innerWidth-290),y:Math.min(e.clientY,window.innerHeight-360)}),className:`flex h-10 w-10 items-center justify-center rounded-md border hover:bg-accent`,children:(0,Z.jsx)(c,{icon:I||`ph:stack-fill`,width:22,height:22,color:hp(ee)})}),(0,Z.jsx)(q,{id:`ws-color`,type:`color`,value:ee,onChange:e=>F(e.target.value),className:`h-10 w-16 p-1`}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>F(fp()),children:`Randomize`})]})]}),(0,Z.jsx)(Y,{type:`submit`,disabled:D||!j.trim(),children:D?`Saving...`:`Save Changes`})]}),R&&(0,Z.jsx)(rS,{x:R.x,y:R.y,current:{icon:I??void 0,color:ee},onChange:e=>{`icon`in e&&L(e.icon??null),`color`in e&&e.color&&F(e.color)},onClose:()=>te(null)}),(0,Z.jsx)($A,{currentMode:x.protection?.mode,workspaceId:H,isActive:x.status===`active`,onChanged:()=>w(e=>e+1)}),x.status===`active`&&(0,Z.jsx)(Y2,{workspaceName:e}),x.status===`active`&&(0,Z.jsx)(V2,{workspaceId:H}),(0,Z.jsx)(N2,{workspaceId:H,workspaceName:x.label||x.name,isActive:x.status===`active`,onChanged:()=>w(e=>e+1)}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(Y,{variant:`destructive`,disabled:k,onClick:Ae,children:[(0,Z.jsx)(lt,{className:`mr-2 h-4 w-4`}),k?`Destroying...`:`Destroy Workspace`]})]})]}),x.status===`active`&&b===`shares`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Members`}),(0,Z.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,Z.jsx)(M2,{workspaceId:H})]}),(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Public Canvas Shares`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Active public canvas links for this workspace.`})]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>U(),children:[(0,Z.jsx)(we,{className:`mr-2 h-3.5 w-3.5`}),`Refresh`]})]}),ne.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border p-4 text-sm text-muted-foreground`,children:`No public canvas shares. Good.`}):ne.map(e=>{let t=`${window.location.origin}${e.url}`;return(0,Z.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate font-mono text-sm`,children:e.path}),(0,Z.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,Z.jsxs)(`div`,{className:`mt-1 text-[11px] text-muted-foreground`,children:[`locks: `,e.lockedBy.join(`, `)]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ze(e),children:(0,Z.jsx)(Ve,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>window.open(t,`_blank`,`noreferrer`),children:(0,Z.jsx)(gn,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:se===`share:${e.code}`,onClick:()=>Be(e),className:`text-destructive hover:text-destructive`,children:(0,Z.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]}),(0,Z.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,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workspace ACL Tokens`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Generate token-based workspace access for devices, scripts, and other users.`})]}),(0,Z.jsx)(O2,{workspaceId:H})]})]}),x.status===`active`&&b===`data`&&(0,Z.jsxs)(`div`,{className:`space-y-3`,children:[ae.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&&!P2[n],s=P2[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.`},l=t.supported!==!1,u=n===`workspace:data`,d=l&&!u,f=d&&t.managed!==!0,p=ap(e);return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(c,{icon:p.icon,width:16,height:16,color:p.color,className:`shrink-0`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:s.title}),!l&&(0,Z.jsx)(`span`,{className:`rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground`,children:`unsupported`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s.description}),typeof t.root==`string`&&t.root&&(0,Z.jsx)(`p`,{className:`mt-2 truncate font-mono text-xs text-muted-foreground`,children:t.root}),(0,Z.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2 text-[11px] text-muted-foreground`,children:[(0,Z.jsxs)(`span`,{children:[`status: `,e.status]}),e.resyncing&&(0,Z.jsxs)(`span`,{className:`flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 font-medium text-primary`,children:[(0,Z.jsx)(we,{className:`h-3 w-3 animate-spin`}),`indexing`,e.progress?` ${e.progress.scanned}${e.progress.total==null?``:` / ${e.progress.total}`}`:``]}),r?.name&&(0,Z.jsxs)(`span`,{title:r.id,children:[`device: `,r.name]}),t.readOnly===!0&&(0,Z.jsx)(`span`,{className:`rounded bg-warning/15 px-1.5 py-0.5 font-medium text-warning`,children:`read-only`}),e.lastSyncAt&&(0,Z.jsxs)(`span`,{children:[`last scan: `,new Date(e.lastSyncAt).toLocaleString()]})]}),e.lastError&&(0,Z.jsx)(`p`,{className:`mt-2 text-xs text-destructive`,children:e.lastError}),t.readOnly===!0&&(0,Z.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,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t pt-3`,children:[e.capabilities?.sync&&l&&(0,Z.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,Z.jsx)(I2,{checked:t.scanOnStart===!0,disabled:se===`startup:${n}`,onClick:()=>Ne(e,{scanOnStart:t.scanOnStart!==!0},`startup`)})]}),(e.driver===`file`||i||a)&&d&&(0,Z.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,Z.jsx)(I2,{checked:!!t.watch,disabled:!e.enabled||se===`watch:${n}`,onClick:()=>Ne(e,{watch:!t.watch},`watch`)})]}),f&&(0,Z.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,Z.jsx)(I2,{checked:t.readOnly===!0,disabled:se===`readonly:${n}`,onClick:()=>Ne(e,{readOnly:t.readOnly!==!0},`readonly`)})]}),(e.driver===`file`||e.driver===`cacache`)&&l&&(0,Z.jsx)(z2,{workspaceId:H,backend:e}),e.capabilities?.test&&(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:se===`test:${n}`,onClick:()=>Ie(e),title:`Verify credentials and root folder`,children:[(0,Z.jsx)(mt,{className:`mr-2 h-3.5 w-3.5`}),se===`test:${n}`?`Testing…`:`Test`]}),e.capabilities?.sync&&(e.resyncing?(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:se===`stopsync:${n}`,onClick:()=>Le(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,Z.jsx)(nn,{className:`mr-2 h-3.5 w-3.5 fill-current`}),se===`stopsync:${n}`?`Stopping…`:`Stop sync`]}):(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:se===`resync:${n}`,onClick:()=>Fe(e),children:[(0,Z.jsx)(we,{className:`mr-2 h-3.5 w-3.5 ${se===`resync:${n}`?`animate-spin`:``}`}),`Re-sync`]})),u?(0,Z.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,Z.jsx)(I2,{checked:!!e.enabled,disabled:!d||se===`backend:${n}`,onClick:()=>Me(e)}),o&&(0,Z.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:se===`remove:${n}`,title:`Unmount this folder (no files are deleted)`,onClick:()=>Pe(e),children:(0,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]}),a&&(0,Z.jsx)(QA,{workspaceId:H,backend:e,onSaved:async()=>{await Te(),je()}}),e.driver===`file`&&l&&!u&&(0,Z.jsx)(H2,{backend:e,busy:se===`exclude:${n}`,onSave:t=>Ne(e,{exclude:t},`exclude`)})]},n)}),(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(c,{icon:`ph:lightning-fill`,width:16,height:16,className:`shrink-0 text-warning`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Stored Cache`})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Internal working store: local copies of remote resources and derived artifacts (thumbnails). Regenerable; safe to clear.`})]}),(0,Z.jsx)(`div`,{className:`flex shrink-0 items-center gap-3 max-sm:w-full max-sm:flex-wrap`,children:(0,Z.jsx)(B2,{workspaceId:H})})]})}),(0,Z.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-start`,children:[(0,Z.jsx)(L2,{workspaceId:H,onAdded:async()=>{await Te(),je()}}),(0,Z.jsx)(R2,{workspaceId:H,onAdded:async()=>{await Te(),je()}}),(0,Z.jsx)(QA,{workspaceId:H,onSaved:async()=>{await Te(),je()}})]}),e&&(0,Z.jsx)(`section`,{className:`border-t pt-4`,children:(0,Z.jsx)(r2,{workspaceName:e})})]}),x.status===`active`&&b===`db`&&(0,Z.jsxs)(`div`,{className:`space-y-8`,children:[H&&(0,Z.jsxs)(`section`,{className:`space-y-3`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Embeddings`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Which model turns this workspace's content into vectors, and where those vectors live.`})]}),(0,Z.jsx)(uj,{workspaceId:H,workspaceName:e})]}),(0,Z.jsx)(q2,{stats:ce,isLoading:le,onRefresh:()=>xe(),workspaceName:e})]}),x.status===`active`&&b===`devices`&&(0,Z.jsx)(W2,{allDevices:de,linkedDevices:me,isLoading:ge,deviceBusy:ve,onRefresh:()=>Se(),onLink:Ce,onUnlink:W,onUpdate:G}),x.status===`active`&&b===`sync`&&(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(_2,{workspaceId:H,workspaceUuid:x?.id})}),x.status===`active`&&b===`services`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[H&&(0,Z.jsx)(w2,{workspaceId:H}),(0,Z.jsx)(`div`,{className:`space-y-3`,children:F2.map(e=>{let t=re?.[e.id]||re?.[e.id===`git`?`dotfiles`:e.id===`webdav`?`home`:`imap`],n=!!t?.enabled;return(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(_t,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:e.title})]}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:e.description}),(0,Z.jsxs)(`p`,{className:`mt-2 text-[11px] text-muted-foreground`,children:[`initialized: `,t?.initialized?`true`:`false`]})]}),(0,Z.jsx)(I2,{checked:n,disabled:se===`service:${e.id}`,onClick:()=>Re(e.id,n)})]})},e.id)})}),(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(D2,{workspaceId:H,enabled:!!(re?.imap?.enabled||re?.imapSync?.enabled)})})]}),x.status===`active`&&b===`policies`&&(0,Z.jsx)(n2,{workspaceId:H}),x.status===`active`&&b===`hooks`&&(0,Z.jsx)(`section`,{className:`rounded-lg border p-4`,children:(0,Z.jsx)(C0,{workspaceId:H,prefillRule:m,onPrefillConsumed:h,initialSection:a,initialRunsHandler:o,initialRunId:s})})]})}):(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Workspace not found`})}function Y2({workspaceName:e}){let{selected:t,setSelected:n,tree:r,setTree:i,toggle:a}=GS(),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null);return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Default folders`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Create a set of common folders with matching icons and colors.`}),(0,Z.jsx)(`div`,{className:`mt-3`,children:(0,Z.jsx)(KS,{selected:t,onToggle:a,tree:r,onTreeChange:i,disabled:o,idPrefix:`settings-default-folders`})}),(0,Z.jsxs)(`div`,{className:`mt-3 flex items-center gap-3`,children:[(0,Z.jsx)(Y,{type:`button`,size:`sm`,disabled:o||t.size===0,onClick:async()=>{s(!0),l(null);let{ok:i,failed:a}=await WS(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,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:c})]})]})}function X2({workspaceName:e,vectorSpaces:t,onDone:n}){let[r,i]=(0,X.useState)(null),[a,o]=(0,X.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:()=>Bk(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:()=>Uk(e)}]},{title:`Full-text (BM25)`,ops:[{key:`fts`,label:`Backfill`,description:`Index documents missing from the full-text table. Fast, skips already-indexed.`,fn:()=>Vk(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:()=>Vk(e,!0)},{key:`fts-optimize`,label:`Optimize`,description:`Compact fragments + prune old versions of the full-text table.`,fn:()=>Hk(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:()=>Hk(e,t)}))}]:[]];return(0,Z.jsxs)(`section`,{className:`rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`mb-1 flex items-center gap-2`,children:[(0,Z.jsx)(we,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Index maintenance`})]}),(0,Z.jsx)(`p`,{className:`mb-3 text-xs text-muted-foreground`,children:`Runs against this workspace. Reindex operations are idempotent.`}),(0,Z.jsx)(`div`,{className:`space-y-4`,children:c.map(e=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h3`,{className:`mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e.title}),(0,Z.jsx)(`div`,{className:`space-y-2`,children:e.ops.map(e=>(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,Z.jsxs)(Y,{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,Z.jsx)(we,{className:`mr-2 h-3 w-3 animate-spin`}),e.label]}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 basis-52 text-xs text-muted-foreground`,children:e.description})]},e.key))})]},e.title))}),a&&(0,Z.jsx)(`p`,{className:`mt-3 text-xs text-muted-foreground`,children:a})]})}var Z2=[{value:`documentRead`,label:`Read`},{value:`documentWrite`,label:`Write`},{value:`documentReadWrite`,label:`Read & write`}];function Q2(){let{contextId:e,tab:t}=ll(),[n]=Ou(),r=n.get(`ownerId`)||void 0,i=al(),{showToast:a}=Vr(),{selectEntity:o,openM2Drawer:s,closeM2:c}=zS(),l=Jm(),u=GT(t),d=r?`?ownerId=${encodeURIComponent(r)}`:``;(0,X.useEffect)(()=>{t!==u&&e&&i(`/contexts/${e}/settings/${u}${d}`,{replace:!0})},[t,u,e,d,i]);let[f,p]=(0,X.useState)(null),[m,h]=(0,X.useState)(!0),[g,_]=(0,X.useState)(!1),[v,y]=(0,X.useState)(!1),[b,x]=(0,X.useState)(``),[S,C]=(0,X.useState)(``),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(``),[O,k]=(0,X.useState)(``),[A,j]=(0,X.useState)(),[M,N]=(0,X.useState)([]),[P,ee]=(0,X.useState)(!1),[F,I]=(0,X.useState)(``),[L,R]=(0,X.useState)(Z2[0].value),[te,ne]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!e)return;let t=!1;return fs(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 z=(t=e)=>{t&&(ee(!0),Es(t).then(N).catch(()=>N([])).finally(()=>ee(!1)))};(0,X.useEffect)(()=>{if(u!==`shares`||!e)return;let t=!1;return Es(e).then(e=>{t||N(e)}).catch(()=>{t||N([])}),()=>{t=!0}},[u,e]);let re=async t=>{if(t.preventDefault(),e){_(!0);try{let t=await Go(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)}}},ie=async t=>{if(t.preventDefault(),e){_(!0);try{await Promise.all([qo(e,E.trim(),r,A),Qo(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)}}},ae=async()=>{if(e&&window.confirm(`Delete context "${e}"? This cannot be undone.`)){y(!0);try{await ys(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)}}},oe=async t=>{if(t.preventDefault(),!(!e||!F.trim())){ne(`grant`);try{await ws(e,F.trim(),L),I(``),z(),a({title:`Shared`,description:`Access granted to ${F.trim()}`})}catch(e){a({title:`Error`,description:e instanceof Error?e.message:`Failed to grant access`,variant:`destructive`})}finally{ne(null)}}},se=async t=>{if(e&&window.confirm(`Revoke ${t.userEmail}'s access to "${e}"?`)){ne(t.userEmail);try{await Ho(e,t.userEmail),z(),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{ne(null)}}};if(m)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Loading...`});if(!f)return(0,Z.jsx)(`div`,{className:`p-6 text-sm text-muted-foreground`,children:`Context not found`});let B=WT.find(e=>e.id===u),ce=`/contexts/${e}${d}`;return(0,Z.jsx)(`div`,{className:`h-full min-h-0 overflow-y-auto`,children:(0,Z.jsxs)(`div`,{className:`mx-auto max-w-3xl p-6 pb-12 max-md:px-4 max-md:pb-rail-stack`,children:[(0,Z.jsx)($x,{compact:!0,className:`mb-6 border-b pb-4`,title:`${B.label} - ${f.name||f.id}`,description:B.description,backTo:ce,onBack:l?()=>s(`contexts`,`settings`,f.id):void 0}),u===`general`&&(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsxs)(`form`,{onSubmit:re,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Context ID`}),(0,Z.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,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-name`,className:`text-sm font-medium`,children:`Name`}),(0,Z.jsx)(q,{id:`ctx-name`,value:b,onChange:e=>x(e.target.value),placeholder:`My Context`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-description`,className:`text-sm font-medium`,children:`Description`}),(0,Z.jsx)(q,{id:`ctx-description`,value:S,onChange:e=>C(e.target.value),placeholder:`Optional description`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-color`,className:`text-sm font-medium`,children:`Color`}),(0,Z.jsxs)(`div`,{className:`mt-1 flex items-center gap-2`,children:[(0,Z.jsx)(q,{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,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:g||w===null,onClick:()=>T(null),children:`Use inherited color`})]}),(0,Z.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,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{className:`text-sm font-medium`,children:`Workspace`}),(0,Z.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,Z.jsx)(Y,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),(0,Z.jsxs)(`section`,{className:`rounded-lg border border-destructive/30 p-4`,children:[(0,Z.jsx)(`h2`,{className:`mb-3 text-sm font-semibold text-destructive`,children:`Danger Zone`}),(0,Z.jsxs)(Y,{variant:`destructive`,disabled:v,onClick:ae,children:[(0,Z.jsx)(lt,{className:`mr-2 h-4 w-4`}),v?`Deleting...`:`Delete Context`]})]})]}),u===`location`&&(0,Z.jsxs)(`form`,{onSubmit:ie,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`ctx-url`,className:`text-sm font-medium`,children:`URL`}),(0,Z.jsx)(DT,{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,Z.jsxs)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:[`Destination tree: `,A]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`label`,{htmlFor:`ctx-base-url`,className:`text-sm font-medium`,children:[`Base URL `,(0,Z.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional)`})]}),(0,Z.jsx)(DT,{id:`ctx-base-url`,value:O,onChange:k,fixedWorkspaceName:f.workspaceName,placeholder:`workspace://base/path`,pickerTitle:`Pick a base path…`})]}),(0,Z.jsx)(Y,{type:`submit`,disabled:g,children:g?`Saving...`:`Save Changes`})]}),u===`shares`&&(0,Z.jsxs)(`div`,{className:`space-y-4`,children:[(0,Z.jsxs)(`section`,{className:`space-y-3 rounded-lg border p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`People with access`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Only the context owner can see and change this list.`})]}),(0,Z.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>z(),disabled:P,children:[(0,Z.jsx)(we,{className:K(`mr-2 h-3.5 w-3.5`,P&&`animate-spin`)}),`Refresh`]})]}),M.length===0?(0,Z.jsx)(`div`,{className:`rounded-md border border-dashed p-4 text-sm text-muted-foreground`,children:`Not shared with anyone.`}):M.map(e=>(0,Z.jsxs)(`div`,{className:`flex items-start justify-between gap-3 rounded-md border p-3`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0`,children:[(0,Z.jsx)(`div`,{className:`truncate text-sm font-medium`,children:e.userEmail}),(0,Z.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[Z2.find(t=>t.value===e.accessLevel)?.label||e.accessLevel||`unknown access`,e.sharedAt&&` - since ${new Date(e.sharedAt).toLocaleDateString()}`]})]}),(0,Z.jsx)(Y,{type:`button`,variant:`outline`,size:`sm`,className:`text-destructive hover:text-destructive`,disabled:te===e.userEmail,onClick:()=>se(e),children:(0,Z.jsx)(pe,{className:`h-3.5 w-3.5`})})]},e.userEmail))]}),(0,Z.jsxs)(`form`,{onSubmit:oe,className:`space-y-4 rounded-lg border p-4`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Grant access`}),(0,Z.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`share-email`,className:`text-sm font-medium`,children:`User email`}),(0,Z.jsx)(q,{id:`share-email`,type:`email`,value:F,onChange:e=>I(e.target.value),placeholder:`person@example.com`}),(0,Z.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`The user must already have an account on this server.`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`share-level`,className:`text-sm font-medium`,children:`Access level`}),(0,Z.jsx)(`select`,{id:`share-level`,value:L,onChange:e=>R(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:Z2.map(e=>(0,Z.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),(0,Z.jsx)(Y,{type:`submit`,disabled:te===`grant`||!F.trim(),children:te===`grant`?`Sharing...`:`Share context`})]})]})]})})}function $2({status:e}){let t={running:{icon:ce,color:`text-success`,bg:`bg-success-subtle`,label:`Running`},stopped:{icon:be,color:`text-muted-foreground`,bg:`bg-muted`,label:`Stopped`},starting:{icon:cn,color:`text-info`,bg:`bg-info-subtle`,label:`Starting`},stopping:{icon:cn,color:`text-warning`,bg:`bg-warning-subtle`,label:`Stopping`},error:{icon:ve,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Error`},created:{icon:mt,color:`text-muted-foreground`,bg:`bg-muted`,label:`Created`},configured:{icon:mt,color:`text-info`,bg:`bg-info-subtle`,label:`Configured`},removed:{icon:be,color:`text-destructive`,bg:`bg-destructive-subtle`,label:`Removed`}},n=t[e]||t.created,r=n.icon;return(0,Z.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium ${n.bg} ${n.color}`,children:[(0,Z.jsx)(r,{className:`w-3 h-3`}),n.label]})}function e4(){let[e,t]=(0,X.useState)([]),[n,r]=(0,X.useState)(!0),[i,a]=(0,X.useState)(null),[o,s]=(0,X.useState)(null);Ff(()=>s(null),o!==null);let[c,l]=sS(),[u,d]=(0,X.useState)([]),[f,p]=(0,X.useState)([]),[m,h]=(0,X.useState)(``),[g,_]=(0,X.useState)(``),[v,y]=(0,X.useState)(``),[b,x]=(0,X.useState)(!1),{showToast:S}=Vr(),C=ld(),w=(0,X.useCallback)(async()=>{try{r(!0);let e=await $k.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,X.useEffect)(()=>{let e=()=>w();e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[w]),(0,X.useEffect)(()=>{c&&($k.listTemplates().then(e=>{let t=e.filter(e=>e.type===`workspace`);d(t),h(e=>e||t[0]?.id||``)}).catch(()=>d([])),Xr().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 $k.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 $k.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 $k.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 $k.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 $k.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,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)($x,{title:`My Roles`,description:`Manage your workspace roles and services`,actions:(0,Z.jsxs)(Z.Fragment,{children:[!c&&(0,Z.jsxs)(Y,{onClick:()=>l(!0),children:[(0,Z.jsx)(U,{className:`mr-2 h-4 w-4`}),`Create Role`]}),(0,Z.jsxs)(Y,{onClick:w,variant:`outline`,children:[(0,Z.jsx)(ar,{className:`mr-2 h-4 w-4`}),`Refresh`]})]})}),c&&(0,Z.jsx)(aS,{title:`Create New Role`,onClose:()=>l(!1),children:(0,Z.jsxs)(`form`,{onSubmit:T,className:`space-y-4`,children:[(0,Z.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-template`,className:`mb-1 block text-sm font-medium`,children:`Template`}),(0,Z.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,Z.jsx)(`option`,{value:``,children:`No workspace templates available`}),u.map(e=>(0,Z.jsxs)(`option`,{value:e.id,children:[e.name,` - `,e.description]},e.id))]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-name`,className:`mb-1 block text-sm font-medium`,children:`Role Name`}),(0,Z.jsx)(q,{id:`role-name`,value:g,onChange:e=>_(e.target.value),placeholder:`e.g., canvas-sshd`,disabled:b})]})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`label`,{htmlFor:`role-workspace`,className:`mb-1 block text-sm font-medium`,children:`Workspace`}),(0,Z.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,Z.jsx)(`option`,{value:``,children:`No workspaces available. Create one first.`}),f.map(e=>(0,Z.jsx)(`option`,{value:e.id,children:e.label||e.name},e.id))]})]}),(0,Z.jsxs)(Y,{type:`submit`,disabled:b||!m||!g.trim()||!v,children:[(0,Z.jsx)(U,{className:`mr-2 h-4 w-4`}),b?`Creating…`:`Create Role`]})]})}),n?(0,Z.jsx)(`div`,{className:`text-center py-8`,children:`Loading roles...`}):i?(0,Z.jsx)(`div`,{className:`text-center py-8 text-destructive`,children:i}):e.length===0?(0,Z.jsxs)(`div`,{className:`text-center py-12 border rounded-lg`,children:[(0,Z.jsx)(_t,{className:`w-12 h-12 mx-auto text-muted-foreground mb-4`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground`,children:`You don't have any workspace roles yet`}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground mt-2`,children:`Contact your administrator to set up roles for your workspaces`})]}):(0,Z.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:e.map(e=>(0,Z.jsxs)(`div`,{className:`border rounded-lg p-6 space-y-4 hover:shadow-elevation-2 transition-shadow`,children:[(0,Z.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,Z.jsxs)(`div`,{className:`flex-1`,children:[(0,Z.jsx)(`h3`,{className:`font-semibold text-lg`,children:e.name}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.template})]}),(0,Z.jsx)($2,{status:e.status})]}),e.container&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(_t,{className:`w-3 h-3`}),(0,Z.jsx)(`span`,{className:`truncate`,children:e.container.name})]})}),(0,Z.jsxs)(`div`,{className:`flex gap-2 pt-2`,children:[e.status===`stopped`||e.status===`created`?(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>E(e),className:`flex-1`,children:[(0,Z.jsx)(De,{className:`w-4 h-4 mr-2`}),`Start`]}):e.status===`running`?(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>D(e),className:`flex-1`,children:[(0,Z.jsx)(nn,{className:`w-4 h-4 mr-2`}),`Stop`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,onClick:()=>O(e),className:`flex-1`,children:[(0,Z.jsx)(ar,{className:`w-4 h-4 mr-2`}),`Restart`]})]}):(0,Z.jsxs)(Y,{size:`sm`,variant:`outline`,disabled:!0,className:`flex-1`,children:[(0,Z.jsx)(cn,{className:`w-4 h-4 mr-2`}),e.status]}),(0,Z.jsx)(Y,{size:`sm`,variant:`outline`,onClick:()=>k(e),title:`View Logs`,children:(0,Z.jsx)(wn,{className:`w-4 h-4`})})]})]},e.id))}),(0,Z.jsxs)(`div`,{className:`border-t pt-6`,children:[(0,Z.jsx)(`h2`,{className:`text-lg font-semibold mb-4`,children:`Global Services`}),(0,Z.jsxs)(`div`,{className:`text-sm text-muted-foreground space-y-2`,children:[(0,Z.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,Z.jsx)(`p`,{children:`To check the status of global services, contact your system administrator.`})]})]}),o&&(0,Z.jsx)(`div`,{className:`fixed inset-0 bg-scrim flex items-center justify-center z-50`,children:(0,Z.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,Z.jsxs)(`div`,{className:`p-6 border-b`,children:[(0,Z.jsxs)(`h2`,{className:`text-xl font-bold`,children:[o.role.name,` - Logs`]}),(0,Z.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.role.template})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto p-6`,children:(0,Z.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,Z.jsx)(`div`,{className:`text-muted-foreground`,children:`No logs available`}):(0,Z.jsx)(`pre`,{children:o.logs.join(`
|
|
93
93
|
`)})})}),(0,Z.jsx)(`div`,{className:`p-4 border-t flex justify-end`,children:(0,Z.jsx)(Y,{onClick:()=>s(null),children:`Close`})})]})})]})}function t4(){return(0,Z.jsxs)(`div`,{className:`space-y-6`,children:[(0,Z.jsx)($x,{title:`Remotes`,description:`Connect to remote Canvas instances`}),(0,Z.jsx)(`div`,{className:`flex flex-col items-center justify-center py-12 space-y-4`,children:(0,Z.jsxs)(`div`,{className:`text-center`,children:[(0,Z.jsx)(`h2`,{className:`text-2xl font-semibold mb-2`,children:`Coming Soon`}),(0,Z.jsx)(`p`,{className:`text-muted-foreground max-w-md`,children:`Remote connection management is currently under development. Check back later for updates.`})]})})]})}var n4=[`note`,`todo`,`link`,`file`,`photo`];function r4(){let{kind:e}=ll(),t=al();return e===`sketch`?(0,Z.jsx)(jl,{to:`/apps/sketch?add=1`,replace:!0}):!e||!n4.includes(e)?(0,Z.jsx)(jl,{to:`/home`,replace:!0}):(0,Z.jsx)(sT,{initialKind:e,onInitialCardClose:()=>t(`/home`)})}var i4=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Nl,{index:!0,element:(0,Z.jsx)(_T,{})},`r1`),(0,Z.jsx)(Nl,{path:`home`,element:(0,Z.jsx)(gT,{})},`r2`),(0,Z.jsx)(Nl,{path:`share-target`,element:(0,Z.jsx)(wT,{})},`r3`),(0,Z.jsx)(Nl,{path:`apps/add/:kind`,element:(0,Z.jsx)(r4,{})},`r4`),(0,Z.jsx)(Nl,{path:`workspaces`,element:(0,Z.jsx)(rC,{})},`r5`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName`,element:(0,Z.jsx)(lw,{})},`r6`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/documents/by-id/:documentId`,element:(0,Z.jsx)(pw,{})},`workspace-document-by-id`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/documents/:documentId`,element:(0,Z.jsx)(pw,{})},`workspace-document`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/documents/by-hash/:algo/:checksum`,element:(0,Z.jsx)(pw,{})},`workspace-document-by-hash`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/documents/by-checksum/:algo/:checksum`,element:(0,Z.jsx)(pw,{})},`workspace-document-by-checksum`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/settings`,element:(0,Z.jsx)(J2,{})},`r7`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/settings/:tab`,element:(0,Z.jsx)(J2,{})},`r8`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/path/*`,element:(0,Z.jsx)(lw,{})},`r9`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/trees/:treeName`,element:(0,Z.jsx)(lw,{})},`r10`),(0,Z.jsx)(Nl,{path:`workspaces/:workspaceName/trees/:treeName/path/*`,element:(0,Z.jsx)(lw,{})},`r11`),(0,Z.jsx)(Nl,{path:`contexts`,element:(0,Z.jsx)(OT,{})},`r12`),(0,Z.jsx)(Nl,{path:`contexts/:contextId`,element:(0,Z.jsx)(AT,{})},`r13`),(0,Z.jsx)(Nl,{path:`contexts/:contextId/settings`,element:(0,Z.jsx)(Q2,{})},`r14`),(0,Z.jsx)(Nl,{path:`contexts/:contextId/settings/:tab`,element:(0,Z.jsx)(Q2,{})},`r15`),(0,Z.jsx)(Nl,{path:`agents`,element:(0,Z.jsx)(DA,{})},`r16`),(0,Z.jsx)(Nl,{path:`agents/:agentId`,element:(0,Z.jsx)(UA,{})},`r17`),(0,Z.jsx)(Nl,{path:`agents/:agentId/:sessionId`,element:(0,Z.jsx)(UA,{})},`r18`),(0,Z.jsx)(Nl,{path:`agents/:agentId/settings`,element:(0,Z.jsx)(ZA,{})},`r19`),(0,Z.jsx)(Nl,{path:`agents/:agentId/settings/:tab`,element:(0,Z.jsx)(ZA,{})},`r20`),(0,Z.jsx)(Nl,{path:`roles`,element:(0,Z.jsx)(e4,{})},`r21`),(0,Z.jsx)(Nl,{path:`remotes`,element:(0,Z.jsx)(t4,{})},`r22`),(0,Z.jsx)(Nl,{path:`settings`,element:(0,Z.jsx)(PE,{})},`settings`),(0,Z.jsx)(Nl,{path:`appearance`,element:(0,Z.jsx)(eO,{})},`r23`),(0,Z.jsx)(Nl,{path:`key-bindings`,element:(0,Z.jsx)(lO,{})},`key-bindings`),(0,Z.jsx)(Nl,{path:`offline`,element:(0,Z.jsx)(JO,{})},`r24`),(0,Z.jsx)(Nl,{path:`about`,element:(0,Z.jsx)(ZO,{})},`r25`),(0,Z.jsx)(Nl,{path:`api-tokens`,element:(0,Z.jsx)(MT,{})},`r26`),(0,Z.jsx)(Nl,{path:`devices`,element:(0,Z.jsx)(BT,{})},`r27`),(0,Z.jsx)(Nl,{path:`embedding`,element:(0,Z.jsx)(Mk,{})},`r28`),(0,Z.jsx)(Nl,{path:`shared`,element:(0,Z.jsx)(Nk,{})},`r29`),(0,Z.jsx)(Nl,{path:`admin/users`,element:(0,Z.jsx)(rA,{})},`r30`),(0,Z.jsx)(Nl,{path:`admin/contexts`,element:(0,Z.jsx)(qk,{})},`r31`),(0,Z.jsx)(Nl,{path:`admin/workspaces`,element:(0,Z.jsx)(Kk,{})},`r32`),(0,Z.jsx)(Nl,{path:`admin/agents`,element:(0,Z.jsx)(Jk,{})},`r33`),(0,Z.jsx)(Nl,{path:`admin/logs`,element:(0,Z.jsx)(Qk,{})},`r34`),(0,Z.jsx)(Nl,{path:`admin/roles`,element:(0,Z.jsx)(nA,{})},`r35`),(0,Z.jsx)(Nl,{path:`admin/embedding`,element:(0,Z.jsx)(iA,{})},`r36`),(0,Z.jsx)(Nl,{path:`admin/auth`,element:(0,Z.jsx)(TA,{})},`r37`)]});function a4(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 o4(e){let t=2166136261;for(let n of e)t=Math.imul(t^n.charCodeAt(0),16777619);return`canvas:last-screen:${t>>>0}`}var s4=Il(i4),c4=e=>{let t=a4(e);return t&&Xs(s4,t)?t:null};function l4(){let e=nl(),[t]=(0,X.useState)(()=>{if(e.pathname!==`/`||e.search||e.hash)return null;try{let t=localStorage.getItem(`authToken`);return t?{key:e.key,path:c4(localStorage.getItem(o4(t)))||`/home`}:null}catch{return{key:e.key,path:`/home`}}}),n=t&&e.key===t.key&&e.pathname===`/`;return(0,X.useEffect)(()=>{if(n)return;let t=c4(e.pathname+e.search+e.hash);if(t)try{let e=localStorage.getItem(`authToken`);e&&localStorage.setItem(o4(e),t)}catch{}},[e.pathname,e.search,e.hash,n]),n?(0,Z.jsx)(jl,{to:t.path,replace:!0}):null}var u4={activeSection:null,m0Open:!1,m1Open:!1,m2Open:!1,m2View:null,selectedEntityId:null,user:null};function d4(e,t){switch(t.type){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`: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:t.m2View!==null,m2View:t.m2View};case`SET_USER`:return{...e,user:t.user};default:return e}}function f4({children:e}){let[t,n]=(0,X.useReducer)(d4,u4);VS(t,n),(0,X.useEffect)(()=>{let e=ld();if(e){n({type:`SET_USER`,user:e});return}let t=!1;return ud().then(e=>{!t&&e&&n({type:`SET_USER`,user:e})}).catch(()=>{}),()=>{t=!0}},[]);let r={state:t,dispatch:n,setSection:(0,X.useCallback)(e=>{n({type:`SET_SECTION`,section:e})},[]),toggleSection:(0,X.useCallback)(e=>{n({type:`TOGGLE_SECTION`,section:e})},[]),toggleM0:(0,X.useCallback)(()=>{n({type:`TOGGLE_M0`})},[]),closeM0:(0,X.useCallback)(()=>{n({type:`CLOSE_M0`})},[]),closeM1:(0,X.useCallback)(()=>{n({type:`CLOSE_M1`})},[]),openM2:(0,X.useCallback)((e,t)=>{n({type:`OPEN_M2`,view:e,entityId:t})},[]),openM2Drawer:(0,X.useCallback)((e,t,r)=>{n({type:`OPEN_M2_DRAWER`,section:e,view:t,entityId:r})},[]),openM1Drawer:(0,X.useCallback)(e=>{n({type:`OPEN_M1_DRAWER`,section:e})},[]),closeM2:(0,X.useCallback)(()=>{n({type:`CLOSE_M2`})},[]),selectEntity:(0,X.useCallback)(e=>{n({type:`SELECT_ENTITY`,entityId:e})},[])};return(0,Z.jsx)(RS.Provider,{value:r,children:e})}function p4(){return(0,X.useSyncExternalStore)(Pr,Er,()=>!1)}function m4(e,t){let n=null,r=!1,i,a;function o(){clearTimeout(i),!r&&Er()&&(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=Er();return Or(),(i||s)&&t(),!0}catch{return r||jr(),!1}finally{clearTimeout(c),n=null,o()}})(),n}let c=Pr(o),l=()=>{s()};return window.addEventListener(`online`,l),o(),{retry:s,stop(){r=!0,clearTimeout(i),a?.abort(),c(),window.removeEventListener(`online`,l)}}}var h4;function g4(){h4=m4(`${Rr}/ping`,()=>id.retryNow());let e=()=>{h4?.retry()},t=id.on(`connect_error`,e),n=id.on(`disconnect`,e);return()=>{t(),n(),h4?.stop(),h4=void 0}}function _4(){return h4?.retry(!0)??Promise.resolve(!1)}function v4(){let e=p4(),[t,n]=(0,X.useState)(!1);return e?(0,Z.jsxs)(`details`,{className:`relative`,children:[(0,Z.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,Z.jsx)(qe,{className:`h-5 w-5`})}),(0,Z.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,Z.jsx)(`p`,{className:`text-sm font-medium`,role:`status`,children:`Offline`}),(0,Z.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,Z.jsx)(`button`,{type:`button`,disabled:t,onClick:async()=>{n(!0);try{await _4()}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 y4=Ie,b4=E,x4=nr,S4=X.forwardRef(({className:e,sideOffset:t=4,...n},r)=>(0,Z.jsx)(or,{children:(0,Z.jsx)(St,{ref:r,sideOffset:t,className:K(`z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in 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})}));S4.displayName=St.displayName;var C4=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(pt,{ref:n,className:K(`relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full`,e),...t}));C4.displayName=pt.displayName;var w4=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(ur,{ref:n,className:K(`aspect-square h-full w-full`,e),...t}));w4.displayName=ur.displayName;var T4=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Zn,{ref:n,className:K(`flex h-full w-full items-center justify-center rounded-full bg-muted`,e),...t}));T4.displayName=Zn.displayName;function E4({section:e,icon:t,label:n,disabled:r}){let{state:i,toggleSection:a}=zS(),o=i.activeSection===e;return(0,Z.jsxs)(b4,{children:[(0,Z.jsx)(x4,{asChild:!0,children:(0,Z.jsxs)(`button`,{type:`button`,disabled:r,"aria-label":n,onClick:()=>!r&&e&&a(e),className:K(`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,Z.jsx)(`span`,{className:`absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-foreground rounded-l`}),t]})}),(0,Z.jsx)(S4,{side:`right`,sideOffset:8,children:n})]})}function D4({path:e,icon:t,label:n,section:r=`settings`}){let i=al(),{setSection:a}=zS();return(0,Z.jsxs)(b4,{children:[(0,Z.jsx)(x4,{asChild:!0,children:(0,Z.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,Z.jsx)(S4,{side:`right`,sideOffset:8,children:n})]})}function O4(){let{state:e,toggleM0:t}=zS(),n=p4();return(0,Z.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,Z.jsx)(Me,{className:`h-5 w-5`}):(0,Z.jsx)(yn,{className:`h-5 w-5`}),n&&(0,Z.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 k4(){let{state:e,closeM0:t,closeM1:n}=zS(),{state:r,setView:i,closeT1:a}=Os(),o=al(),{showToast:s}=Vr(),c=e.user?.userType===`admin`,l=Zx(),u=()=>{r.t1Open?a():i(`tools`),n(),t()},d=(0,X.useCallback)(async()=>{try{await J.post(`/auth/logout`),localStorage.removeItem(`authToken`),o(`/login`)}catch{s({title:`Error`,description:`Logout failed`,variant:`destructive`})}},[o,s]);return(0,Z.jsxs)(y4,{delayDuration:200,children:[e.m0Open&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-nav-scrim bg-scrim animate-fade-in md:hidden`,onClick:t,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{"data-shell":`rail`,className:K(`flex flex-col items-center w-rail h-full 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:rounded-[var(--panel-radius)] max-md:bg-card max-md:surface-glass max-md:shadow-elevation-5 max-md:animate-fade-in`:`max-md:hidden`),children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-center h-12 w-full shrink-0`,children:(0,Z.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,Z.jsx)(`img`,{src:`/images/logo-br_128x128.png`,alt:``,className:`w-6 h-6`})})}),(0,Z.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,Z.jsx)(E4,{section:`contexts`,icon:(0,Z.jsx)(Ct,{className:`w-5 h-5`}),label:`Contexts`}),(!l.local||l.workspace!==!1)&&(0,Z.jsx)(E4,{section:`workspaces`,icon:(0,Z.jsx)(dr,{className:`w-5 h-5`}),label:`Workspaces`}),(!l.local||l.agent)&&(0,Z.jsx)(E4,{section:`agents`,icon:(0,Z.jsx)(dt,{className:`w-5 h-5`}),label:`Agents`}),(!l.local||l.workspace!==!1)&&(0,Z.jsx)(D4,{path:`/roles`,section:null,icon:(0,Z.jsx)(Xn,{className:`w-5 h-5`}),label:`Roles`}),c&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`w-6 h-px bg-border my-2`}),(0,Z.jsx)(D4,{path:`/admin/users`,icon:(0,Z.jsx)(Ue,{className:`w-5 h-5`}),label:`All Users`}),(0,Z.jsx)(D4,{path:`/admin/logs`,icon:(0,Z.jsx)(wn,{className:`w-5 h-5`}),label:`Server Logs`}),(0,Z.jsx)(D4,{path:`/admin/workspaces`,icon:(0,Z.jsx)(ke,{className:`w-5 h-5`}),label:`All Workspaces`}),(0,Z.jsx)(D4,{path:`/admin/agents`,icon:(0,Z.jsx)(dt,{className:`w-5 h-5`}),label:`All Agents`}),(0,Z.jsx)(D4,{path:`/admin/roles`,icon:(0,Z.jsx)(Xn,{className:`w-5 h-5`}),label:`All Roles`})]})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-1 py-2 shrink-0`,children:[(0,Z.jsx)(`div`,{className:`w-6 h-px bg-border mb-2`}),(0,Z.jsx)(v4,{}),(0,Z.jsxs)(b4,{children:[(0,Z.jsx)(x4,{asChild:!0,children:(0,Z.jsx)(`button`,{type:`button`,onClick:u,"aria-label":r.t1Open?`Close toolbox`:`Open toolbox`,className:K(`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,Z.jsx)(mr,{className:`w-5 h-5`})})}),(0,Z.jsx)(S4,{side:`right`,sideOffset:8,children:`Toolbox`})]}),!l.local&&(0,Z.jsx)(D4,{path:`/settings`,section:`settings`,icon:(0,Z.jsx)(Qt,{className:`w-5 h-5`}),label:`Settings`}),(0,Z.jsxs)(b4,{children:[(0,Z.jsx)(x4,{asChild:!0,children:(0,Z.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,Z.jsx)(C4,{className:`h-7 w-7 touch-target`,children:(0,Z.jsx)(T4,{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,Z.jsx)(S4,{side:`right`,sideOffset:8,children:e.user?.email?.split(`@`)[0]||`Profile`})]}),(0,Z.jsxs)(b4,{children:[(0,Z.jsx)(x4,{asChild:!0,children:(0,Z.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,Z.jsx)(zn,{className:`w-5 h-5`})})}),(0,Z.jsx)(S4,{side:`right`,sideOffset:8,children:`Logout`})]})]})]})]})}function A4(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await ns();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch contexts:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useRef)(s);(0,X.useEffect)(()=>{c.current=s});let l=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>id.emit(`subscribe`,{channel:`context`}),r=()=>id.emit(`unsubscribe`,{channel:`context`}),i=id.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])=>id.on(e,t)),()=>{r(),i?.(),p.forEach(([e,t])=>id.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=e=>{let t=e.detail;n(e=>e.filter(e=>!Xo(e,t)))};return window.addEventListener(Yo,e),()=>window.removeEventListener(Yo,e)},[]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`contexts:refresh`,e),()=>window.removeEventListener(`contexts:refresh`,e)},[s]),{contexts:(0,X.useMemo)(()=>$S(t),[t]),isLoading:r,refresh:l}}function j4(){let{state:e,selectEntity:t,openM2:n,closeM2:r}=zS(),i=Jm(),{contexts:a,isLoading:o}=A4(e.activeSection===`contexts`),{showToast:s}=Vr(),l=al(),[u,d]=(0,X.useState)(null),f=u&&u.base===a?u.order:a,p=e=>e.isShared===!0||e.type===`shared`,{rowProps:m,handleProps:h,draggingIndex:g,insertLineClass:_}=nC((e,t)=>{let n=eC(f,e,t);d({base:a,order:n}),tC(n,(e,t)=>p(e)?Promise.resolve():Qo(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),l(`/contexts/${e.id}`)};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Contexts`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{r(),l(`/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,Z.jsx)(U,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:o&&a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):a.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No contexts found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:f.map((r,a)=>{let o=e.selectedEntityId===r.id,s=p(r),u=r.workspaceActive!==!1,d=hp(r.color);return(0,Z.jsxs)(`div`,{...m(a),"data-active":o||void 0,className:K(`group relative rounded-md py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,u?`cursor-pointer hover:shadow `+(o?`bg-accent shadow`:`bg-card hover:bg-accent/50`):`cursor-not-allowed opacity-50 bg-card`,_(a,f.length),g===a&&`opacity-60`),onClick:()=>u&&v(r),title:u?void 0:`Workspace "${r.workspaceName}" is not active`,children:[s?(0,Z.jsx)(`div`,{className:K(`absolute inset-y-0 right-0 w-4 rounded-r-md`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0}):(0,Z.jsx)(`button`,{type:`button`,...h(a),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:K(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-md active:cursor-grabbing`,!d&&`bg-muted`),style:d?{backgroundColor:d}:void 0,children:(0,Z.jsx)(Je,{className:K(`h-3.5 w-3.5`,gp(d))})}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(c,{icon:r.icon||`ph:stack-fill`,width:16,height:16,color:d,className:K(`mt-0.5 shrink-0`,!d&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate flex-1`,children:r.name||r.id}),s&&(0,Z.jsx)(`span`,{className:`rounded-full bg-info/10 px-1.5 py-0.5 text-[9px] text-info shrink-0`,children:`Shared`}),u&&(0,Z.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,Z.jsx)(Gt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),t(r.id),i?n(`settings`,r.id):l(`/contexts/${r.id}/settings/general`)},className:`reveal-on-hover shrink-0 mt-0.5`,title:`Settings`,children:(0,Z.jsx)(Qt,{className:`w-3.5 h-3.5 text-muted-foreground hover:text-foreground`})})]}),r.name&&(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground/60 truncate font-mono`,children:r.id}),(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5`,children:r.url||`/`}),r.ownerEmail&&(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground truncate mt-0.5`,children:r.ownerEmail})]},`${r.userId||`u`}-${r.id}`)})})})]})}function M4({title:e,onBack:t,action:n,className:r,icon:i,accentColor:a}){let{closeM1:o}=zS(),s=hp(a);return(0,Z.jsxs)(`div`,{className:K(`flex items-center h-12 px-2 border-b border-border shrink-0 gap-1`,r),style:{...s?{borderLeft:`6px solid ${s}`}:{},borderBottomWidth:3,...s?{borderBottomColor:s}:{}},children:[(0,Z.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`,children:[(0,Z.jsx)(oe,{className:`w-4 h-4 shrink-0`}),i&&(0,Z.jsx)(c,{icon:i,width:16,height:16,color:s,className:K(`mr-1 shrink-0`,!s&&`text-muted-foreground`)}),(0,Z.jsx)(`span`,{className:`text-sm font-semibold truncate`,children:e})]}),n&&(0,Z.jsx)(`div`,{className:`shrink-0`,children:n}),(0,Z.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,Z.jsx)(Me,{className:`w-4 h-4`})})]})}var N4=22,P4=44,F4=4;function I4(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 L4(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 R4({x:e,y:t,node:n,path:r,isBackendsTree:i,onClose:a,onShowContent:o,onOpenToSide:s,sourceLayer:c,targetLayers:l,clipboard:u,onStartInlineCreate:d,onChangeIcon:f,onNewCanvas:p,onShareCanvas:m,onRemove:h,onRename:g,onExportSubtree:_,onImportSubtree:v,onLock:y,onUnlock:x,onDestroy:S,onMerge:C,onSubtract:w,onMergeDown:T,onSubtractDown:E,onResyncBackend:D,onAddRule:O,onSyncFolderTree:k,onAddStoreRule:A,onStoragePolicy:j,onRenameBackendFolder:M,onDeleteBackendFolder:N,onRestoreTrash:P,onDiscardTrash:ee,onCopy:F,onCut:I,onPaste:L,pastedDocumentIds:te,onPasteDocuments:ne,isPinned:z,onTogglePin:re}){let ie=c&&l.size>0&&c.path===r,ae=!i&&(T||E)&&r!==`/`&&n.type!==`canvas`&&r.split(`/`).filter(Boolean).length>1,oe=c&&l.size>0&&(c.path===r||l.has(r)),se=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},B=(e,t,n,r=!1)=>(0,Z.jsxs)(`button`,{type:`button`,className:K(`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,Z.jsxs)(If,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[o&&B((0,Z.jsx)(lt,{className:`h-3 w-3`}),`Open Trash`,async()=>o(r)),r!==`/Trash`&&P&&B((0,Z.jsx)(He,{className:`h-3 w-3`}),`Restore original paths`,()=>P(r)),r!==`/Trash`&&ee&&B((0,Z.jsx)(lt,{className:`h-3 w-3`}),`Empty Trash`,()=>ee(r),!0)]}):(0,Z.jsxs)(If,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[o&&B((0,Z.jsx)(Vt,{className:`w-3 h-3`}),`Show layer content`,async()=>{o(r,n.id||void 0)}),s&&B((0,Z.jsx)(Vt,{className:`w-3 h-3`}),`Open to the side`,async()=>{s(r)}),(o||s)&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.type===`canvas`&&m&&B((0,Z.jsx)(_n,{className:`w-3 h-3`}),`Share canvas`,async()=>{await m(r)}),n.type===`canvas`&&m&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),D&&L4(r,i)&&(0,Z.jsxs)(Z.Fragment,{children:[B((0,Z.jsx)(we,{className:`w-3 h-3`}),`Resync backend (${L4(r,i)})`,async()=>{await D(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),i&&L4(r,i)&&(O||k||A)&&(0,Z.jsxs)(Z.Fragment,{children:[O&&B((0,Z.jsx)(ot,{className:`w-3 h-3`}),`Auto-Link documents to…`,async()=>{O(r)}),A&&I4(r,i)&&B((0,Z.jsx)(hr,{className:`w-3 h-3`}),`Create storage rule…`,async()=>{A(r)}),k&&B((0,Z.jsx)(Mn,{className:`w-3 h-3`}),`Sync folders into Directory`,async()=>{await k(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),!i&&(A||j)&&r!==`/`&&(0,Z.jsxs)(Z.Fragment,{children:[A&&B((0,Z.jsx)(hr,{className:`w-3 h-3`}),`Create rule…`,async()=>{A(r)}),A&&B((0,Z.jsx)(er,{className:`w-3 h-3`}),`Create download rule…`,async()=>{A(r,`download`)}),j&&n.type!==`canvas`&&B((0,Z.jsx)(ue,{className:`w-3 h-3`}),`Storage policy…`,async()=>{j(r)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`})]}),(!i||I4(r,i))&&(0,Z.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:()=>{d(r),a()},children:[(0,Z.jsx)(U,{className:`w-3 h-3`}),`New folder here`]}),M&&I4(r,i)?.key&&B((0,Z.jsx)(_r,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New folder name:`,e);!t||t===e||await M(r,t)}),N&&I4(r,i)?.key&&B((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Delete folder`,async()=>{confirm(`Delete folder "${r.split(`/`).pop()}" and its contents from the backend?`)&&await N(r)},!0),p&&!i&&(0,Z.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),a()},children:[(0,Z.jsx)($n,{className:`w-3 h-3 text-primary`}),`New canvas here…`]}),r!==`/`&&re&&B(z?(0,Z.jsx)(V,{className:`w-3 h-3`}):(0,Z.jsx)(R,{className:`w-3 h-3`}),z?`Unpin`:`Pin`,async()=>{await re()}),r!==`/`&&f&&(0,Z.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:()=>{f(),a()},children:[(0,Z.jsx)(Ke,{className:`w-3 h-3`}),`Change icon`]}),r!==`/`&&!n.locked&&g&&!i&&B((0,Z.jsx)(_r,{className:`w-3 h-3`}),`Rename`,async()=>{let e=r.split(`/`).pop()||``,t=prompt(`New name:`,e);!t||t===e||await g(r,t)}),(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),B((0,Z.jsx)(Ve,{className:`w-3 h-3`}),`Copy`,async()=>F(r)),!i&&B((0,Z.jsx)(lr,{className:`w-3 h-3`}),`Cut`,async()=>I(r)),u&&!i&&B((0,Z.jsx)(b,{className:`w-3 h-3`}),`Paste (${u.mode})`,async()=>L(r)),te&&te.length>0&&ne&&B((0,Z.jsx)(b,{className:`w-3 h-3`}),`Paste ${te.length} document(s)`,async()=>{await ne(r,te)}),(_||v)&&(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),_&&n.type!==`canvas`&&B((0,Z.jsx)(er,{className:`w-3 h-3`}),`Export subtree…`,()=>_(r)),v&&!i&&n.type!==`canvas`&&B((0,Z.jsx)(Mn,{className:`w-3 h-3`}),`Import subtree here…`,()=>v(r)),r!==`/`&&!n.locked&&h&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),B((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${r}"?`)&&await h(r,!1)},!0),B((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove recursive`,async()=>{confirm(`Remove "${r}" and all children?`)&&await h(r,!0)},!0),i&&(0,Z.jsxs)(Z.Fragment,{children:[B((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove and purge documents`,async()=>{confirm(`Remove "${r}" and all children, and PERMANENTLY purge every document under it from the index?`)&&await h(r,!0,!0)},!0),B((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Remove, purge and destroy on backend`,async()=>{confirm(`Remove "${r}" and all children, purge every document under it from the index, and PERMANENTLY DELETE the mirrored files/messages on the backend?`)&&await h(r,!0,!0,!0)},!0)]})]}),(y||x||S)&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),n.locked?x&&B((0,Z.jsx)(dn,{className:`w-3 h-3`}),`Unlock layer`,async()=>{await x(n.id)}):y&&B((0,Z.jsx)(Dt,{className:`w-3 h-3`}),`Lock layer`,async()=>{await y(n.id)}),n.locked&&n.lockedBy&&n.lockedBy.length>0&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2 px-3 py-1 text-xs`,children:[(0,Z.jsx)(`span`,{className:`truncate`,title:e,children:e}),x&&(0,Z.jsx)(`button`,{type:`button`,title:`Remove lock held by ${e}`,className:`shrink-0 text-muted-foreground hover:text-destructive`,onClick:()=>se(async()=>{await x(n.id,e)}),children:(0,Z.jsx)(dn,{className:`w-3 h-3`})})]},e))]}),r!==`/`&&!n.locked&&S&&B((0,Z.jsx)(lt,{className:`w-3 h-3`}),`Destroy layer`,async()=>{confirm(`Permanently destroy layer "${n.label||n.name}" and its bitmap?`)&&await S(n.id)},!0)]}),ae&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),T&&B((0,Z.jsx)(Yt,{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 T(r)}),E&&B((0,Z.jsx)(un,{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 E(r)})]}),ie&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),C&&B((0,Z.jsx)(Ct,{className:`w-3 h-3`}),`Merge this layer into ${l.size} selected`,async()=>{confirm(`Merge "${r}" (source) INTO:\n${Array.from(l.keys()).join(`
|
|
94
94
|
`)}\n\nThe selected layers gain this layer's documents. This layer is unchanged.`)&&await C(n.id,Array.from(l.values()))}),w&&B((0,Z.jsx)(Ct,{className:`w-3 h-3`}),`Subtract this layer from ${l.size} selected`,async()=>{confirm(`Subtract "${r}" (source) FROM:\n${Array.from(l.keys()).join(`
|
|
95
|
-
`)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await w(n.id,Array.from(l.values()))})]}),oe&&!ie&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`div`,{className:`px-3 py-1.5 text-[10px] text-muted-foreground italic`,children:[`This is a target. Right-click the source (`,c?.path,`) to merge/subtract`]})]})]})}function z4({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,X.useRef)(null);(0,X.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,Z.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 bg-card ring-1 ring-primary/50 shadow-elevation-3 text-sm font-medium`,children:[(0,Z.jsx)(Ye,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,Z.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 B4(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function V4(e,t,n){let r=B4(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>V4(e,r,n))??!1}function H4({node:e,parentPath:t,depth:n,isLast:r,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:f,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:P=!1,trail:ee=[]}){let F=Af(),I=B4(t,e.name),L=M?.(I)??null,R=S.get(I)??op(e),[te,ne]=(0,X.useState)(()=>i!==`/`&&(i===I||i.startsWith(I+`/`))),[z,re]=(0,X.useState)(i);if(z!==i&&(re(i),i!==`/`&&i.startsWith(I+`/`)&&ne(!0)),f&&!V4(e,t,f))return null;let ie=te||p===I||f.length>0,ae=e.children&&e.children.length>0,oe=i===I,se=a===I,B=l?.path===I,ce=u.has(I),V=e.type===`canvas`,le=t=>{if(t.ctrlKey||t.metaKey){_(I,e.id);return}if(t.shiftKey&&h){h(I);return}m(I)},de=[...ee].reverse().find(Boolean)??null,fe=R.color||de,pe=P?[...ee,fe]:ee,me=i!==`/`&&i.startsWith(I+`/`),he=!B&&!ce,ge=he&&oe,_e=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,ve=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,ye=Math.min(n,5),H=ie&&!!ae,be=n>0&&de?de:fe,U=he&&!ge&&!e.locked&&H,xe=be?Math.min(12+ye*5+(me?6:0),34):Math.min(ye*7+(me?5:0)+(se?3:0),30),Se=ge?`var(--primary)`:B?_e(`var(--info)`,22):ce?_e(`var(--warning)`,22):e.locked?_e(`var(--warning)`,20+ye*4):U?fe?_e(fe,84):_e(`var(--foreground)`,38):_e(be||`var(--foreground)`,xe),Ce=ge?`text-primary-foreground`:U&&fe?_p(fe):`text-foreground`,W=P&&ie&&ae&&n<F4,G=(0,Z.jsxs)(`div`,{"data-active":oe||void 0,className:K(`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]`,Ce,B&&`ring-1 ring-inset ring-info/40`,ce&&!B&&`ring-1 ring-inset ring-warning/40`,C===I&&!s&&!w&&`ring-2 ring-inset ring-info`,C===I&&!s&&w&&`ring-2 ring-inset ring-success`),style:{height:P4,background:Se,borderBottom:`1px solid ${ve(14)}`,...W?{position:`sticky`,top:n*P4,zIndex:20-n}:{}},draggable:!s&&!e.metadata?.backendTrash,onClick:le,...s?{}:F,onContextMenu:t=>{s||(t.preventDefault(),v(t,I,e))},onDragStart:e=>{s||T(I,e)},onDragEnter:e=>{s||E(I,e)},onDragOver:e=>{s||D(I,e)},onDragLeave:e=>O(I,e),onDragEnd:()=>k(),onDrop:e=>{s||A(I,e)},children:[ee.length>0&&(0,Z.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:ee.map((e,t)=>(0,Z.jsx)(`span`,{className:`w-[3px]`,style:{background:e||ve(28)}},t))}),(()=>{let t=R.color?{background:R.color}:de?{background:`color-mix(in oklab, ${de} 45%, transparent)`}:{background:ve(10)},n=(0,Z.jsx)(c,{icon:R.icon||(V?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:K(`shrink-0`,R.color?gp(R.color):ge?`text-primary-foreground`:U?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return x?(0,Z.jsx)(`button`,{type:`button`,className:r,style:t,title:`Change icon`,onClick:t=>{xr()||(t.stopPropagation(),x(t,I,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,I,e)},children:n}):(0,Z.jsx)(`span`,{className:r,style:t,children:n})})(),(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 self-center truncate px-2.5`,oe||me||H?`font-semibold`:`font-medium`),title:e.description||void 0,children:e.label||e.name}),N.has(I)&&(0,Z.jsx)(we,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":N.get(I)}),j?.has(I)&&(0,Z.jsx)(we,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),L&&(0,Z.jsx)(ue,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":L,children:(0,Z.jsx)(`title`,{children:L})}),!s&&(0,Z.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,I,e)},children:(0,Z.jsx)(Kt,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,className:K(`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!==I&&`invisible`),style:{borderLeft:`1px solid ${ve(16)}`},"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,title:ie?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,Z.jsx)(Ge,{className:`h-5 w-5`,strokeWidth:2.25}):(0,Z.jsx)(Ye,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,Z.jsxs)(`div`,{className:`relative`,children:[P?G:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${N4/2}px`,...r?{height:`1.375rem`}:{bottom:0}}}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${N4/2}px`,width:`${N4/2}px`}}),(0,Z.jsxs)(`div`,{"data-active":oe||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none 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`,B&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,ce&&!B&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!B&&!ce&&oe&&!e.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!B&&!ce&&oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!B&&!ce&&!oe&&se&&`bg-primary/[0.03] before:bg-transparent`,!B&&!ce&&!oe&&!se&&!e.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!B&&!ce&&!oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,C===I&&!s&&!w&&`ring-2 ring-info bg-info-subtle/50`,C===I&&!s&&w&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:R.color?`4px solid ${R.color}`:`4px solid transparent`},draggable:!s&&!e.metadata?.backendTrash,onClick:le,...s?{}:F,onContextMenu:t=>{s||(t.preventDefault(),v(t,I,e))},onDragStart:e=>{s||T(I,e)},onDragEnter:e=>{s||E(I,e)},onDragOver:e=>{s||D(I,e)},onDragLeave:e=>O(I,e),onDragEnd:()=>k(),onDrop:e=>{s||A(I,e)},children:[(0,Z.jsx)(`button`,{type:`button`,className:K(`shrink-0 text-muted-foreground hover:text-foreground`,!ae&&p!==I&&`invisible`),onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,Z.jsx)(Ge,{className:`w-4 h-4`}):(0,Z.jsx)(Ye,{className:`w-4 h-4`})}),(()=>{let t=(0,Z.jsx)(c,{icon:R.icon||(V?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:R.color||void 0,className:K(`shrink-0`,!R.color&&(V?`text-primary`:`text-muted-foreground`))});return x?(0,Z.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=>{xr()||(t.stopPropagation(),x(t,I,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,I,e)},children:t}):t})(),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name}),N.has(I)&&(0,Z.jsx)(we,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":N.get(I)}),j?.has(I)&&(0,Z.jsx)(we,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),L&&(0,Z.jsx)(ue,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":L,children:(0,Z.jsx)(`title`,{children:L})}),!s&&(0,Z.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,I,e)},children:(0,Z.jsx)(Kt,{className:`w-4 h-4`})})]})]}),ie&&(ae||p===I)&&(0,Z.jsxs)(`div`,{className:P?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[p===I&&(0,Z.jsx)(z4,{onConfirm:e=>y(I,e),onCancel:b}),e.children?.map((t,r)=>(0,Z.jsx)(H4,{node:t,parentPath:I,depth:n+1,isLast:r===(e.children?.length??0)-1,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:f,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:P,trail:pe},t.id||t.name))]})]})}function U4({root:e,treeName:t=`context`,isBackendsTree:n=!1,onRestoreTrash:r,onDiscardTrash:i,selectedPath:a,pendingPath:o,onSelect:s,isLoading:c=!1,readOnly:l=!1,onAddRule:u,onSyncFolderTree: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:P,onSubtractLayer:ee,onMergeDown:F,onSubtractDown:I,onResyncBackend:L,onCreateBackendFolder:R,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onUpdateNode:z,isPathPinned:re,onTogglePin:ie,searchQuery:ae=``,resyncingPaths:oe}){let se=bD(),[B,ce]=(0,X.useState)(null),[V,le]=(0,X.useState)(null),[ue,de]=(0,X.useState)(new Map),[fe,pe]=(0,X.useState)(null),[me,he]=(0,X.useState)(new Map),ge=(0,X.useRef)(new Set),_e=(0,X.useCallback)(async(e,t=!1,n=!1,r=!1)=>{if(!C||[...ge.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;ge.current.add(e);let i=r?`Removing documents and backend files…`:n?`Removing and purging documents…`:`Removing folder…`;he(t=>new Map(t).set(e,i));try{return await C(e,t,n,r)}finally{ge.current.delete(e),he(t=>{let n=new Map(t);return n.delete(e),n})}},[C]),[ve,ye]=(0,X.useState)(null),[H,be]=(0,X.useState)(new Map),[U,xe]=(0,X.useState)(e),Se=(0,X.useRef)(new Map),Ce=(0,X.useRef)(null),[W,G]=(0,X.useState)(null);if(e!==U){xe(e);let t=W;be(t?new Map([[t.path,t.style]]):new Map)}let[Te,Ee]=(0,X.useState)(null),[De,Oe]=(0,X.useState)(null),[ke,Ae]=(0,X.useState)(!1),[je,Me]=(0,X.useState)(!1),[Ne,Pe]=(0,X.useState)(!1),Fe=(0,X.useRef)(!1),Ie=(0,X.useRef)(null),Le=(0,X.useRef)(t),Re=(0,X.useRef)(!1),ze=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=e=>{ce(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,X.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||ze.current;Re.current=t,Ae(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let Be=(0,X.useCallback)((e,n,r)=>{if(rv(Le.current,e)||rv(t,n))return!1;if(Le.current!==t)return!0;let i=e.endsWith(`/`)?e.slice(0,-1):e,a=n.endsWith(`/`)?n.slice(0,-1):n,o=i.substring(0,i.lastIndexOf(`/`))||`/`;return!(a.startsWith(i+`/`)||i===a||!r&&a===o)},[t]),Ve=(0,X.useCallback)((e,n)=>{if(rv(t,e)){n.preventDefault();return}Ie.current=e,Le.current=t,n.dataTransfer.setData(`text/plain`,e),n.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:t})),n.dataTransfer.effectAllowed=`copyMove`},[t]),He=e=>e.ctrlKey||e.altKey||ze.current,Ue=(0,X.useCallback)((e,n)=>{if(rv(t,e))return;let r=Ie.current,i=He(n);i!==Re.current&&(Re.current=i,Ae(i)),!(r&&!Be(r,e,i))&&(n.preventDefault(),Oe(e))},[Be,t]),We=(0,X.useCallback)((e,n)=>{if(rv(t,e)){n.dataTransfer.dropEffect=`none`;return}let r=He(n);r!==Re.current&&(Re.current=r,Ae(r));let i=Ie.current;if(i&&!Be(i,e,r)){n.dataTransfer.dropEffect=`none`;return}n.preventDefault(),n.dataTransfer.dropEffect=r?`copy`:`move`},[Be,t]),Ke=(0,X.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||Oe(t=>t===e?null:t)},[]),qe=(0,X.useCallback)(()=>{Ie.current=null,Le.current=t,Re.current=!1,Ae(!1),Oe(null)},[t]),Je=(0,X.useCallback)(async(e,r)=>{if(r.preventDefault(),rv(t,e))return;let i=(()=>{try{return JSON.parse(r.dataTransfer.getData(`application/json`))}catch{return null}})();if(i?.type===`document`&&Array.isArray(i.documentIds)&&i.documentIds.length){if(Ie.current=null,Re.current=!1,Ae(!1),Oe(null),A)try{await A(e,i.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let a=(()=>{try{return JSON.parse(r.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),o=a?.path||r.dataTransfer.getData(`text/plain`),s=a?.treeName||Le.current||t;if(rv(s,o))return;let c=He(r)||Re.current;if(Ie.current=null,Le.current=t,Re.current=!1,Ae(!1),Oe(null),!o)return;let l=r.shiftKey,u=s!==t;if(!(!u&&o===e)&&!(!u&&!Be(o,e,c)))try{if(c&&E)await E(o,e,l,s,t);else if(!c&&T){let r=Fe.current&&!n&&!!F;await T(o,e,l,s,t,r?{mergeDown:r}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[Be,E,T,A,t,n,F]),Ye=ae.toLowerCase().trim(),Xe=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),pe({x:e.clientX,y:e.clientY,path:t,node:n})},[]),Ze=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(Ce.current=null,G(null),ye({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),Qe=(0,X.useCallback)(e=>{if(!ve||!z)return;let t=ve.path,n={...H.get(t)??(Ce.current?.path===t?Ce.current.style:op(ve.node)),...e};Ce.current={path:t,style:n},G({path:t,style:n}),be(e=>new Map(e).set(t,n));let r=cp(ve.node.metadata,n),i=Se.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),z(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[ve,z,H]),$e=(0,X.useCallback)((e,t)=>{V?e===V.path?(le(null),de(new Map)):de(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(le({path:e,id:t}),de(new Map))},[V]),et=(0,X.useCallback)(async e=>{!B||!T||!E||B.treeName===t&&(e===B.path||e.startsWith(B.path+`/`))||(B.mode===`cut`?(await T(B.path,e,!1,B.treeName,t),ce(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))):await E(B.path,e,!0,B.treeName,t))},[B,T,E,t]);(0,X.useEffect)(()=>{if(l)return;let e=e=>{let n=e.target;if(n?.tagName===`INPUT`||n?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),B?.mode===`cut`){et(a);return}let r={mode:`cut`,path:a,treeName:t};ce(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[B,et,l,a,t]);let tt=(0,X.useCallback)(async(e,t)=>{Ee(null);let r=e===`/`?`/${t}`:`${e}/${t}`;try{I4(e,n)&&R?await R(e,t)&&s(r):b&&await b(r,!0)&&s(r)}catch(e){alert(e instanceof Error?e.message:String(e))}},[b,R,s,n]),nt=(0,X.useCallback)(()=>{Ee(null)},[]),rt=(0,X.useCallback)((e,n)=>{let r={mode:n,path:e,treeName:t};ce(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))},[t]),it=(0,X.useCallback)(r=>{if(!(l||Vf(r.target)||a&&rv(t,a))){if(Bf(r,`Mod+V`)){k?.length&&A&&a?(r.preventDefault(),A(a,k).catch(()=>{})):B&&a&&(r.preventDefault(),et(a).catch(e=>alert(e instanceof Error?e.message:String(e))));return}if(a&&a!==`/`&&(Bf(r,`Mod+C`)||!n&&Bf(r,`Mod+X`))){r.preventDefault(),rt(a,r.key.toLowerCase()===`x`?`cut`:`copy`);return}if(C&&(r.key===`Delete`||r.key===`Backspace`)&&!(!a||a===`/`)){if(r.preventDefault(),Zr(e,a)?.locked){alert(`"${a}" is locked`);return}confirm(`Remove "${a}"?`)&&_e(a,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))}}},[l,C,_e,a,e,k,A,B,et,n,rt,t]),at=(0,X.useCallback)(()=>{Me(e=>{let t=!e;return ze.current=t,Re.current=t,Ae(t),t})},[]);if(c)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let ot=V||ue.size>0,st={accordion:se,selectedPath:a,pendingPath:o,contentPath:g,readOnly:l,sourceLayer:V,targetLayers:ue,clipboard:B,searchQuery:Ye,inlineCreateParent:Te,onSelect:s,onShiftSelect:y,onShowContent:_,onCtrl:$e,onCtxMenu:Xe,onConfirmCreate:tt,onCancelCreate:nt,onOpenPicker:z?Ze:void 0,styleOverrides:H,dragOverPath:De,isCopyDrag:ke,onDragStart:Ve,onDragEnter:Ue,onDragOver:We,onDragLeave:Ke,onDragEnd:qe,onDrop:Je,resyncingPaths:oe,policyBadgeFor:n?void 0:m,removingPaths:me};return(0,Z.jsxs)(`div`,{className:`px-3 py-2 space-y-1.5 outline-none`,tabIndex:0,onKeyDown:it,children:[me.size>0&&(0,Z.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-1 rounded-md border bg-muted/50 p-2 text-xs`,children:[...me].map(([e,t])=>(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(we,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block`,children:t}),(0,Z.jsx)(`span`,{className:`block truncate text-muted-foreground`,title:e,children:e})]})]},e))}),!l&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:at,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:K(`px-2 py-0.5 rounded-full border transition-colors select-none`,je?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:je?`Drag → Copy`:`Drag → Move`}),F&&!n&&!je&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>Pe(e=>(Fe.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:K(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,Ne?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:Ne?`+ merge down`:`merge down: off`})]}),ot&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:V?`Source: ${V.path} · ${ue.size} target(s)`:`Select source with ⌃-click`}),(0,Z.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{le(null),de(new Map)},children:`clear`})]}),(0,Z.jsxs)(`div`,{"data-active":a===`/`&&!g||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,a===`/`&&!g?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,De===`/`&&!l&&!ke&&`ring-2 ring-info bg-info-subtle/50`,De===`/`&&!l&&ke&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>s(`/`),onDragEnter:e=>{l||Ue(`/`,e)},onDragOver:e=>{l||We(`/`,e)},onDragLeave:e=>Ke(`/`,e),onDrop:e=>{l||Je(`/`,e)},onContextMenu:e=>{!l&&b&&(e.preventDefault(),pe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,Z.jsx)(Ge,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,h&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,h,`]`]})]}),!l&&b&&(0,Z.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(),pe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,Z.jsx)(Kt,{className:`w-4 h-4`})})]}),(0,Z.jsxs)(`div`,{className:se?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[Te===`/`&&(0,Z.jsx)(z4,{onConfirm:e=>tt(`/`,e),onCancel:nt}),e.children?.map((t,n)=>(0,Z.jsx)(H4,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...st},t.id||t.name)),!e.children?.length&&Te!==`/`&&(0,Z.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),fe&&(0,Z.jsx)(R4,{x:fe.x,y:fe.y,node:fe.node,path:fe.path,isBackendsTree:n,onClose:()=>pe(null),onShowContent:fe.node.metadata?.backendTrash?s:_,onRestoreTrash:l?void 0:r,onDiscardTrash:l?void 0:i,onOpenToSide:v?e=>v(e,t):void 0,sourceLayer:V,targetLayers:ue,clipboard:B,onStartInlineCreate:e=>Ee(e),onChangeIcon:z?()=>Ze({clientX:fe.x,clientY:fe.y,stopPropagation:()=>{}},fe.path,fe.node):void 0,onNewCanvas:x,onShareCanvas:S,onExportSubtree:D,onImportSubtree:l?void 0:O,onRemove:!l&&C&&![...me.keys()].some(e=>e===fe.path||e.startsWith(fe.path+`/`)||fe.path.startsWith(e+`/`))?_e:void 0,onRename:l?void 0:w,onLock:l?void 0:j,onUnlock:l?void 0:M,onDestroy:l?void 0:N,onMerge:l?void 0:P,onSubtract:l?void 0:ee,onMergeDown:l?void 0:F,onSubtractDown:l?void 0:I,onResyncBackend:L,onAddRule:u,onSyncFolderTree:d,onAddStoreRule:f,onStoragePolicy:!l&&!n?p:void 0,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onCopy:e=>rt(e,`copy`),onCut:e=>rt(e,`cut`),onPaste:et,pastedDocumentIds:k,onPasteDocuments:A,isPinned:re?re(fe.path):!1,onTogglePin:ie?()=>ie(fe.path,fe.node):void 0}),ve&&z&&(0,Z.jsx)(rS,{x:ve.x,y:ve.y,current:H.get(ve.path)??op(ve.node),onChange:Qe,onClose:()=>ye(null)})]})}function W4(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=zS(),a=Jm(),o=al(),s=e.selectedEntityId,{showToast:c}=Vr(),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(`/`),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(!1),k=(0,X.useCallback)(async e=>{w(!0);try{let t=await as(e);f(t),E(null)}catch(e){E(e instanceof Error?e.message:`Failed to load the tree`)}finally{w(!1)}},[]);(0,X.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await fs(e);if(t)return;u(n),m(n.url||``),g(void 0),v(``),S(null),b(n.path||`/`),w(!0);try{let n=await as(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=mv({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,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(M4,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,Z.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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})}),(0,Z.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(DT,{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:K(`text-xs transition-colors`,M&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,Z.jsx)(Y,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;O(!0);try{await qo(e,p,void 0,h);let t=await fs(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,Z.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,h,` · press Set to apply`]}),(0,Z.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,Z.jsx)(q,{"aria-label":`Search context tree`,placeholder:`Search paths…`,value:_,onChange:e=>v(e.target.value),className:`h-7 text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,Z.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,Z.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:T}),(0,Z.jsx)(U4,{root:d,searchQuery:_,selectedPath:y,pendingPath:x,onSelect:j,isLoading:C,rootLabel:l?.workspaceName,...A})]})]})}function G4({items:e,activeId:t,onSelect:n}){let[r,i]=(0,X.useState)(``),a=e.filter(e=>_S(r,e.label,e.description||``));return(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,Z.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,Z.jsx)(q,{type:`search`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,Z.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,Z.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:K(`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,Z.jsx)(`span`,{className:K(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,Z.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,Z.jsx)(Ye,{className:K(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}function K4(){let{state:e,closeM2:t}=zS(),n=Jm(),r=al(),i=nl(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return fs(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?GT(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,X.useMemo)(()=>WT.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,Z.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,Z.jsx)(gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(G4,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function q4(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Xr();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>id.emit(`subscribe`,{channel:`workspace`}),r=()=>id.emit(`unsubscribe`,{channel:`workspace`}),i=id.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])=>id.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>id.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,X.useMemo)(()=>$S(t),[t]),isLoading:r,refresh:c}}function J4({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function Y4(){let e=Zx(),{state:t,selectEntity:n,openM2:r,closeM2:i}=zS(),a=Jm(),{workspaces:o,isLoading:s}=q4(t.activeSection===`workspaces`),{showToast:l}=Vr(),u=al(),[d,f]=(0,X.useState)(new Set),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(new Map),_=(0,X.useRef)(new Map),[v,y]=(0,X.useState)(null),b=v&&v.base===o?v.order:o,{rowProps:x,handleProps:S,draggingIndex:C,insertLineClass:w}=nC((e,t)=>{let n=eC(b,e,t);y({base:o,order:n}),tC(n,(e,t)=>Ba(Qx(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&l({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),T=e=>h.get(Qx(e))??{icon:e.icon??void 0,color:e.color??void 0},E=(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),Ba(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>l({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},D=e=>{n(Qx(e)),r(`detail`,Qx(e)),!a&&pS(Qx(e))&&u(mS(Qx(e)))},O=async(e,t)=>{e.stopPropagation(),f(e=>new Set(e).add(Qx(t)));try{await Ua(Qx(t)),l({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{f(e=>{let n=new Set(e);return n.delete(Qx(t)),n})}},k=async(e,t)=>{e.stopPropagation(),f(e=>new Set(e).add(Qx(t)));try{await eo(Qx(t)),l({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{f(e=>{let n=new Set(e);return n.delete(Qx(t)),n})}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`}),!e.local&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i(),u(`/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,Z.jsx)(U,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:b.map((e,i)=>{let o=t.selectedEntityId===Qx(e),s=d.has(Qx(e)),l=e.status!==`active`,f=T(e),p=hp(f.color);return(0,Z.jsxs)(`div`,{...x(i),"data-active":o||void 0,className:K(`group relative rounded-md py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,o?`bg-accent shadow cursor-pointer hover:shadow`:l?`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:()=>{l||D(e)},children:[(0,Z.jsx)(`button`,{type:`button`,...S(i),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:K(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-md active:cursor-grabbing`,!p&&`bg-muted`),style:p?{backgroundColor:p}:void 0,children:(0,Z.jsx)(Je,{className:K(`h-3.5 w-3.5`,gp(p))})}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Change icon`,onClick:t=>{xr()||(t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Qx(e)}))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Qx(e)})},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,Z.jsx)(c,{icon:f.icon||`ph:stack-fill`,width:18,height:18,color:p,className:K(!p&&`text-muted-foreground`)})}),(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(J4,{status:e.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:s,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:`Stop`,children:(0,Z.jsx)(nn,{className:`w-3.5 h-3.5`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:s,onClick:t=>O(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,Z.jsx)(De,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(Qx(e)),a?r(`settings`,Qx(e)):u(`/workspaces/${Qx(e)}/settings/general`)},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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),p&&(()=>{let e=o.find(e=>Qx(e)===p.name);if(!e)return null;let t=T(e);return(0,Z.jsx)(rS,{x:p.x,y:p.y,current:t,onChange:e=>E(p.name,t,e),onClose:()=>m(null)})})()]})}function X4(e,t){let n=(0,X.useRef)(null),r=(0,X.useRef)(0);return(0,X.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=oO(e);if(!r)return;let i=iO(),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=cO(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 Z4(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 Q4(e,t,n,r=!1,i=`forward`,a=`copy`,o){let s=Z4(e,t,n,r);if(i===`forward`)return[s];let c=t.split(`/`).filter(Boolean);if(c.length<2||t.includes(`{{`)||c.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 l=o.address,u=o.key,d=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],f={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${d.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:d.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:l,folder:u,mode:a,autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[s,f]:[f]}function $4({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(`forward`),[u,d]=(0,X.useState)(`copy`),[f,p]=(0,X.useState)(0),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!0),[v]=(0,X.useState)(()=>`autolink-${crypto.randomUUID()}`),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(0),[k,A]=(0,X.useState)(0),[j,M]=(0,X.useState)(0),[N]=(0,X.useState)(Gv),[P,ee]=(0,X.useState)(1),[F,I]=(0,X.useState)(0),[L,R]=(0,X.useState)(),[te,ne]=(0,X.useState)(0);Ff(n,!x&&!o);let z=()=>{x||n()};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Hp,{onClose:z,children:(0,Z.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`autolink-title`,className:`${Vp} flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`h2`,{id:`autolink-title`,className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Gt,{className:`h-4 w-4`}),`Auto-Link folder`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:z,disabled:x,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Backend folder`}),(0,Z.jsx)(`p`,{className:`mt-1 break-words text-sm`,children:t})]}),(0,Z.jsxs)(`fieldset`,{disabled:x||y,className:`space-y-2 text-sm`,children:[(0,Z.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,Z.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>l(e.target.value),children:[(0,Z.jsx)(`option`,{value:`forward`,children:`Backend → virtual tree`}),(0,Z.jsx)(`option`,{value:`reverse`,children:`Virtual tree → backend`}),(0,Z.jsx)(`option`,{value:`both`,children:`Both`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link indexed files into your virtual paths. Files stay where they are.`:`Store files explicitly added to these virtual paths in the backend folder. Documents appearing through context filters are not copied.`}),c!==`forward`&&(0,Z.jsxs)(`details`,{children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer`,children:`Advanced: storage operation`}),(0,Z.jsxs)(`label`,{className:`mt-2 flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:u===`move`,onChange:e=>d(e.target.checked?`move`:`copy`)}),`Move instead of copy — release the source only after the destination is safely stored.`]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:`Virtual paths`}),i.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,Z.jsx)(`p`,{className:`break-words`,children:e.path})]}),!y&&(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:x,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),!y&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:x,onClick:()=>s(!0),children:[(0,Z.jsx)(U,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Choose a context path, a directory path, or both.`})]}),(0,Z.jsxs)(`fieldset`,{disabled:x||y,className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`mt-1`}),`Recursive — include subfolders and recreate their structure at each destination`]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Without Recursive, only direct folder contents are included. Context paths keep their usual layer membership. Both creates two independently manageable rules in workspace Rules. Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`}),x&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:y?`${P>1?`Rule ${Math.min(f+1,P)}/${P}: `:``}Processing ${F}${L===void 0?``:`/${L}`} existing documents… ${k} matches applied.`:`Saving Auto-Link…`}),C&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Auto-Link is enabled for future documents.`,g?` ${te} document${P>1?` checks across ${P} rules`:`s checked`}. ${k} matches applied.`:``]}),j>0&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[j,` document operations failed. Check the rule’s run log in Rules and rerun it after resolving the errors.`]}),T&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[y?`Auto-Link is enabled. `:``,T]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Z.jsx)(Y,{variant:`ghost`,disabled:x,onClick:r,children:`Manage rules`}),C?(0,Z.jsx)(Y,{onClick:n,children:`Done`}):(0,Z.jsx)(Y,{disabled:x||!i.length,onClick:async()=>{if(!x){S(!0),E(``);try{let n=c===`forward`?void 0:Jo(t,await Ta(e));if(n?.driver===`cacache`)throw Error(`Choose a backend that preserves folder paths.`);let r=Q4(v,t,i,m,c,u,n);if(ee(r.length),y||(await $v(e,r),b(!0)),g){for(let t=f;t<r.length;t++){let n=t===f?D:0;I(n),R(void 0);let i=await Jv(e,{ruleId:r[t].id,limit:1,offset:n,dryRun:!0});for(R(i.total);n!==null;){let i=await Jv(e,{ruleId:r[t].id,limit:N,offset:n});if(A(e=>e+i.matched-i.failed),M(e=>e+i.failed),I(n+i.processed),ne(e=>e+i.processed),R(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&&O(n)}p(t+1),O(0)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}w(!0)}catch(e){E(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{S(!1)}}},children:x?`Applying…`:y?`Retry existing documents`:`Enable Auto-Link`})]})]})}),o&&(0,Z.jsx)(Hp,{onClose:()=>s(!1),children:(0,Z.jsx)(Bp,{fixedWorkspaceName:e,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,onClose:()=>s(!1),onConfirm:(e,t)=>{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)}})})]})}async function e3(){return await J.get(`${Rr}/users/me/config/webui`)??{}}async function t3(e){return await J.put(`${Rr}/users/me/config/webui`,e)??e}var n3=`application/x-canvas-workspace-pin`;function r3({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:i,onShowInTree:a,onUnpin:o,onMove:s}){let[l,u]=(0,X.useState)(null),[d,f]=(0,X.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=()=>{u(null),f(null)},g=async()=>{let t=d,n=l;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,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,Z.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{l&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),l&&!d&&f({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=hp(e.color),s=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===po(e.tree,e.path),_=d?.id===e.id&&d.before,v=d?.id===e.id&&!d.before;return(0,Z.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(n3,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,u(e.id)},onDragEnd:h,onDragOver:t=>{if(!l||l===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;f(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:K(`group relative flex items-stretch gap-2.5 rounded-lg 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`,l===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,Z.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,Z.jsx)(at,{className:`w-5 h-5 text-warning`}):(0,Z.jsx)(c,{icon:s,width:22,height:22,color:n,className:K(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,Z.jsx)(Dt,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,Z.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.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,Z.jsx)(Mn,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(V,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Z.jsx)(Je,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,Z.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,Z.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,Z.jsx)(`p`,{children:`No pinned folders yet.`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,Z.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var i3=[`pins`,`context`,`layers`,`directory`,`backends`],a3=e=>typeof e==`string`&&i3.includes(e),o3=e=>{let t=Array.isArray(e)?e.filter(a3).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...i3.filter(e=>!t.includes(e))]},s3={pins:(0,Z.jsx)(R,{className:`w-3.5 h-3.5`}),context:(0,Z.jsx)(We,{className:`w-3.5 h-3.5`}),layers:(0,Z.jsx)(Ct,{className:`w-3.5 h-3.5`}),directory:(0,Z.jsx)(Mn,{className:`w-3.5 h-3.5`}),backends:(0,Z.jsx)(wt,{className:`w-3.5 h-3.5`})},c3={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},l3=e=>e===`directory`||e===`backends`?e:ao,u3=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function d3(){let{state:e}=zS();return e.selectedEntityId?(0,Z.jsx)(lC,{workspaceName:e.selectedEntityId,children:(0,Z.jsx)(f3,{},e.selectedEntityId)}):null}function f3(){let{state:e,closeM2:t,openM2:n}=zS(),r=s_(),i=Jm(),a=e.selectedEntityId,o=al(),s=nl(),{treeName:c,path:l}=nb(s.pathname),u=new URLSearchParams(s.search).get(`layer`)===`1`,d=new URLSearchParams(s.search).get(`layerId`),f=/\/trees\/|\/path(\/|$)/.test(s.pathname)||!!d,p=f?u3(c,d):i3[0],[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)({icon:null,color:null}),[b,x]=(0,X.useState)(p),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)([]),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(!1),[P,ee]=(0,X.useState)(!1),[F,I]=(0,X.useState)(!1),[L,R]=(0,X.useState)(l),[te,ne]=(0,X.useState)(new Set),[z,re]=(0,X.useState)(u&&l!==`/`?l:null),[ie,ae]=(0,X.useState)(``),[oe,se]=(0,X.useState)(null),[B,ce]=(0,X.useState)(null),[V,le]=(0,X.useState)(null),{policies:ue,refresh:de}=Q0(a),fe=(0,X.useCallback)(e=>{if(b!==`context`&&b!==`directory`||!ue.length)return null;let t=R0(ue,b,e);return t.length?`Storage policy targets: ${z0(t)} (see Settings for transfer status)`:null},[b,ue]),[pe,me]=(0,X.useState)([]),[he,ge]=(0,X.useState)(!1),[_e,ve]=(0,X.useState)(!1),ye=(0,X.useRef)(null),H=(0,X.useRef)(!1),[be,U]=(0,X.useState)(!1),[xe,Se]=(0,X.useState)(i3),Ce=!f;(0,X.useEffect)(()=>{let e=!1;return e3().then(t=>{if(e)return;let n=o3(t?.m2?.tabOrder);Se(n),Ce&&x(e=>e===i3[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let W=(0,X.useCallback)(async e=>{let t=xe;Se(e);try{let t=await e3();await t3({...t,m2:{...t.m2,tabOrder:e}})}catch{Se(t)}},[xe]),[G,we]=(0,X.useState)(null),[Te,Ee]=(0,X.useState)(null),De=()=>{we(null),Ee(null)},Oe=()=>{if(G&&Te&&G!==Te.id){let e=xe.filter(e=>e!==G),t=e.indexOf(Te.id);t>=0&&(e.splice(Te.before?t:t+1,0,G),e.some((e,t)=>e!==xe[t])&&W(e))}De()};(0,X.useEffect)(()=>{let e=e=>se(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[ke,Ae]=(0,X.useState)(l);l!==ke&&(Ae(l),R(l));let je=(0,X.useRef)(new Map),Me=(0,X.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();je.current.set(t,i);let a=()=>je.current.get(t)===i,o=t===`context`?j:t===`directory`?N:ee,s=t===`context`?C:t===`directory`?T:D;n||o(!0);try{n&&!r&&Sa(e,t);let i=await Gi(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ne=(0,X.useCallback)(async(e,t=!1)=>{let n=Symbol();je.current.set(`pins`,n);let r=()=>je.current.get(`pins`)===n;t||ge(!0);try{let t=await _o(e);r()&&me(t)}catch{}finally{r()&&ge(!1)}},[]),Pe=(0,X.useCallback)(async(e,t=!1)=>{let n=Symbol();je.current.set(`layers`,n);let r=()=>je.current.get(`layers`)===n;t||I(!0);try{let t=await Vi(e,`context`);r()&&k(t)}catch{}finally{r()&&I(!1)}},[]);(0,X.useEffect)(()=>{if(!a)return;let e=a,t=!1,n=je.current;async function r(){Zi(e).then(e=>{t||(h(e.label||null),_(e.id||null),y({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Me(e,`context`),Me(e,`directory`),Me(e,`backends`),Pe(e),Ne(e)])}return r(),()=>{t=!0,n.clear()}},[a,Me,Pe,Ne]);let Fe=(0,X.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Me(e,r,!0,n);(!t||t===`context`)&&Pe(e,!0),Ne(e,!0)},[Me,Pe,Ne]),Ie=(0,X.useCallback)(()=>{a&&Fe(a)},[a,Fe]);(0,X.useEffect)(()=>{if(!a)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==a||Fe(a,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[a,Fe]),(0,X.useEffect)(()=>{if(!a)return;let e=!1;return Ta(a).then(t=>{e||ne(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath)))}).catch(()=>{}),()=>{e=!0}},[a]),(0,X.useEffect)(()=>{if(!a)return;let e=[`workspace:${a}`,g?`workspace:${g}`:null].filter(Boolean),t=()=>e.forEach(e=>id.emit(`subscribe`,{channel:e})),n=id.on(`connect`,t);t();let r=tw(a,g),i=e=>{if(e?.workspaceId&&g&&e.workspaceId!==g)return;let t=e?.treePath;t&&ne(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};id.on(`backend.resync.changed`,i);let o=e=>{e?.workspaceId&&g&&e.workspaceId!==g||Ne(a,!0)};return id.on(`pins.changed`,o),()=>{r(),n?.(),id.off(`backend.resync.changed`,i),id.off(`pins.changed`,o)}},[a,g,Ne]);let[Le,Re]=(0,X.useState)(null),ze=`${s.pathname}|${s.search}`;if(ze!==Le){Re(ze);let{treeName:e,path:t}=nb(s.pathname),n=new URLSearchParams(s.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(s.pathname)||!!n;_e?ve(!1):x(r||be?r?u3(e,n):b:xe[0]),R(t),re(t===`/`?null:t)}let{showToast:Be,showProgress:Ve}=Vr(),He=(0,X.useCallback)(async e=>{if(!a)return!1;let t=Av(e);if(!t)throw Error(`Not a backend folder`);let n=Pv(await gv(a));if(!n)throw Error(`No backend-tree-sync hook in this workspace (Git/internal/hooks/started/). Recreate the seed hooks from Settings → Hooks.`);let r=await Yv(a,{hookFile:n,payload:{backend:t.backend,subdir:t.rel,target:jv(e)}});if(r.status===`error`)throw Error(r.error||`Sync failed`);return Be({title:`Folders synced`,description:`${t.backend}${t.rel?`/${t.rel}`:``} → ${jv(e)} (see Hooks → Runs)`}),Fe(a),!0},[a,Be,Fe]),Ue=mv({workspaceId:a??void 0,treeName:l3(b),onRefresh:Ie}),We=new Set(pe.map(e=>po(e.tree,e.path))),Ge=l3(b),Ke=(0,X.useCallback)(e=>We.has(po(Ge,e)),[pe,Ge]),qe=(0,X.useCallback)(async e=>{if(!a)return;let t=pe.find(t=>po(t.tree,t.path)===po(Ge,e));t?await xa(a,t.id):await gi(a,e,Ge),await Ne(a)},[a,pe,Ge,Ne]),Je=(0,X.useCallback)(async e=>{if(a){me(t=>t.filter(t=>t.id!==e.id));try{await xa(a,e.id)}finally{await Ne(a)}}},[a,Ne]),Ye=(0,X.useCallback)(async(e,t)=>{if(!a)return;let n=pe.find(t=>t.id===e);if(!n)return;let r=pe.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let o=[...r.slice(0,i),n,...r.slice(i)];if(!o.every((e,t)=>e===pe[t])){me(o);try{me(await Qa(a,o.map(e=>e.id)))}catch(e){throw await Ne(a),e}}},[a,pe,Ne]),Xe=(0,X.useCallback)(e=>{if(!a)return;ve(!0),R(e.path),re(null);let t=rb(a,e.path,e.tree);if(r){r.activateRow(`pin:${a}:${e.id}`,e.label||e.name||e.path,t);return}o(t)},[a,o,r]),Ze=(0,X.useCallback)(e=>{!a||e.resolvable===!1||(ve(!1),U(!0),x(u3(e.tree)),R(e.path),re(null),ae(``),H.current=!0,r?.setFocus(`main`),o(rb(a,e.path,e.tree)))},[a,o,r]),Qe=b===`context`?S:b===`directory`?w:b===`backends`?E:null,$e=b===`context`?A:b===`directory`?M:b===`backends`&&P;(0,X.useEffect)(()=>{if(!H.current||$e||b===`pins`)return;let e=ye.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),H.current=!1)},[b,L,Qe,$e]);let et=(0,X.useCallback)(e=>{U(!0),x(e),R(`/`),re(null),ae(``)},[]),tt=(0,X.useCallback)(e=>{et(sO(xe,b,e))},[xe,b,et]),nt=X4(e.m2Open,tt),rt=e=>{re(null),R(e);let t=l3(b);r?.setFocus(`main`),o(rb(a,e,t))},it=(0,X.useCallback)((e,t)=>{R(e),re(e);let n=l3(b),i=new URLSearchParams;i.set(`layer`,`1`),t&&i.set(`layerId`,t),r?.setFocus(`main`),o(`${rb(a,e,n)}?${i.toString()}`)},[a,b,o,r]),at=(0,X.useCallback)((e,t)=>{if(a){if(r){r.openCanvas({kind:`route`,location:rb(a,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:a,treeName:t,path:e}}))}},[a,r]),ot=(0,X.useCallback)(async e=>{if(!a)return;let t=l3(b),n=await ra(a,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[a,b]),st=ie.toLowerCase().trim(),ct=st?O.filter(e=>e.name.toLowerCase().includes(st)||(e.label||``).toLowerCase().includes(st)||(e.description||``).toLowerCase().includes(st)):O;return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(M4,{title:m||a||`Workspace`,icon:v.icon||`ph:stack-fill`,accentColor:v.color,onBack:t,action:(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a&&o(mS(a)),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,Z.jsx)(gn,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i?n(`settings`,a??null):o(`/workspaces/${a}/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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})]})}),(0,Z.jsx)(`div`,{...nt,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:xe.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>et(e),title:`${c3[e]} — drag to reorder; the first tab opens by default`,"aria-label":c3[e],"aria-pressed":b===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,we(e)},onDragEnd:De,onDragOver:t=>{if(!G||G===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;Ee(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),Oe()},className:K(`relative flex-1 flex items-center justify-center py-2 transition-colors`,b===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,G===e&&`opacity-40`,Te?.id===e&&Te.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Te?.id===e&&!Te.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[s3[e],e===`pins`&&pe.length>0&&(0,Z.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:pe.length})]},e))}),(0,Z.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,Z.jsx)(pr,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`input`,{className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:b===`layers`?`Search layers…`:b===`pins`?`Search pins…`:`Search paths…`,value:ie,onChange:e=>ae(e.target.value)})]})}),(0,Z.jsx)(`div`,{ref:ye,className:`flex-1 overflow-y-auto`,children:b===`pins`?(0,Z.jsx)(r3,{pins:pe,isLoading:he,searchQuery:ie,activeKey:po(c,l),onOpen:Xe,onShowInTree:Ze,onUnpin:Je,onMove:Ye}):b===`layers`?(0,Z.jsx)(y3,{layers:ct,isLoading:F,wsName:a??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),o(`${rb(a,`/`)}?${t.toString()}`)},onLock:async e=>{await Ma(a,e.id,a,`context`),Fe(a)},onUnlock:async e=>{await ga(a,e.id,a,`context`),Fe(a)},onRename:async(e,t)=>{await yi(a,e.id,t,`context`),Fe(a)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await Oi(a,e.id,`context`),Fe(a))}}):(0,Z.jsx)(U4,{root:Qe,treeName:b,isBackendsTree:b===`backends`,onRestoreTrash:a?e=>dv(a,e):void 0,onDiscardTrash:a?e=>pv(a,e):void 0,onShiftSelect:r?e=>at(e,l3(b)):void 0,selectedPath:L,contentPath:z,onSelect:rt,onShowContent:b===`context`?it:void 0,onOpenToSide:at,onShareCanvas:ot,onNewCanvas:a&&b!==`backends`?e=>{o(`${rb(a,e,b)}?createCanvas=1`)}:void 0,isLoading:$e,rootLabel:a??void 0,searchQuery:ie,resyncingPaths:b===`backends`?te:void 0,onAddRule:a&&b===`backends`?ce:void 0,onSyncFolderTree:a&&b===`backends`?He:void 0,onAddStoreRule:a?(e,t=`store`)=>{let n=b===`backends`?(()=>{let n=Av(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${b===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:Nv(e)};o(`/workspaces/${a}/settings/hooks?${Mv(n).toString()}`)}:void 0,onStoragePolicy:a&&(b===`context`||b===`directory`)?e=>le(k0(b,e)):void 0,policyBadgeFor:fe,pastedDocumentIds:oe?.documentIds,isPathPinned:Ke,onTogglePin:a?qe:void 0,onPasteDocuments:a&&b!==`backends`?async(e,t)=>{let n=b===`directory`?`directory`:`context`,r=b===`directory`?`directory`:ao,i=Ve({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),o=!1;try{o=await li(a,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(o?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),o&&(oe&&(se(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:a,path:e,treeName:r}}))),o}:void 0,...Ue})}),B&&a&&(0,Z.jsx)($4,{workspaceId:a,sourcePath:B,onClose:()=>ce(null),onManageRules:()=>{ce(null),o(`/workspaces/${a}/settings/hooks?section=rules`)}}),V&&a&&(0,Z.jsx)(U0,{workspaceId:a,path:V,onClose:()=>le(null),onSaved:()=>{de()}})]})}var p3={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}},m3=100,h3=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),g3=e=>p3[e]??{label:`${h3(e)} layers`,order:m3};function _3({type:e}){return e===`canvas`?(0,Z.jsx)($n,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Z.jsx)(wt,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Z.jsx)(Ct,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function v3(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:g3(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 y3({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,X.useState)(null),l=(0,X.useRef)(null);if((0,X.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,Z.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=v3(e);return(0,Z.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,Z.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,Z.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,Z.jsx)(`div`,{className:K(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,Z.jsx)(_3,{type:e.type}),s===e.id?(0,Z.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,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,Z.jsx)(Dt,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,Z.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,Z.jsx)(dn,{className:`w-3 h-3`})}):(0,Z.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,Z.jsx)(Dt,{className:`w-3 h-3`})}),!e.locked&&(0,Z.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,Z.jsx)(_r,{className:`w-3 h-3`})}),!e.locked&&(0,Z.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,Z.jsx)(lt,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function b3(){let{state:e,closeM2:t}=zS(),n=Jm(),r=al(),i=nl(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)({icon:null,color:null});(0,X.useEffect)(()=>{if(!a)return;let e=!1;return Zi(a).then(t=>{e||(s(t.label||null),l({icon:t.icon??null,color:t.color??null}))}).catch(()=>{}),()=>{e=!0}},[a]);let u=i.pathname.split(`/`).filter(Boolean),d=u[2]===`settings`?UT(u[3]):null,f=(0,X.useMemo)(()=>VT.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:`Settings: ${o||a||`Workspace`}`,icon:c.icon||`ph:stack-fill`,accentColor:c.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,Z.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,Z.jsx)(gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(G4,{items:f,activeId:d,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)})]})}function x3(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await lE();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>id.emit(`subscribe`,{channel:`agent`}),r=()=>id.emit(`unsubscribe`,{channel:`agent`}),i=id.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])=>id.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>id.off(e,t))}},[e,s]),(0,X.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 S3({status:e}){return(0,Z.jsx)(`span`,{className:K(`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 C3(){let e=Zx(),{state:t,selectEntity:n,openM2:r,closeM2:i}=zS(),a=Jm(),{agents:o,isLoading:s,refresh:c}=x3(t.activeSection===`agents`),{showToast:l}=Vr(),[u,d]=(0,X.useState)(new Set),f=al(),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 CE(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 wE(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,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`}),!e.local&&(0,Z.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,Z.jsx)(U,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No agents found`}):(0,Z.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,Z.jsxs)(`div`,{"data-active":i||void 0,className:K(`group relative rounded-md 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`}`,borderRadius:e.color?`6px 0 0 6px`:void 0},onClick:()=>p(e),children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(S3,{status:e.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Z.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,Z.jsx)(nn,{className:`w-3.5 h-3.5`})}):(0,Z.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,Z.jsx)(De,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description})]},e.id)})})})]})}function w3(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function T3(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function E3(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 D3(){let{state:e,closeM2:t}=zS(),n=e.selectedEntityId||``,r=al(),{showToast:i}=Vr(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{current:h,sessions:g,isLoading:_,error:v,refresh:y,create:b,select:x,rename:S,remove:C}=NA(n);(0,X.useEffect)(()=>{n&&(uE(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,X.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]),E=a?.name||n,D=e=>e?.slug||e?.id,O=e=>{let t=typeof e==`string`?e:D(e);r(t?`/agents/${encodeURIComponent(E)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(E)}`)},k=async()=>{try{let e=await b({mode:`persistent`,name:l.trim()||void 0});c(!1),u(``),O(E3(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create session`,variant:`destructive`})}},A=async()=>{try{let e=await b({mode:`experimental`});O(E3(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open experimental session`,variant:`destructive`})}},j=async()=>{try{await b({mode:`incognito`}),O()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open incognito session`,variant:`destructive`})}},M=async e=>{try{e.isExperimental?await x({mode:`experimental`}):await x({mode:`persistent`,sessionId:e.id}),O(e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}},P=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&&O(t||e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to rename session`,variant:`destructive`})}},ee=async e=>{if(!e.isExperimental&&window.confirm(`Delete session "${w3(e)}"?`))try{await C(e.id),O()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete session`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:a?.label||a?.name||n,onBack:t,action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(`/agents/${encodeURIComponent(E)}/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,Z.jsx)(Qt,{className:`h-3.5 w-3.5`})})}),(0,Z.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:g?.mode===`incognito`?`Incognito mode`:g?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:_,children:[(0,Z.jsx)(U,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:g?.mode===`experimental`?`default`:`outline`,onClick:A,disabled:_,children:[(0,Z.jsx)(N,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,Z.jsx)(Y,{size:`sm`,variant:g?.mode===`incognito`?`default`:`outline`,onClick:j,disabled:_,children:`Incognito`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[v&&(0,Z.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:v}),s&&(0,Z.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,Z.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),k()),e.key===`Escape`&&(c(!1),u(``))},placeholder:`Debugging auth`,className:`h-8`}),(0,Z.jsx)(Y,{size:`sm`,onClick:k,disabled:_,children:`Create`})]})]}),g?.sessions.length?(0,Z.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,Z.jsx)(`div`,{onClick:()=>M(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),M(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,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:p,onChange:e=>m(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),P(e)),t.key===`Escape`&&(f(null),m(``))},placeholder:`Session name`,className:`h-8`}),(0,Z.jsx)(Y,{size:`sm`,onClick:t=>{t.stopPropagation(),P(e)},disabled:!p.trim()||_,children:`Save`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:w3(e)}),e.isExperimental&&(0,Z.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:T3(e)})]})}),!n&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),m(e.name||w3(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,Z.jsx)(T,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),ee(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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-sm`,children:_?`Loading sessions...`:`No persistent sessions yet.`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),h?.mode===`incognito`&&(0,Z.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 O3(){let{state:e,closeM2:t}=zS(),n=Jm(),r=al(),i=nl(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return uE(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?qT(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,X.useMemo)(()=>KT.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,Z.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,Z.jsx)(gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(G4,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function k3(){let e=nl(),{state:t}=zS(),[n,r]=(0,X.useState)(``),i=(0,X.useRef)(null);(0,X.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=hS.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>_S(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,Z.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`}),(0,Z.jsx)(q,{type:`search`,"aria-label":`Search settings menu`,placeholder:`Find a setting…`,value:n,onChange:e=>r(e.target.value)})]}),(0,Z.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,Z.jsxs)(`section`,{"aria-label":t.label,children:[(0,Z.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,Z.jsxs)(Su,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:K(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,Z.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,Z.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var A3=280,j3=220,M3=560;function N3(){let{state:e}=zS(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,Z.jsx)(K4,{});if(n===`detail`)return(0,Z.jsx)(W4,{})}if(t===`workspaces`){if(n===`settings`)return(0,Z.jsx)(b3,{});if(n===`detail`)return(0,Z.jsx)(d3,{})}if(t===`agents`){if(n===`settings`)return(0,Z.jsx)(O3,{});if(n===`detail`)return(0,Z.jsx)(D3,{})}return null}function P3(){let{state:e,closeM1:t,closeM2:n}=zS();Ff(t,e.m1Open&&!e.m2Open),Ff(n,e.m2Open);let r=Jm(),[i,a]=(0,X.useState)(A3),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(null),l=(0,X.useCallback)(e=>{e.preventDefault(),s(!0),c.current={startX:e.clientX,startWidth:i};let t=e=>{if(!c.current)return;let t=e.clientX-c.current.startX,n=Math.min(M3,Math.max(j3,c.current.startWidth+t));a(n)},n=()=>{c.current=null,s(!1),window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[i]),u=r&&e.m1Open;return(0,Z.jsxs)(Z.Fragment,{children:[u&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:e.m1Open&&!u?{width:i}:void 0,className:K(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!o&&!u&&`transition-[width] duration-200 ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,u?`fixed bottom-2 left-[calc(0.5rem+var(--spacing-rail)+0.5rem)] right-2 top-2 z-40 shadow-elevation-5 animate-fade-in`:`relative`),children:[(0,Z.jsxs)(`div`,{className:K(`absolute inset-0 flex flex-col transition-opacity duration-200 ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:u?void 0:{minWidth:i},children:[e.activeSection===`contexts`&&(0,Z.jsx)(j4,{}),e.activeSection===`workspaces`&&(0,Z.jsx)(Y4,{}),e.activeSection===`agents`&&(0,Z.jsx)(C3,{}),e.activeSection===`admin`&&(0,Z.jsx)(k3,{}),e.activeSection===`settings`&&(0,Z.jsx)(k3,{})]}),(0,Z.jsx)(`div`,{className:K(`absolute inset-0 z-10 bg-card flex flex-col transition-transform duration-200 ease-out`,e.m2Open?`translate-x-0`:`translate-x-full`),children:e.m2Open&&(0,Z.jsx)(N3,{})}),e.m1Open&&!u&&(0,Z.jsx)(`div`,{onMouseDown:l,className:`absolute right-0 top-0 bottom-0 z-20 w-1 cursor-col-resize hover:bg-primary/20 transition-colors`})]})]})}var F3=`canvas:readerWidth`,I3=320,L3=1600;function R3(){try{let e=Number(sessionStorage.getItem(F3));return Number.isFinite(e)&&e>=I3&&e<=L3?e:null}catch{return null}}var z3=R3(),B3=new Set;function V3(e){return B3.add(e),()=>{B3.delete(e)}}function H3(e){z3=e===null?null:Math.round(Math.max(I3,Math.min(L3,e)));try{z3===null?sessionStorage.removeItem(F3):sessionStorage.setItem(F3,String(z3))}catch{}B3.forEach(e=>e())}function U3(){return(0,X.useSyncExternalStore)(V3,()=>z3,()=>null)}var W3=320,G3=1600;function K3({edge:e}){let t=U3(),n=(0,X.useRef)(null),r=e===`left`?-1:1;return(0,Z.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":W3,"aria-valuemax":G3,"aria-valuenow":t??560,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)-240:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(W3,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&H3(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:()=>H3(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`?H3(null):H3(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function q3(e){return e.schema===`data/schema/note`?xn:e.schema===`data/schema/tab`?Xt:e.schema===`data/schema/file`?bt:e.schema===`data/schema/message/email`?Cn:fn}function J3({entry:e,onClose:t,frame:n}={}){let r=hm(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=M_(i?.workspaceId,i?.document??null);if(!i||!o)return null;let{workspaceId:c}=i;return(0,Z.jsx)(Ew,{title:Ui(o).title,icon:q3(o),onClose:a,onSave:async e=>(await li(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:ng(o)===oh,children:(0,Z.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,Z.jsx)(j_,{document:o,workspaceId:c,onChanged:s,compact:!0},`${c}:${o.id}`)})})}function Y3(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function X3(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`].includes(t)&&!!n}var Z3=`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:pr-0 max-md:rounded-2xl max-md:shadow-elevation-5 max-md:animate-fade-in`,Q3=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function $3(){let e=U3(),{pathname:t}=nl(),n=X3(t),r=Y3(t),{entry:i,close:a}=hm();return(0,Z.jsx)(`div`,{className:K(`relative flex flex-col flex-1 min-w-0`,!r&&`surface-sheet`),children:(0,Z.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,Z.jsx)(`main`,{id:`content-area`,className:K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!n&&!r&&`p-page max-md:pb-rail-stack`),children:(0,Z.jsx)(Ml,{})}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:Q3,onClick:a,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??560}px`,"--document-card-width":`100%`},className:K(`relative flex shrink-0 items-stretch py-2 pr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_240px)]`,Z3),children:[(0,Z.jsx)(K3,{edge:`left`}),(0,Z.jsx)(J3,{})]})]})]})})}function e6(){let{state:e,setView:t}=Os(),{pathname:n}=nl();return e.t1Open||e.addOpen||!Y3(n)?null:(0,Z.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,Z.jsx)(kt,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var t6={current:null,sessions:null,isLoading:!1,error:null};function n6(e){return e instanceof Error?e.message:`Session request failed`}function r6({children:e}){let[t,n]=(0,X.useState)({}),r=(0,X.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||t6,...t}}))},[]),i=(0,X.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,X.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([dE(e),fE(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}}},[r]),o=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await pE(e,t))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),s=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await mE(e,t))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),c=(0,X.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await hE(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),l=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await gE(e,t))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),u=(0,X.useMemo)(()=>({getState:e=>t[e]||t6,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,Z.jsx)(MA.Provider,{value:u,children:e})}var i6=`data/schema/`,a6={"data/schema/file":{label:`Files`,icon:wn},"data/schema/note":{label:`Notes`,icon:xn},"data/schema/task":{label:`Todos`,icon:On},"data/schema/tab":{label:`Tabs`,icon:ae},"data/schema/message/email":{label:`Emails`,icon:Cn},"data/schema/link":{label:`Links`,icon:Xt},"data/schema/identity":{label:`Identities`,icon:Ze},"data/schema/drawing":{label:`Sketches`,icon:rt}};function o6(e){return a6[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:h}}function s6(e){return a6[e]?.icon??h}function c6(e){return{...e,lens:L_.lens}}function l6(e,t,n=!1){let r=n?e=>e:c6;return JSON.stringify(r(e))!==JSON.stringify(r(t??L_))}var u6={savedGeoSelection:null,liveEnabled:!1,liveError:null,t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,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:L_,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function d6(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,addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,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`?l6(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`?l6(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:L_,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:l6(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??L_;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?l6(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 f6=`toolbox:session:filters`;function p6(){try{let e=localStorage.getItem(f6);if(!e)return null;let t=JSON.parse(e);return{...L_,...t,features:{...L_.features,...t.features??{}},timeline:{...L_.timeline,...t.timeline??{}},geo:{...L_.geo,...t.geo??{}},lens:L_.lens,sort:I_(t.sort)}}catch{return null}}function m6(e){try{localStorage.setItem(f6,JSON.stringify(c6(e)))}catch{}}function h6(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?{...L_.lens,...n.lens??{}}:L_.lens,sort:I_(n.sort)}}catch{return null}}function g6(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 _6({children:e}){let[t,n]=(0,X.useReducer)(d6,u6),r=nl(),i=al(),a=new URLSearchParams(r.search).get(`ownerId`)||void 0,o=(0,X.useRef)(null),s=(0,X.useRef)(t);(0,X.useEffect)(()=>{s.current=t}),(0,X.useEffect)(()=>{let e=!1,t=r.pathname.split(`/`).filter(Boolean),i=t[0]===`workspaces`&&t[1]||null,a=t[0]===`contexts`&&t[1]||null,{path:o,treeName:c}=i?nb(r.pathname):{path:`/`,treeName:``},l=t=>{if(e)return;let r=t?`canvas`:a?`context`:null,l=s.current;l.activeContextType!==null&&r===null&&m6(l.filters),n({type:`SET_NAVIGATION`,workspaceName:i,treeName:i?c:null,canvasId:t,contextId:a,contextType:r,contextPath:i?o:null})};return i&&o!==`/`?(Gi(i,c).then(t=>{if(e)return;let n=g6(t,o);l(n?.type===`canvas`?n.id:null)}).catch(()=>l(null)),()=>{e=!0}):(l(null),()=>{e=!0})},[r.pathname]),(0,X.useEffect)(()=>{let e=t.activeWorkspaceName;e&&(n({type:`SET_BITMAPS_LOADING`,loading:!0}),So(e).then(e=>{n({type:`SET_BITMAPS`,keys:e})}))},[t.activeWorkspaceName]),(0,X.useEffect)(()=>{let e=t.activeWorkspaceName;e&&(n({type:`SET_TIMELINES_LOADING`,loading:!0}),Ai(e).then(e=>{n({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[t.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeCanvasId:r,activeWorkspaceName:i,activeTreeName:a,activeContextPath:o}=t;if(e!==`context`){if(e===`canvas`&&r&&i&&o)Gi(i,a||`context`).then(e=>{let t=g6(e,o),r=h6(t?.metadata);n({type:`SET_SAVED_FILTERS`,savedFilters:r,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{n({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=p6();n({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[t.activeCanvasId,t.activeContextPath,t.activeContextType,t.activeTreeName,t.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeContextId:c}=t;if(e!==`context`||!c)return;let l=!1;o.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();i(`${r.pathname}${n?`?${n}`:``}`,{replace:!0})},f=(e,t,r,i=null,a=r?[r]:[])=>{let s=e?.filters??t??L_,c=e?.geoSelection??i;o.current=JSON.stringify({filters:s,geoSelection:c,queries:e?.queries??a}),n({type:`SET_SAVED_FILTERS`,savedFilters:t,savedSearchQuery:r}),n({type:`SET_FILTERS`,filters:s}),n({type:`SET_GEO_SELECTION`,selection:c}),n({type:`SET_SAVED_GEO_SELECTION`,selection:i}),n({type:`SET_LIVE`,enabled:e!==null}),d(e?.queries??a)},p=e=>{let t=++u;return fs(c,a).then(r=>{if(l||t!==u)return;let i=r.metadata,a=h6(i,!0),c=typeof i?.toolboxSearchQuery==`string`?i.toolboxSearchQuery:null;if(n({type:`SET_CONTEXT_SCOPE`,workspaceName:r.workspaceName||r.workspaceId||null,contextPath:r.path||`/`,treeId:r.treeId||null}),r.liveQuery)f(r.liveQuery,a,c,i?.toolboxGeoSelection??null,r.queryOptions?.queries);else if(e){n({type:`SET_LIVE`,enabled:!1});let e=s.current.isDirty?s.current.filters:a??L_,t=i?.toolboxGeoSelection??null;o.current=JSON.stringify({filters:e,geoSelection:t,queries:[]}),n({type:`SET_SAVED_FILTERS`,savedFilters:a,savedSearchQuery:c,hydrating:!0}),n({type:`SET_GEO_SELECTION`,selection:t}),n({type:`SET_SAVED_GEO_SELECTION`,selection:t});let l=new URLSearchParams(window.location.search),u=r.queryOptions?.queries?.length?r.queryOptions.queries:c?[c]:[];!l.has(`q`)&&!l.has(`search`)&&u.length&&d(u)}}).catch(e=>{l||t!==u||n({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not load context`})})};p(!0);let m=()=>{p(!1)},h=id.on(`context.url.set`,e=>{e?.id===c&&m()}),g=id.on(`context.updated`,e=>{let t=e;if((t.contextId||t.id)!==c)return;if(!t.metadata){p(!0);return}++u;let n=h6(t.metadata,!0);f(t.liveQuery??null,n,typeof t.metadata.toolboxSearchQuery==`string`?t.metadata.toolboxSearchQuery:null,t.metadata.toolboxGeoSelection??null,t.queryOptions?.queries)}),_=id.on(`connect`,()=>{p(!0)}),v=id.on(`disconnect`,()=>{s.current.liveEnabled&&n({type:`SET_LIVE_ERROR`,error:`Disconnected — Live updates will resume when connected.`})});return window.addEventListener(`contexts:refresh`,m),()=>{l=!0,o.current=null,h(),g(),_(),v(),window.removeEventListener(`contexts:refresh`,m)}},[t.activeContextId,t.activeContextType,a]);let c=(0,X.useMemo)(()=>{let e=new URLSearchParams(r.search),t=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),n=(e.get(`search`)||``).trim();return t.length?t:n?[n]:[]},[r.search]),l=(0,X.useRef)(c);(0,X.useEffect)(()=>{l.current=c},[c]);let u=(0,X.useRef)(!1),d=(0,X.useRef)(null),[f,p]=(0,X.useState)(0);(0,X.useEffect)(()=>()=>{d.current!==null&&window.clearTimeout(d.current),d.current=null},[t.activeContextType,t.activeContextId,t.liveEnabled,a]),(0,X.useEffect)(()=>{t.activeContextType!==`context`||!t.activeContextId||a||!t.liveEnabled||o.current===null||u.current||d.current!==null||!id.isConnected()||JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:c})!==o.current&&(d.current=window.setTimeout(()=>{d.current=null;let e=s.current;if(e.activeContextId!==t.activeContextId||!e.liveEnabled)return;let r=l.current,i=JSON.stringify({filters:e.filters,geoSelection:e.geoSelection,queries:r});if(i===o.current)return;let a=o.current;u.current=!0;let c={filters:e.filters,geoSelection:e.geoSelection,queries:r,binding:H_(e.filters,e.geoSelection,r)};id.request(`context.filters.set`,{contextId:e.activeContextId,liveQuery:c}).then(()=>{s.current.activeContextId===e.activeContextId&&o.current===a&&(o.current=i,n({type:`SET_LIVE_ERROR`,error:null}))}).catch(t=>{s.current.activeContextId===e.activeContextId&&n({type:`SET_LIVE_ERROR`,error:t instanceof Error?t.message:`Live update failed`})}).finally(()=>{u.current=!1,p(e=>e+1)})},t.liveError?1500:100))},[t.activeContextType,t.activeContextId,t.liveEnabled,t.filters,t.geoSelection,c,a,f,t.liveError]);let m=(0,X.useCallback)(async e=>{let t=s.current;if(t.activeContextType!==`context`||!t.activeContextId||a)return;let r=c,i=e?{filters:t.filters,geoSelection:t.geoSelection,queries:r,binding:H_(t.filters,t.geoSelection,r)}:null;try{await id.request(`context.filters.set`,{contextId:t.activeContextId,liveQuery:i}),o.current=JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:r}),n({type:`SET_LIVE`,enabled:e})}catch(e){n({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not change Live mode`})}},[a,c]);(0,X.useEffect)(()=>{t.activeContextType===null&&m6(t.filters)},[t.filters,t.activeContextType]);let h=(0,X.useCallback)(e=>n({type:`SET_VIEW`,view:e}),[]),g=(0,X.useCallback)(e=>n({type:`TOGGLE_VIEW`,view:e}),[]),_=(0,X.useCallback)(()=>n({type:`CLOSE_T1`}),[]),v=(0,X.useCallback)(e=>n({type:`OPEN_T2_AGENT`,agentId:e}),[]),y=(0,X.useCallback)(()=>n({type:`CLOSE_T2`}),[]),b=(0,X.useCallback)(e=>n({type:`OPEN_ADD`,kind:e}),[]),x=(0,X.useCallback)(()=>n({type:`OPEN_ADD`,kind:null,relateTo:null}),[]),S=(0,X.useCallback)(e=>n({type:`OPEN_ADD`,kind:null,relateTo:e}),[]),C=(0,X.useCallback)(()=>n({type:`CLOSE_ADD`}),[]),w=(0,X.useCallback)((e,t)=>n({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),T=(0,X.useCallback)(e=>n({type:`SET_TOOLS_TAB`,tab:e}),[]),E=(0,X.useCallback)(e=>n({type:`SET_APPS_APPLET`,appletId:e}),[]),D=(0,X.useCallback)(e=>n({type:`SET_ACCENT_COLOR`,color:e}),[]),O=(0,X.useCallback)(e=>{n({type:`SET_FILTERS`,filters:e})},[]),k=(0,X.useCallback)((e,t)=>{let{filters:r}=s.current,i=e.startsWith(i6),a=i?r.features.allOf.filter(t=>t!==e):t?[...new Set([...r.features.allOf,e])]:r.features.allOf.filter(t=>t!==e),o=i&&t?[...new Set([...r.features.anyOf,e])]:r.features.anyOf.filter(t=>t!==e),c=r.features.noneOf.filter(t=>t!==e);n({type:`SET_FILTERS`,filters:{...r,features:{allOf:a,anyOf:o,noneOf:c}}})},[]),A=(0,X.useCallback)((e,t)=>{let{filters:r}=s.current,i=r.features.allOf.filter(t=>t!==e),a=r.features.anyOf.filter(t=>t!==e),o=r.features.noneOf.filter(t=>t!==e);t===`allOf`?i.push(e):t===`anyOf`?a.push(e):t===`noneOf`&&o.push(e),n({type:`SET_FILTERS`,filters:{...r,features:{allOf:i,anyOf:a,noneOf:o}}})},[]),j=(0,X.useCallback)(()=>{let{filters:e}=s.current;n({type:`SET_GEO_SELECTION`,selection:null}),n({type:`SET_FILTERS`,filters:{...L_,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}})},[]),M=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),N=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),P=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),ee=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),F=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),I=(0,X.useCallback)(e=>{n({type:`SET_GEO_SELECTION`,selection:e})},[]),L=(0,X.useCallback)((e,t=null)=>{n({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),R=(0,X.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:i,activeTreeName:o,activeContextPath:l,filters:u,geoSelection:d,isSaving:f}=s.current;if(!f){n({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&i&&l){let e=o||`context`,t=g6(await Gi(i,e),l),n=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;await ia(i,l,{metadata:{...t?.metadata||{},toolbox:c6(u)},querySpec:{features:u.features,filters:[...V_(u.timeline),...R_(u.geo)],query:n.trim()||void 0,sort:u.sort?.sortBy?u.sort:null}},e),Sa(i,e)}else if(e===`context`&&t){let e=(await fs(t,a)).metadata||{},n=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;await Go(t,{metadata:{...e,toolbox:u,toolboxGeoSelection:d,toolboxSearchQuery:n.trim()||void 0},...H_(u,d,c)},a)}let s=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;n({type:`SET_SAVED_FILTERS`,savedFilters:u,savedSearchQuery:s.trim()||null,hydrating:!0}),e===`context`&&n({type:`SET_SAVED_GEO_SELECTION`,selection:d})}finally{n({type:`SET_SAVING`,isSaving:!1})}}},[r.search,a,c]),te=(0,X.useCallback)(e=>{let t=s.current.availableBitmaps.filter(t=>t!==e);n({type:`SET_BITMAPS`,keys:t});let r=s.current.filters,i={...r,features:{allOf:r.features.allOf.filter(t=>t!==e),anyOf:r.features.anyOf.filter(t=>t!==e),noneOf:r.features.noneOf.filter(t=>t!==e)}};JSON.stringify(i.features)!==JSON.stringify(r.features)&&n({type:`SET_FILTERS`,filters:i})},[]),ne=(0,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await zi(t,e),te(e)},[te]),z=(0,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await $r(t,e);return te(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[te]),re=(0,X.useCallback)(()=>{let e=s.current.activeWorkspaceName;e&&(n({type:`SET_TIMELINES_LOADING`,loading:!0}),Ai(e).then(e=>{n({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,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await la(t,e),re()},[re]),ae=(0,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await ai(t,e);let r=s.current.availableTimelines.filter(t=>t!==e);n({type:`SET_TIMELINES`,names:r});let i=s.current.filters,a=i.timeline.selectedTimelines.filter(t=>t!==e);a.length!==i.timeline.selectedTimelines.length&&n({type:`SET_FILTERS`,filters:{...i,timeline:{...i.timeline,selectedTimelines:a}}})},[]),{features:oe,timeline:se,geo:B,lens:ce}=t.filters,V=oe.allOf.length>0||oe.anyOf.length>0||oe.noneOf.length>0||se.quickFilter!==null||(se.customRanges?.length??0)>0||(se.selectedTimelines?.length??0)>0||B.bbox!==null||ce.gps!==null||ce.ids!==null||t.geoSelection!==null;return(0,Z.jsx)(ts.Provider,{value:{state:t,setView:h,toggleView:g,closeT1:_,openAgentT2:v,closeT2:y,openAdd:b,openAddPicker:x,openAddRelated:S,closeAdd:C,openEdit:w,setToolsTab:T,openApplet:E,setAccentColor:D,setFilters:O,setFeatureToggle:k,setFeatureMode:A,clearFilters:j,hasActiveFilters:V,setTimelineFilter:N,setGeoBBox:P,setLensGps:ee,setLensIds:F,setGeoSelection:I,setMapDocuments:L,setSort:M,setLiveEnabled:m,saveFilters:R,deleteBitmap:ne,deleteDataset:z,createTimeline:ie,deleteTimeline:ae,refreshTimelines:re},children:e})}var v6=`references`;function y6(e){return e?e.documents.map(e=>({predicate:v6,direction:`out`,targetId:e.id,document:e})):[]}function b6(e,t){let[n,r]=(0,X.useState)(()=>y6(t)),[i,a]=(0,X.useState)([...$a]),o=e?.mode===`context`?e.contextId:null,[s,c]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!o)return;let e=!1;return xs({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,X.useEffect)(()=>{let e=!1;if(l)return $i(l).then(t=>{e||a(t)}),()=>{e=!0}},[l]),{rows:n,predicates:i,workspaceName:l,add:(0,X.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?qr(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,X.useCallback)((e,t)=>{r(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),remove:(0,X.useCallback)(e=>{r(t=>t.filter((t,n)=>n!==e))},[]),write:(0,X.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 Ca(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&&Dm(),r},[n,l]),hasRows:n.length>0}}function x6({f:e,idPrefix:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(!1),o=!e.workspaceName;return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(Pu,{children:`Related documents`}),(0,Z.jsxs)(Y,{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,Z.jsx)(U,{className:`mr-1 h-3 w-3`}),` Add`]})]}),e.rows.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None. Relations are written right after the document is created.`}):(0,Z.jsx)(`ul`,{className:`space-y-1`,children:e.rows.map((n,r)=>{let i=n.document?Ui(n.document).title:`Document ${n.targetId}`,a=`${t}-relation-${r}`;return(0,Z.jsxs)(`li`,{className:`flex items-center gap-1.5 rounded-md border border-input px-2 py-1.5 text-sm`,children:[(0,Z.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,Z.jsx)(qn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Bt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`label`,{htmlFor:a,className:`sr-only`,children:`Predicate`}),(0,Z.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,Z.jsx)(`option`,{value:e,children:e},e))}),n.document?(0,Z.jsx)(Dp,{document:n.document,size:3.5}):null,(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 truncate`,!n.document&&`italic text-muted-foreground`),title:`#${n.targetId}`,children:i}),(0,Z.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,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]},`${n.direction}:${n.predicate}:${n.targetId}`)})}),n&&e.workspaceName&&(0,Z.jsx)(Hp,{onClose:()=>{i||r(!1)},children:(0,Z.jsx)(Bp,{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 S6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=Sw(),o=b6(n,t.addRelateTo),s=Ww(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`note-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Body`}),(0,Z.jsx)(Io,{kind:`markdown`,value:a.content,onChange:a.setContent,placeholder:`Write your note…`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`note-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`note-comment`,value:a.comment,onChange:e=>a.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,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsx)(ww,{geotag:a.geotag,idPrefix:`note-geotag`}),(0,Z.jsx)(x6,{f:o,idPrefix:`note`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Note created; some relations failed`:`Note created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create note`)}},disabled:!c,children:a.saving?`Saving…`:`Save note`})]})]})}function C6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=jw(),o=b6(n,t.addRelateTo),s=Ww(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsx)(ww,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,Z.jsx)(x6,{f:o,idPrefix:`link`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{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 w6(e){let[t,n]=(0,X.useState)({key:``,list:[]});return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return Ta(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await Xa(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 T6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=Nh(),o=b6(n,t.addRelateTo),s=Ww(t.activeWorkspaceName),c=w6(t.activeWorkspaceName),[l,u]=(0,X.useState)(`canvas`),[d,f]=(0,X.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 Ea(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(Ig,{...a}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`todo-comment`,children:`Comment`}),(0,Z.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,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`todo-destination`,children:`Save to`}),(0,Z.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,Z.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,bs(n)]}),c.map(e=>(0,Z.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,Z.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,Z.jsx)(ww,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,Z.jsx)(x6,{f:o,idPrefix:`todo`}),!p&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function E6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=Gg(),o=b6(n,t.addRelateTo),s=Ww(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(Xg,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`identity-comment`,children:`Comment`}),(0,Z.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,Z.jsx)(x6,{f:o,idPrefix:`identity`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function D6({capture:e=!1}={}){let{closeAdd:t,state:n}=Os(),r=gs(),i=r?.mode===`workspace`&&r.treeName===`backends`,a=b6(r,n.addRelateTo),{showSuccessToast:o,showErrorToast:s}=Wr(),c=(0,X.useRef)(null),[l,u]=(0,X.useState)(!1),d=Lw(),{items:f,running:p}=d,[m,h]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(r?.mode!==`context`)return;let e=!1;return xs(r).then(t=>{e||h({contextId:r.contextId,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[r]);let g=qw(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,onClick:()=>c.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,l?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(te,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:e?`Take a photo or video`:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`click to open the camera`:`or click to browse`}),(0,Z.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,Z.jsx)(Hw,{items:f,running:p,onRemove:d.removeItem}),!i&&(0,Z.jsx)(Xw,{fields:g,idPrefix:`file`,multiple:f.length>1}),(0,Z.jsx)(x6,{f:a,idPrefix:`file`}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[bs(r),i?`. Existing files are never overwritten.`:``]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>p?d.cancel():t(),children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{if(!(!S||!r))try{let e=i?null:await g.geotag.capture(),n=await d.start(r,(t,n)=>Jw(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,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(He,{className:`h-3.5 w-3.5`}),`Retry failed (`,y,`)`]}):`Add files`})]})]})}function O6(){let{closeAdd:e}=Os(),t=gs(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.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 xs(t),o=i===`/`?``:i;if(a===`backends`){let e=await vs(r,i);await oa(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),os(t)}else await _a(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,Z.jsx)(q,{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,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,bs(t)]})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function k6(){let{openAddPicker:e,closeAdd:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,X.useState)(!1);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:e,"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(fm,{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 ps(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 A6(e,t){let[n,r]=(0,X.useState)(String(e.data?.title??``)),[i,a]=(0,X.useState)(String(e.data?.content??``)),[o,s]=(0,X.useState)(qp(e.metadata?.features)),[c,l]=(0,X.useState)(!1),u=i.trim().length>0&&!c;async function d(){l(!0);try{await Da(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...n.trim()?{title:n.trim()}:{},content:i},metadata:{features:Kp(o)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{l(!1)}}return{title:n,setTitle:r,content:i,setContent:a,tags:o,setTags:s,saving:c,canSave:u,save:d}}function j6(){let{state:e,closeAdd:t}=Os(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,Z.jsx)(M6,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function M6({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=A6(e,t),s=Ww(t);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(Pu,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(Io,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Note updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update note`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save note`})]})]})}function N6(e,t){let n=qp(e.metadata?.features),[r,i]=(0,X.useState)(String(e.data?.label??``)),[a,o]=(0,X.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,X.useState)(!1),l=!s;async function u(){c(!0);try{let n=a.map(e=>e.trim()).filter(Boolean);await Da(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data,...r.trim()?{label:r.trim()}:{},tags:n},metadata:{features:Kp(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 P6(){let{state:e,closeAdd:t}=Os(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,Z.jsx)(F6,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function F6({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=N6(e,t),s=Ww(t);return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(Pu,{children:[`URL `,(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,Z.jsx)(q,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-link-label`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Z.jsx)(Y,{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 I6=380,L6=300,R6=560,z6={message:{label:`New Message`,icon:It},note:{label:`New Note`,icon:xn},link:{label:`New Link`,icon:Xt},todo:{label:`New Todo`,icon:On},identity:{label:`New Identity`,icon:Ze},sketch:{label:`New Sketch`,icon:rt},file:{label:`Add Files`,icon:te},photo:{label:`Photo/Video`,icon:z},existing:{label:`Add Existing`,icon:Ot},folder:{label:`New Folder`,icon:ut}};function B6(){let{state:e,openAdd:t,closeAdd:n}=Os();Ff(n,e.addOpen);let{addOpen:r,addKind:i,editDocument:a}=e,o=gs(),s=Cs(o),c=s.isBackend&&!!i&&![`file`,`photo`,`folder`,`message`].includes(i),l=e.activeWorkspaceName,u=!l||!!e.addRelateTo,d=c||i===`message`&&u,f=s.isBackend?[`note`,`link`,`todo`,`identity`,`sketch`,`existing`]:[];u&&f.push(`message`);let p=o?.mode===`workspace`?`${o.workspaceName}:${o.treeName}:${o.path}`:o?.contextId,m=al();(0,X.useEffect)(()=>{!r||i!==`sketch`||s.isBackend||(n(),m(gw.createUrl(o)))},[r,i,o,n,m,s.isBackend]);let h=Ym(),[g,_]=(0,X.useState)(I6),v=(0,X.useRef)(null),y=(0,X.useCallback)(e=>{e.preventDefault(),v.current={startX:e.clientX,startWidth:g};let t=e=>{if(!v.current)return;let t=v.current.startX-e.clientX,n=Math.min(R6,Math.max(L6,v.current.startWidth+t));_(n)},n=()=>{v.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[g]);if(!r)return null;let b=!!a,x=!b&&(!i||d),S,C;return b?(S=a.schema===`data/schema/note`?`Edit Note`:`Edit Link`,C=a.schema===`data/schema/note`?xn:Xt):i&&!d?(S=z6[i].label,C=z6[i].icon):(S=`Add`,C=U),(0,Z.jsxs)(Z.Fragment,{children:[h&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:h?void 0:{width:g},className:K(`flex flex-col overflow-hidden rounded-[var(--panel-radius)] border bg-card surface-glass`,h?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!h&&(0,Z.jsx)(`div`,{onMouseDown:y,className:`absolute left-0 top-0 bottom-0 z-10 w-1 cursor-col-resize transition-colors hover:bg-primary/20`}),(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[b?(0,Z.jsx)(Fe,{className:`h-4 w-4`}):(0,Z.jsx)(C,{className:`h-4 w-4`}),S]}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground transition-colors hover:text-foreground`,"aria-label":`Close`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[b&&a.schema===`data/schema/note`&&(0,Z.jsx)(j6,{}),b&&a.schema===`data/schema/link`&&(0,Z.jsx)(P6,{}),!b&&x&&e.addRelateTo&&(0,Z.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`,`.`]}),!b&&s.isBackend&&i!==`message`&&(0,Z.jsx)(`p`,{className:`border-b px-4 py-3 text-xs text-muted-foreground`,children:s.loading?`Checking storage destination…`:s.error||`Files are saved directly to this backend folder. Notes and other database documents belong in context or directory trees.`}),!b&&x&&(!s.isBackend||s.destination)&&(0,Z.jsx)(yw,{onSelect:t,omit:f}),!b&&i===`message`&&!u&&l&&(0,Z.jsx)(gg,{workspaceId:l,onClose:n},l),!b&&!s.isBackend&&i===`note`&&(0,Z.jsx)(S6,{}),!b&&!s.isBackend&&i===`link`&&(0,Z.jsx)(C6,{}),!b&&!s.isBackend&&i===`todo`&&(0,Z.jsx)(T6,{}),!b&&!s.isBackend&&i===`identity`&&(0,Z.jsx)(E6,{}),!b&&(!s.isBackend||s.destination)&&i===`file`&&(0,Z.jsx)(D6,{},p),!b&&(!s.isBackend||s.destination)&&i===`photo`&&(0,Z.jsx)(D6,{capture:!0},p),!b&&!s.isBackend&&i===`existing`&&(0,Z.jsx)(k6,{}),!b&&(!s.isBackend||s.destination)&&i===`folder`&&(0,Z.jsx)(O6,{},p)]})]})]})}var V6=(0,X.createContext)(null);function H6(){return(0,X.useContext)(V6)}function U6(){let e=H6(),t=e?.notifications??[];return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,Z.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,Z.jsx)(cn,{className:`w-4 h-4`}),(0,Z.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)($t,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,Z.jsx)(lt,{className:`w-3 h-3`})})]}),t.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-lg`,children:`No notifications`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,Z.jsxs)(`div`,{className:`rounded-lg border p-2.5`,children:[(0,Z.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,Z.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}function W6(){let{state:e,setFilters:t}=Os();return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.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 G6=l();Do();var K6=`#8b5cf6`,q6=`#94a3b8`,J6={color:K6,weight:2,fillColor:K6,fillOpacity:.12},Y6={color:K6,weight:2,dashArray:`5,5`,fillColor:K6,fillOpacity:.06},X6=e=>Math.round(e*1e6)/1e6;function Z6(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:${K6};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 Xp.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var Q6=e=>e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e]),$6=new Map;function e8(e){let t=$6.get(e);return t??(t=(0,G6.renderToStaticMarkup)((0,X.createElement)(s6(e),{width:13,height:13,strokeWidth:2.5})),$6.set(e,t)),t}var t8=new Map;function n8(e,t){let n=`${e}|${+!!t}`,r=t8.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?K6:q6};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${e8(e)}</div>`;r=Xp.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),t8.set(n,r)}return r}function r8(){let{state:e,setGeoSelection:t,setGeoBBox:n}=Os(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=i_(),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(null),p=(0,X.useRef)([]),m=(0,X.useRef)(!1),[h,g]=(0,X.useState)(`idle`),[_,v]=(0,X.useState)(0),y=(0,X.useRef)(h),b=(0,X.useMemo)(()=>r.reduce((e,t)=>e+ +!!T_(t),0),[r]),x=(0,X.useMemo)(()=>i?r.reduce((e,t)=>{let n=T_(t);return e+(n&&D_(n.lat,n.lon,i)?1:0)},0):0,[r,i]),S=(0,X.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&Xp.default.polyline(t,Y6).addTo(e),t.forEach(t=>Xp.default.circleMarker(t,{radius:4,color:K6,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),C=(0,X.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),w=(0,X.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:X6(e.lat),lon:X6(e.lng)}))}),C(),g(`idle`)},[t,C]),T=(0,X.useCallback)(()=>{C(),g(`idle`),t(null),n(null)},[C,t,n]);(0,X.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=Xp.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});Xp.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=Xp.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>Z6(e.getChildCount())}).addTo(t),f.current=Xp.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=Xp.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=Xp.default.rectangle(n,Y6).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=Xp.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:X6(s.lat),minLon:X6(s.lng),maxLat:X6(c.lat),maxLon:X6(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,X.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,X.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,X.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=T_(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||D_(t.lat,t.lon,i),c=Xp.default.marker([t.lat,t.lon],{icon:n8(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(Q6(Ui(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(Xp.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,X.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=Xp.default.layerGroup();o&&Xp.default.rectangle(Xp.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),J6).addTo(t),i?.kind===`polygon`&&Xp.default.polygon(i.points.map(e=>[e.lat,e.lon]),J6).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,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:K(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,Z.jsx)(nn,{className:`h-3.5 w-3.5`}),`Box`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:K(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,Z.jsx)(I,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:w,disabled:_<3,className:K(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,Z.jsx)($e,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:C,className:K(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:T,disabled:!o&&!i&&h===`idle`,className:K(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,Z.jsx)(lt,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,Z.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:E})]}),(0,Z.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,Z.jsx)(`div`,{ref:c,className:`absolute inset-0`}),b===0&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,Z.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,Z.jsx)(yt,{className:`h-3 w-3`}),b,` of `,r.length,` located`,i&&(0,Z.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,x,` in area`]})]})]})}var i8=[{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}],a8=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,o8=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,s8=e=>Math.round(e*1e4)/1e4;function c8(){let{state:e,setLensGps:t,setLensIds:n}=Os(),r=e.filters.lens,i=e.activeWorkspaceName,a=r.gps?.radiusM??100,[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(r.gps?.radiusM??100),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(0),[m,h]=(0,X.useState)(`prompt`),g=(0,X.useRef)(null),_=(0,X.useRef)(c);(0,X.useEffect)(()=>{_.current=c},[c]);let v=`geolocation`in navigator&&window.isSecureContext;(0,X.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,X.useEffect)(()=>{if(!o||!v)return;let e=navigator.geolocation.watchPosition(e=>{let n=s8(e.coords.latitude),r=s8(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=ix(),{rateMs:C,setRateMs:w,maxDistance:T,setMaxDistance:E,error:D}=S,O=S.running&&S.consumer===`filter`,k=S.running&&S.consumer!==`filter`;ax(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[e.activeContextType===`context`&&(0,Z.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,Z.jsx)(W6,{}),(0,Z.jsxs)(`section`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,disabled:!v,onChange:e=>y(e.target.checked)}),(0,Z.jsx)(Jn,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{children:`Track this device’s GPS`})]}),(0,Z.jsx)(`select`,{className:a8,value:c,onChange:e=>x(Number(e.target.value)),disabled:!o,children:i8.map(e=>(0,Z.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?m===`denied`?(0,Z.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):u?(0,Z.jsxs)(`span`,{className:`text-destructive`,children:[u,` `,(0,Z.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,Z.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,Z.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,Z.jsx)(Se,{className:`h-3.5 w-3.5`}),` `,S.source===`photo`?`Close photo`:`Stop ${S.source===`camera`?`camera`:`recording`}`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(z,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.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,Z.jsx)(fe,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(Ex,{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,Z.jsx)(`select`,{className:a8,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:px.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(o8,`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,Z.jsxs)(`div`,{className:K(`relative overflow-hidden rounded-lg border border-border bg-black/80`,j?N?`aspect-[3/4] max-h-[60vh]`:`aspect-video`:`hidden`),children:[(0,Z.jsx)(vx,{className:`h-full w-full`,interactive:!0}),(0,Z.jsx)(wx,{})]}),j&&(0,Z.jsx)(Cx,{}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?(0,Z.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,Z.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 l8={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function u8(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 d8(e){return l8[e]??`oklch(var(--data-l) var(--data-c) ${u8(e)})`}var f8=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],p8=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],m8=[`Yesterday`,`Today`,`Tomorrow`],h8=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],g8=10,_8=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function v8(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 y8(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 b8(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`${_8[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${_8[t.getMonth()]} – ${e.getDate()} ${_8[e.getMonth()]}`}}}function x8(e,t){return Array.from({length:t},(t,n)=>{let r=v8(e,n),i=y8(e,r);return{offset:n,label:b8(e,r,n),start:r,end:i,isNow:n===0}})}var S8={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 C8(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function w8(e,t){let n=k8(e);return n?(n.setDate(n.getDate()+t),C8(n)):e}function T8(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<=w8(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function E8(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return T8([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=w8(t,-1)&&r.push({start:n.start,end:w8(t,-1)}),w8(t,1)<=n.end&&r.push({start:w8(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function D8(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:C8(t.start),end:C8(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function O8({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=Os(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,X.useState)(3),[d,f]=(0,X.useState)(g8),[p,m]=(0,X.useState)(new Set),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(e);e!==_&&(v(e),e&&S8[e]!==void 0&&u(S8[e]),m(new Set));let[y,b]=(0,X.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=h8[l],S=x8(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,X.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{Co(a,{names:r,buckets:x8(x.unit,d).map(e=>D8(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:R_(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(g8),m(new Set)},O=(0,X.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:C8(n),end:C8(r)}})),i})},[S,n]);return(0,Z.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.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,Z.jsx)(B,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(F,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.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,Z.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:K(`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,Z.jsx)(cn,{className:`w-3 h-3 shrink-0`}),(0,Z.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,Z.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,Z.jsx)(`span`,{className:K(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,Z.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,Z.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:d8(e)}},e))})]})]},e.offset)}),d<200&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+g8),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function k8(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 A8({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,X.useState)(()=>{let t=e[0]?.start&&k8(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,X.useState)(null),[c,l]=(0,X.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=C8(r);return(0,Z.jsxs)(`div`,{className:`select-none`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.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,Z.jsx)(w,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(oe,{className:`w-3.5 h-3.5`})})]}),(0,Z.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:[_8[i.m],` `,i.y]}),(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.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,Z.jsx)(Ye,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(gr,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=C8(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,Z.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:K(`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,Z.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 j8({label:e,checked:t,onChange:n,color:r}){return(0,Z.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,Z.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,Z.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,Z.jsx)(`div`,{className:K(`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,Z.jsx)(`div`,{className:K(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function M8(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=Os(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(`quick`),[_,v]=(0,X.useState)(!1),{showToast:y}=Vr(),b=new Set(a.selectedTimelines??[]),x=(0,X.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=B_(a),D=E.length>0,O=(0,X.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,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!D;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>k(e),className:K(`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?m8[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,Z.jsx)(O8,{quickFilterKey:a.quickFilter,activeRangeCount:E.length,onSelectRanges:O,histogramNames:x}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,Z.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:K(`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,Z.jsx)(_e,{className:`w-3 h-3`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:K(`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,Z.jsx)(Nn,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,Z.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),f8.map((e,t)=>j(e,t===0)),(0,Z.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,Z.jsx)(Ge,{className:K(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&p8.map(e=>j(e,!1))]}):(0,Z.jsx)(A8,{ranges:E,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:E8(E,e),customRange:null,quickFilter:null})}),D&&(0,Z.jsx)(`div`,{className:`mt-2 space-y-1`,children:E.map((e,t)=>(0,Z.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,Z.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>A(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,Z.jsx)(Me,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(j8,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:d8(`crud:created`)}),(0,Z.jsx)(j8,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:d8(`crud:updated`)}),(0,Z.jsx)(j8,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:d8(`crud:deleted`)}),(0,Z.jsx)(j8,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:d8(`content`)})]}),(0,Z.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,Z.jsx)(we,{className:`w-3 h-3`})})]}),c?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):T.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,Z.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:T.map(e=>{let t=b.has(e),n=d8(e);return(0,Z.jsxs)(`div`,{className:K(`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,Z.jsx)(`div`,{className:K(`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,Z.jsx)(`svg`,{className:K(`w-2.5 h-2.5`,gp(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,Z.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,Z.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,Z.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,Z.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,Z.jsx)(Mt,{className:`w-3 h-3 animate-spin`}):(0,Z.jsx)(lt,{className:`w-3 h-3`})})]},e)})}),(0,Z.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,Z.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,Z.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,Z.jsx)(Mt,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(U,{className:`w-3.5 h-3.5`})})]})]})]})]})}var N8={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},P8=`data/dataset/default`;function F8(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 I8=[`off`,`anyOf`,`allOf`,`noneOf`];function L8(e){return I8[(I8.indexOf(e)+1)%I8.length]}var R8=[{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 z8({mode:e,onSet:t}){return(0,Z.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:R8.map(n=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:K(`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 B8({keys:e,modeOf:t,onCycle:n}){return e.length?(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=o6(e),a=t(e),o=R8.find(e=>e.m===a);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:K(`relative flex flex-col items-center justify-center gap-1.5 rounded-lg 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,Z.jsx)(`span`,{className:K(`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,Z.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function V8(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=Os(),{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,X.useState)(``),[h,g]=(0,X.useState)(null),{showToast:_}=Vr(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==P8){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,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{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,Z.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(i6)).sort((e,t)=>{let n=Object.keys(a6),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=F8(S.filter(e=>!e.startsWith(i6))),T=w.get(`data/dataset`);return T&&!T.includes(P8)&&(!x||P8.includes(x))&&T.unshift(P8),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,Z.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,Z.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,Z.jsx)(Me,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsx)(B8,{keys:C,modeOf:f,onCycle:e=>t(e,L8(f(e)))}),w.size===0&&C.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:N8[e]??e}),(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===P8,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,Z.jsxs)(`div`,{onClick:()=>t(e,L8(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,L8(o)))},className:K(`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,Z.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,Z.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,Z.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(z8,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,Z.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,Z.jsx)(Mt,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function H8(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i,setLiveEnabled:a}=Os(),{toolsTab:o,isDirty:s,isSaving:c,activeContextType:l,savedSearchQuery:u}=e,d=nl(),f=new URLSearchParams(d.search).get(`q`)||new URLSearchParams(d.search).get(`search`)||``,p=l!==null&&f.trim()!==(u||``),m=l!==null&&(s||p);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:K(`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,Z.jsxs)(`div`,{className:`space-y-2 border-b border-border px-3 py-2 shrink-0`,children:[(0,Z.jsxs)(`label`,{className:`flex min-h-10 cursor-pointer items-center justify-between gap-3 text-sm font-medium`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:K(`h-2 w-2 rounded-full`,e.liveEnabled?`bg-success`:`bg-muted-foreground`)}),`Live`]}),(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-5 w-5 accent-current`,checked:e.liveEnabled,disabled:new URLSearchParams(d.search).has(`ownerId`),onChange:e=>{a(e.target.checked)}})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.liveEnabled?`Filters and camera matches update every device bound to this context. Save to keep the current view.`:`Preview on this device. Turn on Live to update bound devices.`}),e.liveError&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-destructive`,children:e.liveError})]}),(i||m)&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:[i&&(0,Z.jsxs)(`button`,{type:`button`,onClick:r,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`,title:`Clear all active filters`,children:[(0,Z.jsx)(Me,{className:`w-3 h-3`}),`Clear`]}),m&&(0,Z.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,Z.jsx)(Mt,{className:`w-3 h-3 animate-spin`}):(0,Z.jsx)(k,{className:`w-3 h-3`}),l===`context`&&e.liveEnabled?`Save current view`:`Save filters`]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[o===`features`&&(0,Z.jsx)(V8,{}),o===`timeline`&&(0,Z.jsx)(M8,{}),o===`map`&&(0,Z.jsx)(r8,{}),o===`lens`&&(0,Z.jsx)(c8,{})]})]})}function U8({status:e}){return(0,Z.jsx)(`span`,{className:K(`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 W8(){let{openAgentT2:e}=Os(),{setSection:t}=zS(),n=al(),{agents:r,isLoading:i,refresh:a}=x3(!0),{showToast:o}=Vr(),[s,c]=(0,X.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 CE(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 wE(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,Z.jsx)(dt,{className:`w-8 h-8 opacity-30`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,Z.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(U8,{status:t.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,Z.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,Z.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,Z.jsx)(nn,{className:`w-3 h-3`})}):(0,Z.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,Z.jsx)(De,{className:`w-3 h-3`})})})]}),t.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function G8(){return(0,Z.jsx)(`div`,{className:`flex h-full flex-col`,children:(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,Z.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,Z.jsx)($t,{className:`h-5 w-5 text-muted-foreground`})}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No notifications yet`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This is where activity, agent updates, and alerts will appear once notifications are wired in.`})]})]})})}function K8(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(`
|
|
95
|
+
`)}\n\nThe selected layers lose this layer's documents. This layer is unchanged.`)&&await w(n.id,Array.from(l.values()))})]}),oe&&!ie&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`my-1 h-px bg-border`}),(0,Z.jsxs)(`div`,{className:`px-3 py-1.5 text-[10px] text-muted-foreground italic`,children:[`This is a target. Right-click the source (`,c?.path,`) to merge/subtract`]})]})]})}function z4({onConfirm:e,onCancel:t,placeholder:n=`folder name…`}){let r=(0,X.useRef)(null);(0,X.useEffect)(()=>{r.current?.focus()},[]);let i=()=>{let n=r.current?.value.trim()??``;n?e(n):t()};return(0,Z.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 bg-card ring-1 ring-primary/50 shadow-elevation-3 text-sm font-medium`,children:[(0,Z.jsx)(Ye,{className:`w-4 h-4 opacity-0 shrink-0`}),(0,Z.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 B4(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function V4(e,t,n){let r=B4(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>V4(e,r,n))??!1}function H4({node:e,parentPath:t,depth:n,isLast:r,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:f,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:P=!1,trail:ee=[]}){let F=Af(),I=B4(t,e.name),L=M?.(I)??null,R=S.get(I)??op(e),[te,ne]=(0,X.useState)(()=>i!==`/`&&(i===I||i.startsWith(I+`/`))),[z,re]=(0,X.useState)(i);if(z!==i&&(re(i),i!==`/`&&i.startsWith(I+`/`)&&ne(!0)),f&&!V4(e,t,f))return null;let ie=te||p===I||f.length>0,ae=e.children&&e.children.length>0,oe=i===I,se=a===I,B=l?.path===I,ce=u.has(I),V=e.type===`canvas`,le=t=>{if(t.ctrlKey||t.metaKey){_(I,e.id);return}if(t.shiftKey&&h){h(I);return}m(I)},de=[...ee].reverse().find(Boolean)??null,fe=R.color||de,pe=P?[...ee,fe]:ee,me=i!==`/`&&i.startsWith(I+`/`),he=!B&&!ce,ge=he&&oe,_e=(e,t)=>`color-mix(in oklab, ${e} ${t}%, var(--card))`,ve=e=>`color-mix(in oklab, currentColor ${e}%, transparent)`,ye=Math.min(n,5),H=ie&&!!ae,be=n>0&&de?de:fe,U=he&&!ge&&!e.locked&&H,xe=be?Math.min(12+ye*5+(me?6:0),34):Math.min(ye*7+(me?5:0)+(se?3:0),30),Se=ge?`var(--primary)`:B?_e(`var(--info)`,22):ce?_e(`var(--warning)`,22):e.locked?_e(`var(--warning)`,20+ye*4):U?fe?_e(fe,84):_e(`var(--foreground)`,38):_e(be||`var(--foreground)`,xe),Ce=ge?`text-primary-foreground`:U&&fe?_p(fe):`text-foreground`,W=P&&ie&&ae&&n<F4,G=(0,Z.jsxs)(`div`,{"data-active":oe||void 0,className:K(`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]`,Ce,B&&`ring-1 ring-inset ring-info/40`,ce&&!B&&`ring-1 ring-inset ring-warning/40`,C===I&&!s&&!w&&`ring-2 ring-inset ring-info`,C===I&&!s&&w&&`ring-2 ring-inset ring-success`),style:{height:P4,background:Se,borderBottom:`1px solid ${ve(14)}`,...W?{position:`sticky`,top:n*P4,zIndex:20-n}:{}},draggable:!s&&!e.metadata?.backendTrash,onClick:le,...s?{}:F,onContextMenu:t=>{s||(t.preventDefault(),v(t,I,e))},onDragStart:e=>{s||T(I,e)},onDragEnter:e=>{s||E(I,e)},onDragOver:e=>{s||D(I,e)},onDragLeave:e=>O(I,e),onDragEnd:()=>k(),onDrop:e=>{s||A(I,e)},children:[ee.length>0&&(0,Z.jsx)(`span`,{className:`flex shrink-0 gap-px`,"aria-hidden":!0,children:ee.map((e,t)=>(0,Z.jsx)(`span`,{className:`w-[3px]`,style:{background:e||ve(28)}},t))}),(()=>{let t=R.color?{background:R.color}:de?{background:`color-mix(in oklab, ${de} 45%, transparent)`}:{background:ve(10)},n=(0,Z.jsx)(c,{icon:R.icon||(V?`ph:squares-four-fill`:`ph:folder-fill`),width:18,height:18,className:K(`shrink-0`,R.color?gp(R.color):ge?`text-primary-foreground`:U?`text-current`:`text-foreground/80`)}),r=`flex w-10 shrink-0 items-center justify-center`;return x?(0,Z.jsx)(`button`,{type:`button`,className:r,style:t,title:`Change icon`,onClick:t=>{xr()||(t.stopPropagation(),x(t,I,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,I,e)},children:n}):(0,Z.jsx)(`span`,{className:r,style:t,children:n})})(),(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 self-center truncate px-2.5`,oe||me||H?`font-semibold`:`font-medium`),title:e.description||void 0,children:e.label||e.name}),N.has(I)&&(0,Z.jsx)(we,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center`,"aria-label":N.get(I)}),j?.has(I)&&(0,Z.jsx)(we,{className:`mr-1 h-3.5 w-3.5 shrink-0 animate-spin self-center opacity-70`,"aria-label":`Indexing`}),L&&(0,Z.jsx)(ue,{className:`mr-1 h-3 w-3 shrink-0 self-center text-muted-foreground`,"aria-label":L,children:(0,Z.jsx)(`title`,{children:L})}),!s&&(0,Z.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,I,e)},children:(0,Z.jsx)(Kt,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,className:K(`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!==I&&`invisible`),style:{borderLeft:`1px solid ${ve(16)}`},"aria-label":ie?`Collapse`:`Expand`,"aria-expanded":ie,title:ie?`Collapse`:`Expand`,onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,Z.jsx)(Ge,{className:`h-5 w-5`,strokeWidth:2.25}):(0,Z.jsx)(Ye,{className:`h-5 w-5`,strokeWidth:2.25})})]});return(0,Z.jsxs)(`div`,{className:`relative`,children:[P?G:(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-0 w-px bg-border`,style:{left:`-${N4/2}px`,...r?{height:`1.375rem`}:{bottom:0}}}),(0,Z.jsx)(`div`,{className:`pointer-events-none absolute top-[1.375rem] h-px bg-border`,style:{left:`-${N4/2}px`,width:`${N4/2}px`}}),(0,Z.jsxs)(`div`,{"data-active":oe||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none 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`,B&&`ring-1 ring-info/40 bg-info/10 before:bg-info`,ce&&!B&&`ring-1 ring-warning/40 bg-warning/10 before:bg-warning`,!B&&!ce&&oe&&!e.locked&&`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`,!B&&!ce&&oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-primary`,!B&&!ce&&!oe&&se&&`bg-primary/[0.03] before:bg-transparent`,!B&&!ce&&!oe&&!se&&!e.locked&&`bg-card hover:bg-primary/[0.04] before:bg-transparent`,!B&&!ce&&!oe&&e.locked&&`bg-warning/15 hover:bg-warning/20 before:bg-warning`,C===I&&!s&&!w&&`ring-2 ring-info bg-info-subtle/50`,C===I&&!s&&w&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:R.color?`4px solid ${R.color}`:`4px solid transparent`},draggable:!s&&!e.metadata?.backendTrash,onClick:le,...s?{}:F,onContextMenu:t=>{s||(t.preventDefault(),v(t,I,e))},onDragStart:e=>{s||T(I,e)},onDragEnter:e=>{s||E(I,e)},onDragOver:e=>{s||D(I,e)},onDragLeave:e=>O(I,e),onDragEnd:()=>k(),onDrop:e=>{s||A(I,e)},children:[(0,Z.jsx)(`button`,{type:`button`,className:K(`shrink-0 text-muted-foreground hover:text-foreground`,!ae&&p!==I&&`invisible`),onClick:e=>{e.stopPropagation(),ne(e=>!e)},children:ie?(0,Z.jsx)(Ge,{className:`w-4 h-4`}):(0,Z.jsx)(Ye,{className:`w-4 h-4`})}),(()=>{let t=(0,Z.jsx)(c,{icon:R.icon||(V?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:R.color||void 0,className:K(`shrink-0`,!R.color&&(V?`text-primary`:`text-muted-foreground`))});return x?(0,Z.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=>{xr()||(t.stopPropagation(),x(t,I,e))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),x(t,I,e)},children:t}):t})(),(0,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name}),N.has(I)&&(0,Z.jsx)(we,{className:`h-3.5 w-3.5 shrink-0 animate-spin`,"aria-label":N.get(I)}),j?.has(I)&&(0,Z.jsx)(we,{className:`w-3.5 h-3.5 shrink-0 animate-spin text-muted-foreground`,"aria-label":`Indexing`}),L&&(0,Z.jsx)(ue,{className:`w-3 h-3 shrink-0 text-muted-foreground`,"aria-label":L,children:(0,Z.jsx)(`title`,{children:L})}),!s&&(0,Z.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,I,e)},children:(0,Z.jsx)(Kt,{className:`w-4 h-4`})})]})]}),ie&&(ae||p===I)&&(0,Z.jsxs)(`div`,{className:P?void 0:`ml-[22px] mt-2 mb-1 space-y-1.5`,children:[p===I&&(0,Z.jsx)(z4,{onConfirm:e=>y(I,e),onCancel:b}),e.children?.map((t,r)=>(0,Z.jsx)(H4,{node:t,parentPath:I,depth:n+1,isLast:r===(e.children?.length??0)-1,selectedPath:i,pendingPath:a,contentPath:o,readOnly:s,sourceLayer:l,targetLayers:u,clipboard:d,searchQuery:f,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:P,trail:pe},t.id||t.name))]})]})}function U4({root:e,treeName:t=`context`,isBackendsTree:n=!1,onRestoreTrash:r,onDiscardTrash:i,selectedPath:a,pendingPath:o,onSelect:s,isLoading:c=!1,readOnly:l=!1,onAddRule:u,onSyncFolderTree: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:P,onSubtractLayer:ee,onMergeDown:F,onSubtractDown:I,onResyncBackend:L,onCreateBackendFolder:R,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onUpdateNode:z,isPathPinned:re,onTogglePin:ie,searchQuery:ae=``,resyncingPaths:oe}){let se=bD(),[B,ce]=(0,X.useState)(null),[V,le]=(0,X.useState)(null),[ue,de]=(0,X.useState)(new Map),[fe,pe]=(0,X.useState)(null),[me,he]=(0,X.useState)(new Map),ge=(0,X.useRef)(new Set),_e=(0,X.useCallback)(async(e,t=!1,n=!1,r=!1)=>{if(!C||[...ge.current].some(t=>t===e||t.startsWith(e+`/`)||e.startsWith(t+`/`)))return!1;ge.current.add(e);let i=r?`Removing documents and backend files…`:n?`Removing and purging documents…`:`Removing folder…`;he(t=>new Map(t).set(e,i));try{return await C(e,t,n,r)}finally{ge.current.delete(e),he(t=>{let n=new Map(t);return n.delete(e),n})}},[C]),[ve,ye]=(0,X.useState)(null),[H,be]=(0,X.useState)(new Map),[U,xe]=(0,X.useState)(e),Se=(0,X.useRef)(new Map),Ce=(0,X.useRef)(null),[W,G]=(0,X.useState)(null);if(e!==U){xe(e);let t=W;be(t?new Map([[t.path,t.style]]):new Map)}let[Te,Ee]=(0,X.useState)(null),[De,Oe]=(0,X.useState)(null),[ke,Ae]=(0,X.useState)(!1),[je,Me]=(0,X.useState)(!1),[Ne,Pe]=(0,X.useState)(!1),Fe=(0,X.useRef)(!1),Ie=(0,X.useRef)(null),Le=(0,X.useRef)(t),Re=(0,X.useRef)(!1),ze=(0,X.useRef)(!1);(0,X.useEffect)(()=>{let e=e=>{ce(e.detail??null)};return window.addEventListener(`tree:path-clipboard`,e),()=>window.removeEventListener(`tree:path-clipboard`,e)},[]),(0,X.useEffect)(()=>{let e=e=>{let t=e.ctrlKey||e.altKey||ze.current;Re.current=t,Ae(t)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,e),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,e)}},[]);let Be=(0,X.useCallback)((e,n,r)=>{if(rv(Le.current,e)||rv(t,n))return!1;if(Le.current!==t)return!0;let i=e.endsWith(`/`)?e.slice(0,-1):e,a=n.endsWith(`/`)?n.slice(0,-1):n,o=i.substring(0,i.lastIndexOf(`/`))||`/`;return!(a.startsWith(i+`/`)||i===a||!r&&a===o)},[t]),Ve=(0,X.useCallback)((e,n)=>{if(rv(t,e)){n.preventDefault();return}Ie.current=e,Le.current=t,n.dataTransfer.setData(`text/plain`,e),n.dataTransfer.setData(`application/x-canvas-tree-path`,JSON.stringify({path:e,treeName:t})),n.dataTransfer.effectAllowed=`copyMove`},[t]),He=e=>e.ctrlKey||e.altKey||ze.current,Ue=(0,X.useCallback)((e,n)=>{if(rv(t,e))return;let r=Ie.current,i=He(n);i!==Re.current&&(Re.current=i,Ae(i)),!(r&&!Be(r,e,i))&&(n.preventDefault(),Oe(e))},[Be,t]),We=(0,X.useCallback)((e,n)=>{if(rv(t,e)){n.dataTransfer.dropEffect=`none`;return}let r=He(n);r!==Re.current&&(Re.current=r,Ae(r));let i=Ie.current;if(i&&!Be(i,e,r)){n.dataTransfer.dropEffect=`none`;return}n.preventDefault(),n.dataTransfer.dropEffect=r?`copy`:`move`},[Be,t]),Ke=(0,X.useCallback)((e,t)=>{t.currentTarget.contains(t.relatedTarget)||Oe(t=>t===e?null:t)},[]),qe=(0,X.useCallback)(()=>{Ie.current=null,Le.current=t,Re.current=!1,Ae(!1),Oe(null)},[t]),Je=(0,X.useCallback)(async(e,r)=>{if(r.preventDefault(),rv(t,e))return;let i=(()=>{try{return JSON.parse(r.dataTransfer.getData(`application/json`))}catch{return null}})();if(i?.type===`document`&&Array.isArray(i.documentIds)&&i.documentIds.length){if(Ie.current=null,Re.current=!1,Ae(!1),Oe(null),A)try{await A(e,i.documentIds)}catch(e){alert(e instanceof Error?e.message:String(e))}return}let a=(()=>{try{return JSON.parse(r.dataTransfer.getData(`application/x-canvas-tree-path`))}catch{return null}})(),o=a?.path||r.dataTransfer.getData(`text/plain`),s=a?.treeName||Le.current||t;if(rv(s,o))return;let c=He(r)||Re.current;if(Ie.current=null,Le.current=t,Re.current=!1,Ae(!1),Oe(null),!o)return;let l=r.shiftKey,u=s!==t;if(!(!u&&o===e)&&!(!u&&!Be(o,e,c)))try{if(c&&E)await E(o,e,l,s,t);else if(!c&&T){let r=Fe.current&&!n&&!!F;await T(o,e,l,s,t,r?{mergeDown:r}:void 0)}}catch(e){alert(e instanceof Error?e.message:String(e))}},[Be,E,T,A,t,n,F]),Ye=ae.toLowerCase().trim(),Xe=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),pe({x:e.clientX,y:e.clientY,path:t,node:n})},[]),Ze=(0,X.useCallback)((e,t,n)=>{e.stopPropagation(),!n.metadata?.backendTrash&&(Ce.current=null,G(null),ye({x:e.clientX,y:e.clientY,path:t,node:n}))},[]),Qe=(0,X.useCallback)(e=>{if(!ve||!z)return;let t=ve.path,n={...H.get(t)??(Ce.current?.path===t?Ce.current.style:op(ve.node)),...e};Ce.current={path:t,style:n},G({path:t,style:n}),be(e=>new Map(e).set(t,n));let r=cp(ve.node.metadata,n),i=Se.current,a=i.get(t);a&&clearTimeout(a),i.set(t,setTimeout(()=>{i.delete(t),z(t,{metadata:r}).catch(e=>alert(e instanceof Error?e.message:String(e)))},350))},[ve,z,H]),$e=(0,X.useCallback)((e,t)=>{V?e===V.path?(le(null),de(new Map)):de(n=>{let r=new Map(n);return r.has(e)?r.delete(e):r.set(e,t),r}):(le({path:e,id:t}),de(new Map))},[V]),et=(0,X.useCallback)(async e=>{!B||!T||!E||B.treeName===t&&(e===B.path||e.startsWith(B.path+`/`))||(B.mode===`cut`?(await T(B.path,e,!1,B.treeName,t),ce(null),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:null}))):await E(B.path,e,!0,B.treeName,t))},[B,T,E,t]);(0,X.useEffect)(()=>{if(l)return;let e=e=>{let n=e.target;if(n?.tagName===`INPUT`||n?.tagName===`TEXTAREA`||e.key!==`F6`)return;if(e.preventDefault(),B?.mode===`cut`){et(a);return}let r={mode:`cut`,path:a,treeName:t};ce(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[B,et,l,a,t]);let tt=(0,X.useCallback)(async(e,t)=>{Ee(null);let r=e===`/`?`/${t}`:`${e}/${t}`;try{I4(e,n)&&R?await R(e,t)&&s(r):b&&await b(r,!0)&&s(r)}catch(e){alert(e instanceof Error?e.message:String(e))}},[b,R,s,n]),nt=(0,X.useCallback)(()=>{Ee(null)},[]),rt=(0,X.useCallback)((e,n)=>{let r={mode:n,path:e,treeName:t};ce(r),window.dispatchEvent(new CustomEvent(`tree:path-clipboard`,{detail:r}))},[t]),it=(0,X.useCallback)(r=>{if(!(l||Vf(r.target)||a&&rv(t,a))){if(Bf(r,`Mod+V`)){k?.length&&A&&a?(r.preventDefault(),A(a,k).catch(()=>{})):B&&a&&(r.preventDefault(),et(a).catch(e=>alert(e instanceof Error?e.message:String(e))));return}if(a&&a!==`/`&&(Bf(r,`Mod+C`)||!n&&Bf(r,`Mod+X`))){r.preventDefault(),rt(a,r.key.toLowerCase()===`x`?`cut`:`copy`);return}if(C&&(r.key===`Delete`||r.key===`Backspace`)&&!(!a||a===`/`)){if(r.preventDefault(),Zr(e,a)?.locked){alert(`"${a}" is locked`);return}confirm(`Remove "${a}"?`)&&_e(a,!1).catch(e=>alert(e instanceof Error?e.message:String(e)))}}},[l,C,_e,a,e,k,A,B,et,n,rt,t]),at=(0,X.useCallback)(()=>{Me(e=>{let t=!e;return ze.current=t,Re.current=t,Ae(t),t})},[]);if(c)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading tree…`});if(!e)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`No tree available`});let ot=V||ue.size>0,st={accordion:se,selectedPath:a,pendingPath:o,contentPath:g,readOnly:l,sourceLayer:V,targetLayers:ue,clipboard:B,searchQuery:Ye,inlineCreateParent:Te,onSelect:s,onShiftSelect:y,onShowContent:_,onCtrl:$e,onCtxMenu:Xe,onConfirmCreate:tt,onCancelCreate:nt,onOpenPicker:z?Ze:void 0,styleOverrides:H,dragOverPath:De,isCopyDrag:ke,onDragStart:Ve,onDragEnter:Ue,onDragOver:We,onDragLeave:Ke,onDragEnd:qe,onDrop:Je,resyncingPaths:oe,policyBadgeFor:n?void 0:m,removingPaths:me};return(0,Z.jsxs)(`div`,{className:`px-3 py-2 space-y-1.5 outline-none`,tabIndex:0,onKeyDown:it,children:[me.size>0&&(0,Z.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`space-y-1 rounded-md border bg-muted/50 p-2 text-xs`,children:[...me].map(([e,t])=>(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(we,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),(0,Z.jsxs)(`span`,{className:`min-w-0`,children:[(0,Z.jsx)(`span`,{className:`block`,children:t}),(0,Z.jsx)(`span`,{className:`block truncate text-muted-foreground`,title:e,children:e})]})]},e))}),!l&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-end px-1 pb-0.5 text-[10px]`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:at,title:`Toggle drag-drop mode (or hold Ctrl / Alt while dragging)`,className:K(`px-2 py-0.5 rounded-full border transition-colors select-none`,je?`border-success bg-success/15 text-success dark:text-success`:`border-border text-muted-foreground hover:bg-muted`),children:je?`Drag → Copy`:`Drag → Move`}),F&&!n&&!je&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>Pe(e=>(Fe.current=!e,!e)),title:`When moving a layer, also merge it into its new ancestors so the new path lists its documents`,className:K(`ml-1 px-2 py-0.5 rounded-full border transition-colors select-none`,Ne?`border-info bg-info/15 text-info dark:text-info`:`border-border text-muted-foreground hover:bg-muted`),children:Ne?`+ merge down`:`merge down: off`})]}),ot&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-1 pb-1 text-[10px] text-muted-foreground`,children:[(0,Z.jsx)(`span`,{children:V?`Source: ${V.path} · ${ue.size} target(s)`:`Select source with ⌃-click`}),(0,Z.jsx)(`button`,{type:`button`,className:`hover:text-foreground underline`,onClick:()=>{le(null),de(new Map)},children:`clear`})]}),(0,Z.jsxs)(`div`,{"data-active":a===`/`&&!g||void 0,className:K(`group relative flex min-h-11 items-center gap-2 rounded-md px-3 py-2.5 cursor-pointer transition-all select-none`,`shadow-elevation-3 hover:shadow-elevation-4 text-sm`,a===`/`&&!g?`bg-primary/[0.06]`:`bg-card hover:bg-primary/[0.04]`,De===`/`&&!l&&!ke&&`ring-2 ring-info bg-info-subtle/50`,De===`/`&&!l&&ke&&`ring-2 ring-success bg-success-subtle/50`),style:{borderRight:`4px solid transparent`},onClick:()=>s(`/`),onDragEnter:e=>{l||Ue(`/`,e)},onDragOver:e=>{l||We(`/`,e)},onDragLeave:e=>Ke(`/`,e),onDrop:e=>{l||Je(`/`,e)},onContextMenu:e=>{!l&&b&&(e.preventDefault(),pe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}}))},children:[(0,Z.jsx)(Ge,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{className:`flex-1 font-medium truncate`,children:[`/ `,h&&(0,Z.jsxs)(`span`,{className:`text-muted-foreground font-normal`,children:[`[`,h,`]`]})]}),!l&&b&&(0,Z.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(),pe({x:e.clientX,y:e.clientY,path:`/`,node:{id:``,name:`/`,label:`/`,type:`root`,description:``,color:null,locked:!1,children:[]}})},children:(0,Z.jsx)(Kt,{className:`w-4 h-4`})})]}),(0,Z.jsxs)(`div`,{className:se?`mt-1.5 border-t border-border/60`:`ml-[22px] mt-1.5 space-y-1.5`,children:[Te===`/`&&(0,Z.jsx)(z4,{onConfirm:e=>tt(`/`,e),onCancel:nt}),e.children?.map((t,n)=>(0,Z.jsx)(H4,{node:t,parentPath:`/`,depth:0,isLast:n===(e.children?.length??0)-1,...st},t.id||t.name)),!e.children?.length&&Te!==`/`&&(0,Z.jsx)(`div`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]}),fe&&(0,Z.jsx)(R4,{x:fe.x,y:fe.y,node:fe.node,path:fe.path,isBackendsTree:n,onClose:()=>pe(null),onShowContent:fe.node.metadata?.backendTrash?s:_,onRestoreTrash:l?void 0:r,onDiscardTrash:l?void 0:i,onOpenToSide:v?e=>v(e,t):void 0,sourceLayer:V,targetLayers:ue,clipboard:B,onStartInlineCreate:e=>Ee(e),onChangeIcon:z?()=>Ze({clientX:fe.x,clientY:fe.y,stopPropagation:()=>{}},fe.path,fe.node):void 0,onNewCanvas:x,onShareCanvas:S,onExportSubtree:D,onImportSubtree:l?void 0:O,onRemove:!l&&C&&![...me.keys()].some(e=>e===fe.path||e.startsWith(fe.path+`/`)||fe.path.startsWith(e+`/`))?_e:void 0,onRename:l?void 0:w,onLock:l?void 0:j,onUnlock:l?void 0:M,onDestroy:l?void 0:N,onMerge:l?void 0:P,onSubtract:l?void 0:ee,onMergeDown:l?void 0:F,onSubtractDown:l?void 0:I,onResyncBackend:L,onAddRule:u,onSyncFolderTree:d,onAddStoreRule:f,onStoragePolicy:!l&&!n?p:void 0,onRenameBackendFolder:te,onDeleteBackendFolder:ne,onCopy:e=>rt(e,`copy`),onCut:e=>rt(e,`cut`),onPaste:et,pastedDocumentIds:k,onPasteDocuments:A,isPinned:re?re(fe.path):!1,onTogglePin:ie?()=>ie(fe.path,fe.node):void 0}),ve&&z&&(0,Z.jsx)(rS,{x:ve.x,y:ve.y,current:H.get(ve.path)??op(ve.node),onChange:Qe,onClose:()=>ye(null)})]})}function W4(){let{state:e,closeM2:t,closeM1:n,closeM0:r,openM2:i}=zS(),a=Jm(),o=al(),s=e.selectedEntityId,{showToast:c}=Vr(),[l,u]=(0,X.useState)(null),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),[h,g]=(0,X.useState)(),[_,v]=(0,X.useState)(``),[y,b]=(0,X.useState)(`/`),[x,S]=(0,X.useState)(null),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(null),[D,O]=(0,X.useState)(!1),k=(0,X.useCallback)(async e=>{w(!0);try{let t=await as(e);f(t),E(null)}catch(e){E(e instanceof Error?e.message:`Failed to load the tree`)}finally{w(!1)}},[]);(0,X.useEffect)(()=>{if(!s)return;let e=s,t=!1;async function n(){try{let n=await fs(e);if(t)return;u(n),m(n.url||``),g(void 0),v(``),S(null),b(n.path||`/`),w(!0);try{let n=await as(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=mv({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,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(M4,{title:s||`Context`,icon:l?.icon||`ph:stack-fill`,accentColor:l?.color,onBack:t,action:(0,Z.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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})}),(0,Z.jsxs)(`div`,{className:`p-3 border-b border-border shrink-0`,children:[(0,Z.jsx)(`div`,{className:`text-[10px] text-muted-foreground mb-1.5 font-medium uppercase tracking-wide`,children:`Context URL`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(DT,{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:K(`text-xs transition-colors`,M&&`border-warning/60 bg-warning/10`),placeholder:`workspace://path`}),(0,Z.jsx)(Y,{size:`sm`,className:`h-9 px-2 text-xs shrink-0`,onClick:async()=>{if(!s)return;let e=s;O(!0);try{await qo(e,p,void 0,h);let t=await fs(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,Z.jsxs)(`p`,{className:`px-3 py-1 text-xs text-muted-foreground`,children:[`Destination tree: `,h,` · press Set to apply`]}),(0,Z.jsx)(`div`,{className:`px-3 py-2 border-b shrink-0`,children:(0,Z.jsx)(q,{"aria-label":`Search context tree`,placeholder:`Search paths…`,value:_,onChange:e=>v(e.target.value),className:`h-7 text-xs`})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[(0,Z.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,Z.jsx)(`p`,{className:`px-3 pb-1 text-xs text-destructive`,children:T}),(0,Z.jsx)(U4,{root:d,searchQuery:_,selectedPath:y,pendingPath:x,onSelect:j,isLoading:C,rootLabel:l?.workspaceName,...A})]})]})}function G4({items:e,activeId:t,onSelect:n}){let[r,i]=(0,X.useState)(``),a=e.filter(e=>_S(r,e.label,e.description||``));return(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:(0,Z.jsxs)(`div`,{className:`space-y-1 px-2`,children:[(0,Z.jsx)(q,{type:`search`,"aria-label":`Search settings sections`,placeholder:`Find a setting…`,className:`mb-3`,value:r,onChange:e=>i(e.target.value)}),!a.length&&(0,Z.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,Z.jsxs)(`button`,{type:`button`,"aria-current":r?`page`:void 0,onClick:()=>n(e.id),className:K(`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,Z.jsx)(`span`,{className:K(`shrink-0`,r?`text-foreground`:`text-muted-foreground`),children:e.icon}),(0,Z.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium text-foreground`,children:e.label}),e.description&&(0,Z.jsx)(`span`,{className:`mt-1 block text-xs leading-relaxed text-muted-foreground`,children:e.description})]}),(0,Z.jsx)(Ye,{className:K(`h-3.5 w-3.5 shrink-0`,r?`opacity-100`:`opacity-0`)})]},e.id)})]})})}function K4(){let{state:e,closeM2:t}=zS(),n=Jm(),r=al(),i=nl(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return fs(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?GT(c[3]):null,u=a?`/contexts/${a}`:null,d=(0,X.useMemo)(()=>WT.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:`Settings: ${o?.name||a||`Context`}`,icon:o?.icon||`ph:stack-fill`,accentColor:o?.color??null,onBack:()=>u&&!n?r(u):t(),action:(0,Z.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,Z.jsx)(gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(G4,{items:d,activeId:l,onSelect:e=>a&&r(`/contexts/${a}/settings/${e}`)})]})}function q4(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await Xr();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch workspaces:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>id.emit(`subscribe`,{channel:`workspace`}),r=()=>id.emit(`unsubscribe`,{channel:`workspace`}),i=id.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])=>id.on(e,t)),()=>{r(),i?.(),l.forEach(([e,t])=>id.off(e,t))}},[e,s]),(0,X.useEffect)(()=>{let e=()=>{a.current=!1,s()};return window.addEventListener(`workspaces:refresh`,e),()=>{window.removeEventListener(`workspaces:refresh`,e)}},[s]),{workspaces:(0,X.useMemo)(()=>$S(t),[t]),isLoading:r,refresh:c}}function J4({status:e}){return(0,Z.jsx)(`span`,{className:K(`inline-block w-2 h-2 rounded-full shrink-0`,e===`active`?`bg-success`:e===`error`?`bg-destructive`:`bg-muted-foreground`),title:e})}function Y4(){let e=Zx(),{state:t,selectEntity:n,openM2:r,closeM2:i}=zS(),a=Jm(),{workspaces:o,isLoading:s}=q4(t.activeSection===`workspaces`),{showToast:l}=Vr(),u=al(),[d,f]=(0,X.useState)(new Set),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(new Map),_=(0,X.useRef)(new Map),[v,y]=(0,X.useState)(null),b=v&&v.base===o?v.order:o,{rowProps:x,handleProps:S,draggingIndex:C,insertLineClass:w}=nC((e,t)=>{let n=eC(b,e,t);y({base:o,order:n}),tC(n,(e,t)=>Ba(Qx(e),{order:t})).then(({failed:e})=>{window.dispatchEvent(new CustomEvent(`workspaces:refresh`)),e&&l({title:`Partial reorder`,description:`${e} workspace(s) could not be reordered`,variant:`destructive`})})}),T=e=>h.get(Qx(e))??{icon:e.icon??void 0,color:e.color??void 0},E=(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),Ba(e,t).then(()=>window.dispatchEvent(new CustomEvent(`workspaces:refresh`))).catch(e=>l({title:`Error`,description:e instanceof Error?e.message:`Update failed`,variant:`destructive`}))},350))},D=e=>{n(Qx(e)),r(`detail`,Qx(e)),!a&&pS(Qx(e))&&u(mS(Qx(e)))},O=async(e,t)=>{e.stopPropagation(),f(e=>new Set(e).add(Qx(t)));try{await Ua(Qx(t)),l({title:`Success`,description:`${t.label||t.name} started`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Start failed`,variant:`destructive`})}finally{f(e=>{let n=new Set(e);return n.delete(Qx(t)),n})}},k=async(e,t)=>{e.stopPropagation(),f(e=>new Set(e).add(Qx(t)));try{await eo(Qx(t)),l({title:`Success`,description:`${t.label||t.name} stopped`}),window.dispatchEvent(new CustomEvent(`workspaces:refresh`))}catch(e){l({title:`Error`,description:e instanceof Error?e.message:`Stop failed`,variant:`destructive`})}finally{f(e=>{let n=new Set(e);return n.delete(Qx(t)),n})}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Workspaces`}),!e.local&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i(),u(`/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,Z.jsx)(U,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Z.jsx)(`div`,{className:`space-y-1.5 px-2`,children:b.map((e,i)=>{let o=t.selectedEntityId===Qx(e),s=d.has(Qx(e)),l=e.status!==`active`,f=T(e),p=hp(f.color);return(0,Z.jsxs)(`div`,{...x(i),"data-active":o||void 0,className:K(`group relative rounded-md py-2.5 pl-3 pr-7 transition-all shadow-elevation-1`,o?`bg-accent shadow cursor-pointer hover:shadow`:l?`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:()=>{l||D(e)},children:[(0,Z.jsx)(`button`,{type:`button`,...S(i),title:`Drag to reorder`,"aria-label":`Drag to reorder`,className:K(`absolute inset-y-0 right-0 flex w-4 cursor-grab items-center justify-center rounded-r-md active:cursor-grabbing`,!p&&`bg-muted`),style:p?{backgroundColor:p}:void 0,children:(0,Z.jsx)(Je,{className:K(`h-3.5 w-3.5`,gp(p))})}),(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`button`,{type:`button`,title:`Change icon`,onClick:t=>{xr()||(t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Qx(e)}))},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),m({x:Math.min(t.clientX,window.innerWidth-290),y:Math.min(t.clientY,window.innerHeight-360),name:Qx(e)})},className:`shrink-0 rounded p-0.5 hover:bg-muted-foreground/10 touch-target`,children:(0,Z.jsx)(c,{icon:f.icon||`ph:stack-fill`,width:18,height:18,color:p,className:K(!p&&`text-muted-foreground`)})}),(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(J4,{status:e.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Z.jsx)(`button`,{type:`button`,disabled:s,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:`Stop`,children:(0,Z.jsx)(nn,{className:`w-3.5 h-3.5`})}):(0,Z.jsx)(`button`,{type:`button`,disabled:s,onClick:t=>O(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,Z.jsx)(De,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),n(Qx(e)),a?r(`settings`,Qx(e)):u(`/workspaces/${Qx(e)}/settings/general`)},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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 pl-3.5`,children:[e.host&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.host}),e.ownerEmail&&(0,Z.jsx)(`span`,{className:`text-[10px] text-muted-foreground truncate`,children:e.ownerEmail})]})]},e.id||e.name)})})}),p&&(()=>{let e=o.find(e=>Qx(e)===p.name);if(!e)return null;let t=T(e);return(0,Z.jsx)(rS,{x:p.x,y:p.y,current:t,onChange:e=>E(p.name,t,e),onClose:()=>m(null)})})()]})}function X4(e,t){let n=(0,X.useRef)(null),r=(0,X.useRef)(0);return(0,X.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=oO(e);if(!r)return;let i=iO(),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=cO(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 Z4(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 Q4(e,t,n,r=!1,i=`forward`,a=`copy`,o){let s=Z4(e,t,n,r);if(i===`forward`)return[s];let c=t.split(`/`).filter(Boolean);if(c.length<2||t.includes(`{{`)||c.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 l=o.address,u=o.key,d=[...new Map(n.map(e=>[`${e.tree}:${e.path}`,e])).values()],f={id:`${e}-reverse`,enabled:!0,description:`Auto-Link ${d.map(e=>`${e.tree}:${e.path}`).join(`, `)} → backends:${t} (${a})`,cascade:!1,when:{event:[`document.inserted`,`document.linked`],[r?`path`:`pathExact`]:d.map(e=>`${e.tree}:${e.path}`)},then:[{action:`store`,to:l,folder:u,mode:a,autoLink:!0,onConflict:`error`,...r?{recursive:!0}:{}}]};return i===`both`?[s,f]:[f]}function $4({workspaceId:e,sourcePath:t,onClose:n,onManageRules:r}){let[i,a]=(0,X.useState)([]),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(`forward`),[u,d]=(0,X.useState)(`copy`),[f,p]=(0,X.useState)(0),[m,h]=(0,X.useState)(!1),[g,_]=(0,X.useState)(!0),[v]=(0,X.useState)(()=>`autolink-${crypto.randomUUID()}`),[y,b]=(0,X.useState)(!1),[x,S]=(0,X.useState)(!1),[C,w]=(0,X.useState)(!1),[T,E]=(0,X.useState)(``),[D,O]=(0,X.useState)(0),[k,A]=(0,X.useState)(0),[j,M]=(0,X.useState)(0),[N]=(0,X.useState)(Gv),[P,ee]=(0,X.useState)(1),[F,I]=(0,X.useState)(0),[L,R]=(0,X.useState)(),[te,ne]=(0,X.useState)(0);Ff(n,!x&&!o);let z=()=>{x||n()};return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(Hp,{onClose:z,children:(0,Z.jsxs)(`section`,{role:`dialog`,"aria-modal":`true`,"aria-labelledby":`autolink-title`,className:`${Vp} flex flex-col overflow-hidden rounded-2xl border bg-card shadow-elevation-4`,children:[(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`h2`,{id:`autolink-title`,className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Z.jsx)(Gt,{className:`h-4 w-4`}),`Auto-Link folder`]}),(0,Z.jsx)(`button`,{type:`button`,onClick:z,disabled:x,"aria-label":`Close`,className:`p-1 disabled:opacity-40`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-5 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Backend folder`}),(0,Z.jsx)(`p`,{className:`mt-1 break-words text-sm`,children:t})]}),(0,Z.jsxs)(`fieldset`,{disabled:x||y,className:`space-y-2 text-sm`,children:[(0,Z.jsx)(`label`,{className:`block font-medium`,htmlFor:`autolink-direction`,children:`Direction`}),(0,Z.jsxs)(`select`,{id:`autolink-direction`,className:`w-full rounded-md border bg-background p-2`,value:c,onChange:e=>l(e.target.value),children:[(0,Z.jsx)(`option`,{value:`forward`,children:`Backend → virtual tree`}),(0,Z.jsx)(`option`,{value:`reverse`,children:`Virtual tree → backend`}),(0,Z.jsx)(`option`,{value:`both`,children:`Both`})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c===`forward`?`Link indexed files into your virtual paths. Files stay where they are.`:`Store files explicitly added to these virtual paths in the backend folder. Documents appearing through context filters are not copied.`}),c!==`forward`&&(0,Z.jsxs)(`details`,{children:[(0,Z.jsx)(`summary`,{className:`cursor-pointer`,children:`Advanced: storage operation`}),(0,Z.jsxs)(`label`,{className:`mt-2 flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:u===`move`,onChange:e=>d(e.target.checked?`move`:`copy`)}),`Move instead of copy — release the source only after the destination is safely stored.`]})]})]}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(`h3`,{className:`text-sm font-medium`,children:`Virtual paths`}),i.map((e,t)=>(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 rounded-lg border p-2 text-sm`,children:[(0,Z.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.tree===`context`?`Context tree`:`Directory tree`}),(0,Z.jsx)(`p`,{className:`break-words`,children:e.path})]}),!y&&(0,Z.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.tree}:${e.path}`,disabled:x,onClick:()=>a(e=>e.filter((e,n)=>n!==t)),children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]},`${e.tree}:${e.path}`)),!y&&(0,Z.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:x,onClick:()=>s(!0),children:[(0,Z.jsx)(U,{className:`mr-1 h-4 w-4`}),`Add virtual path…`]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Choose a context path, a directory path, or both.`})]}),(0,Z.jsxs)(`fieldset`,{disabled:x||y,className:`space-y-3 text-sm`,children:[(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:m,onChange:e=>h(e.target.checked),className:`mt-1`}),`Recursive — include subfolders and recreate their structure at each destination`]}),(0,Z.jsxs)(`label`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked),className:`mt-1`}),`Apply to existing documents`]})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Without Recursive, only direct folder contents are included. Context paths keep their usual layer membership. Both creates two independently manageable rules in workspace Rules. Removing rules keeps existing files and links. Renames and deletions are not synchronized. Filename conflicts stop the transfer without overwriting.`}),x&&(0,Z.jsx)(`p`,{role:`status`,className:`text-sm`,children:y?`${P>1?`Rule ${Math.min(f+1,P)}/${P}: `:``}Processing ${F}${L===void 0?``:`/${L}`} existing documents… ${k} matches applied.`:`Saving Auto-Link…`}),C&&(0,Z.jsxs)(`p`,{role:`status`,className:`text-sm`,children:[`Auto-Link is enabled for future documents.`,g?` ${te} document${P>1?` checks across ${P} rules`:`s checked`}. ${k} matches applied.`:``]}),j>0&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[j,` document operations failed. Check the rule’s run log in Rules and rerun it after resolving the errors.`]}),T&&(0,Z.jsxs)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:[y?`Auto-Link is enabled. `:``,T]})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2 border-t p-3`,children:[(0,Z.jsx)(Y,{variant:`ghost`,disabled:x,onClick:r,children:`Manage rules`}),C?(0,Z.jsx)(Y,{onClick:n,children:`Done`}):(0,Z.jsx)(Y,{disabled:x||!i.length,onClick:async()=>{if(!x){S(!0),E(``);try{let n=c===`forward`?void 0:Jo(t,await Ta(e));if(n?.driver===`cacache`)throw Error(`Choose a backend that preserves folder paths.`);let r=Q4(v,t,i,m,c,u,n);if(ee(r.length),y||(await $v(e,r),b(!0)),g){for(let t=f;t<r.length;t++){let n=t===f?D:0;I(n),R(void 0);let i=await Jv(e,{ruleId:r[t].id,limit:1,offset:n,dryRun:!0});for(R(i.total);n!==null;){let i=await Jv(e,{ruleId:r[t].id,limit:N,offset:n});if(A(e=>e+i.matched-i.failed),M(e=>e+i.failed),I(n+i.processed),ne(e=>e+i.processed),R(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&&O(n)}p(t+1),O(0)}window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}w(!0)}catch(e){E(e instanceof Error?e.message:`Could not configure Auto-Link`)}finally{S(!1)}}},children:x?`Applying…`:y?`Retry existing documents`:`Enable Auto-Link`})]})]})}),o&&(0,Z.jsx)(Hp,{onClose:()=>s(!1),children:(0,Z.jsx)(Bp,{fixedWorkspaceName:e,title:`Choose virtual paths`,confirmLabel:`Add paths`,sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,onClose:()=>s(!1),onConfirm:(e,t)=>{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)}})})]})}async function e3(){return await J.get(`${Rr}/users/me/config/webui`)??{}}async function t3(e){return await J.put(`${Rr}/users/me/config/webui`,e)??e}var n3=`application/x-canvas-workspace-pin`;function r3({pins:e,isLoading:t,searchQuery:n=``,activeKey:r,onOpen:i,onShowInTree:a,onUnpin:o,onMove:s}){let[l,u]=(0,X.useState)(null),[d,f]=(0,X.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=()=>{u(null),f(null)},g=async()=>{let t=d,n=l;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,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading pins…`}):e.length?m.length?(0,Z.jsx)(`div`,{className:`p-2 flex flex-col gap-2`,onDragOver:e=>{l&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`)},onDrop:e=>{e.preventDefault(),l&&!d&&f({id:null,before:!1}),g()},children:m.map(e=>{let t=e.resolvable===!1,n=hp(e.color),s=e.icon||(e.type===`canvas`?`ph:squares-four-fill`:`ph:folder-fill`),m=r===po(e.tree,e.path),_=d?.id===e.id&&d.before,v=d?.id===e.id&&!d.before;return(0,Z.jsxs)(`div`,{role:`button`,tabIndex:0,"data-active":m||void 0,draggable:!p,onDragStart:t=>{t.dataTransfer.setData(n3,e.id),t.dataTransfer.setData(`text/plain`,e.path),t.dataTransfer.effectAllowed=`move`,u(e.id)},onDragEnd:h,onDragOver:t=>{if(!l||l===e.id)return;t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientY<n.top+n.height/2;f(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:K(`group relative flex items-stretch gap-2.5 rounded-lg 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`,l===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,Z.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,Z.jsx)(at,{className:`w-5 h-5 text-warning`}):(0,Z.jsx)(c,{icon:s,width:22,height:22,color:n,className:K(!n&&(e.type===`canvas`?`text-primary`:`text-muted-foreground`))})}),(0,Z.jsxs)(`div`,{className:`flex flex-col min-w-0 flex-1 py-2 pr-1`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold leading-tight truncate`,children:e.label||e.name||e.path.split(`/`).pop()}),e.locked&&(0,Z.jsx)(Dt,{className:`w-3 h-3 shrink-0 text-warning`})]}),(0,Z.jsxs)(`span`,{className:`text-[11px] text-muted-foreground truncate leading-tight font-mono mt-0.5`,children:[e.tree,`:`,e.path]}),e.description&&(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground/80 truncate leading-tight mt-1`,children:e.description}),t&&(0,Z.jsx)(`span`,{className:`text-[11px] text-warning leading-tight mt-1`,children:`Folder no longer exists`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-col items-center justify-between py-1.5 pr-1.5 shrink-0`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.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,Z.jsx)(Mn,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(V,{className:`w-3.5 h-3.5`})})]}),!p&&(0,Z.jsx)(Je,{className:`w-3.5 h-3.5 text-muted-foreground/50 cursor-grab active:cursor-grabbing`,"aria-hidden":!0})]})]},e.id)})}):(0,Z.jsxs)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:[`No pins match “`,n,`”`]}):(0,Z.jsxs)(`div`,{className:`px-3 py-6 text-xs text-muted-foreground text-center space-y-1`,children:[(0,Z.jsx)(`p`,{children:`No pinned folders yet.`}),(0,Z.jsxs)(`p`,{className:`text-muted-foreground/70`,children:[`Right-click a folder in the context, directory or backends tree and choose `,(0,Z.jsx)(`span`,{className:`font-medium`,children:`Pin`}),`.`]})]})}var i3=[`pins`,`context`,`layers`,`directory`,`backends`],a3=e=>typeof e==`string`&&i3.includes(e),o3=e=>{let t=Array.isArray(e)?e.filter(a3).filter((e,t,n)=>n.indexOf(e)===t):[];return[...t,...i3.filter(e=>!t.includes(e))]},s3={pins:(0,Z.jsx)(R,{className:`w-3.5 h-3.5`}),context:(0,Z.jsx)(We,{className:`w-3.5 h-3.5`}),layers:(0,Z.jsx)(Ct,{className:`w-3.5 h-3.5`}),directory:(0,Z.jsx)(Mn,{className:`w-3.5 h-3.5`}),backends:(0,Z.jsx)(wt,{className:`w-3.5 h-3.5`})},c3={pins:`Pins`,context:`Context tree`,layers:`Context layers`,directory:`Directory tree`,backends:`Backends tree`},l3=e=>e===`directory`||e===`backends`?e:ao,u3=(e,t)=>t?`layers`:e===`directory`?`directory`:e===`backends`?`backends`:`context`;function d3(){let{state:e}=zS();return e.selectedEntityId?(0,Z.jsx)(lC,{workspaceName:e.selectedEntityId,children:(0,Z.jsx)(f3,{},e.selectedEntityId)}):null}function f3(){let{state:e,closeM2:t,openM2:n}=zS(),r=s_(),i=Jm(),a=e.selectedEntityId,o=al(),s=nl(),{treeName:c,path:l}=nb(s.pathname),u=new URLSearchParams(s.search).get(`layer`)===`1`,d=new URLSearchParams(s.search).get(`layerId`),f=/\/trees\/|\/path(\/|$)/.test(s.pathname)||!!d,p=f?u3(c,d):i3[0],[m,h]=(0,X.useState)(null),[g,_]=(0,X.useState)(null),[v,y]=(0,X.useState)({icon:null,color:null}),[b,x]=(0,X.useState)(p),[S,C]=(0,X.useState)(null),[w,T]=(0,X.useState)(null),[E,D]=(0,X.useState)(null),[O,k]=(0,X.useState)([]),[A,j]=(0,X.useState)(!1),[M,N]=(0,X.useState)(!1),[P,ee]=(0,X.useState)(!1),[F,I]=(0,X.useState)(!1),[L,R]=(0,X.useState)(l),[te,ne]=(0,X.useState)(new Set),[z,re]=(0,X.useState)(u&&l!==`/`?l:null),[ie,ae]=(0,X.useState)(``),[oe,se]=(0,X.useState)(null),[B,ce]=(0,X.useState)(null),[V,le]=(0,X.useState)(null),{policies:ue,refresh:de}=Q0(a),fe=(0,X.useCallback)(e=>{if(b!==`context`&&b!==`directory`||!ue.length)return null;let t=R0(ue,b,e);return t.length?`Storage policy targets: ${z0(t)} (see Settings for transfer status)`:null},[b,ue]),[pe,me]=(0,X.useState)([]),[he,ge]=(0,X.useState)(!1),[_e,ve]=(0,X.useState)(!1),ye=(0,X.useRef)(null),H=(0,X.useRef)(!1),[be,U]=(0,X.useState)(!1),[xe,Se]=(0,X.useState)(i3),Ce=!f;(0,X.useEffect)(()=>{let e=!1;return e3().then(t=>{if(e)return;let n=o3(t?.m2?.tabOrder);Se(n),Ce&&x(e=>e===i3[0]?n[0]:e)}).catch(()=>{}),()=>{e=!0}},[]);let W=(0,X.useCallback)(async e=>{let t=xe;Se(e);try{let t=await e3();await t3({...t,m2:{...t.m2,tabOrder:e}})}catch{Se(t)}},[xe]),[G,we]=(0,X.useState)(null),[Te,Ee]=(0,X.useState)(null),De=()=>{we(null),Ee(null)},Oe=()=>{if(G&&Te&&G!==Te.id){let e=xe.filter(e=>e!==G),t=e.indexOf(Te.id);t>=0&&(e.splice(Te.before?t:t+1,0,G),e.some((e,t)=>e!==xe[t])&&W(e))}De()};(0,X.useEffect)(()=>{let e=e=>se(e.detail??null);return window.addEventListener(`documents:clipboard`,e),()=>window.removeEventListener(`documents:clipboard`,e)},[]);let[ke,Ae]=(0,X.useState)(l);l!==ke&&(Ae(l),R(l));let je=(0,X.useRef)(new Map),Me=(0,X.useCallback)(async(e,t,n=!1,r=!1)=>{let i=Symbol();je.current.set(t,i);let a=()=>je.current.get(t)===i,o=t===`context`?j:t===`directory`?N:ee,s=t===`context`?C:t===`directory`?T:D;n||o(!0);try{n&&!r&&Sa(e,t);let i=await Gi(e,t);a()&&s(i)}catch{}finally{a()&&o(!1)}},[]),Ne=(0,X.useCallback)(async(e,t=!1)=>{let n=Symbol();je.current.set(`pins`,n);let r=()=>je.current.get(`pins`)===n;t||ge(!0);try{let t=await _o(e);r()&&me(t)}catch{}finally{r()&&ge(!1)}},[]),Pe=(0,X.useCallback)(async(e,t=!1)=>{let n=Symbol();je.current.set(`layers`,n);let r=()=>je.current.get(`layers`)===n;t||I(!0);try{let t=await Vi(e,`context`);r()&&k(t)}catch{}finally{r()&&I(!1)}},[]);(0,X.useEffect)(()=>{if(!a)return;let e=a,t=!1,n=je.current;async function r(){Zi(e).then(e=>{t||(h(e.label||null),_(e.id||null),y({icon:e.icon??null,color:e.color??null}))}).catch(()=>{}),await Promise.all([Me(e,`context`),Me(e,`directory`),Me(e,`backends`),Pe(e),Ne(e)])}return r(),()=>{t=!0,n.clear()}},[a,Me,Pe,Ne]);let Fe=(0,X.useCallback)((e,t,n=!1)=>{for(let r of[`context`,`directory`,`backends`])(!t||t===r)&&Me(e,r,!0,n);(!t||t===`context`)&&Pe(e,!0),Ne(e,!0)},[Me,Pe,Ne]),Ie=(0,X.useCallback)(()=>{a&&Fe(a)},[a,Fe]);(0,X.useEffect)(()=>{if(!a)return;let e=e=>{e.detail?.workspaceName&&e.detail.workspaceName!==a||Fe(a,e.detail?.treeName,e.detail?.cacheInvalidated)};return window.addEventListener(`workspace:tree:refresh`,e),()=>window.removeEventListener(`workspace:tree:refresh`,e)},[a,Fe]),(0,X.useEffect)(()=>{if(!a)return;let e=!1;return Ta(a).then(t=>{e||ne(new Set(t.filter(e=>e.resyncing&&e.treePath).map(e=>e.treePath)))}).catch(()=>{}),()=>{e=!0}},[a]),(0,X.useEffect)(()=>{if(!a)return;let e=[`workspace:${a}`,g?`workspace:${g}`:null].filter(Boolean),t=()=>e.forEach(e=>id.emit(`subscribe`,{channel:e})),n=id.on(`connect`,t);t();let r=tw(a,g),i=e=>{if(e?.workspaceId&&g&&e.workspaceId!==g)return;let t=e?.treePath;t&&ne(n=>{let r=new Set(n);return e.resyncing?r.add(t):r.delete(t),r})};id.on(`backend.resync.changed`,i);let o=e=>{e?.workspaceId&&g&&e.workspaceId!==g||Ne(a,!0)};return id.on(`pins.changed`,o),()=>{r(),n?.(),id.off(`backend.resync.changed`,i),id.off(`pins.changed`,o)}},[a,g,Ne]);let[Le,Re]=(0,X.useState)(null),ze=`${s.pathname}|${s.search}`;if(ze!==Le){Re(ze);let{treeName:e,path:t}=nb(s.pathname),n=new URLSearchParams(s.search).get(`layerId`),r=/\/trees\/|\/path(\/|$)/.test(s.pathname)||!!n;_e?ve(!1):x(r||be?r?u3(e,n):b:xe[0]),R(t),re(t===`/`?null:t)}let{showToast:Be,showProgress:Ve}=Vr(),He=(0,X.useCallback)(async e=>{if(!a)return!1;let t=Av(e);if(!t)throw Error(`Not a backend folder`);let n=Pv(await gv(a));if(!n)throw Error(`No backend-tree-sync hook in this workspace (Git/internal/hooks/started/). Recreate the seed hooks from Settings → Hooks.`);let r=await Yv(a,{hookFile:n,payload:{backend:t.backend,subdir:t.rel,target:jv(e)}});if(r.status===`error`)throw Error(r.error||`Sync failed`);return Be({title:`Folders synced`,description:`${t.backend}${t.rel?`/${t.rel}`:``} → ${jv(e)} (see Hooks → Runs)`}),Fe(a),!0},[a,Be,Fe]),Ue=mv({workspaceId:a??void 0,treeName:l3(b),onRefresh:Ie}),We=new Set(pe.map(e=>po(e.tree,e.path))),Ge=l3(b),Ke=(0,X.useCallback)(e=>We.has(po(Ge,e)),[pe,Ge]),qe=(0,X.useCallback)(async e=>{if(!a)return;let t=pe.find(t=>po(t.tree,t.path)===po(Ge,e));t?await xa(a,t.id):await gi(a,e,Ge),await Ne(a)},[a,pe,Ge,Ne]),Je=(0,X.useCallback)(async e=>{if(a){me(t=>t.filter(t=>t.id!==e.id));try{await xa(a,e.id)}finally{await Ne(a)}}},[a,Ne]),Ye=(0,X.useCallback)(async(e,t)=>{if(!a)return;let n=pe.find(t=>t.id===e);if(!n)return;let r=pe.filter(t=>t.id!==e),i=t===null?r.length:r.findIndex(e=>e.id===t);if(i===-1)return;let o=[...r.slice(0,i),n,...r.slice(i)];if(!o.every((e,t)=>e===pe[t])){me(o);try{me(await Qa(a,o.map(e=>e.id)))}catch(e){throw await Ne(a),e}}},[a,pe,Ne]),Xe=(0,X.useCallback)(e=>{if(!a)return;ve(!0),R(e.path),re(null);let t=rb(a,e.path,e.tree);if(r){r.activateRow(`pin:${a}:${e.id}`,e.label||e.name||e.path,t);return}o(t)},[a,o,r]),Ze=(0,X.useCallback)(e=>{!a||e.resolvable===!1||(ve(!1),U(!0),x(u3(e.tree)),R(e.path),re(null),ae(``),H.current=!0,r?.setFocus(`main`),o(rb(a,e.path,e.tree)))},[a,o,r]),Qe=b===`context`?S:b===`directory`?w:b===`backends`?E:null,$e=b===`context`?A:b===`directory`?M:b===`backends`&&P;(0,X.useEffect)(()=>{if(!H.current||$e||b===`pins`)return;let e=ye.current?.querySelector(`[data-active="true"]`);e&&(e.scrollIntoView({block:`nearest`,inline:`nearest`}),H.current=!1)},[b,L,Qe,$e]);let et=(0,X.useCallback)(e=>{U(!0),x(e),R(`/`),re(null),ae(``)},[]),tt=(0,X.useCallback)(e=>{et(sO(xe,b,e))},[xe,b,et]),nt=X4(e.m2Open,tt),rt=e=>{re(null),R(e);let t=l3(b);r?.setFocus(`main`),o(rb(a,e,t))},it=(0,X.useCallback)((e,t)=>{R(e),re(e);let n=l3(b),i=new URLSearchParams;i.set(`layer`,`1`),t&&i.set(`layerId`,t),r?.setFocus(`main`),o(`${rb(a,e,n)}?${i.toString()}`)},[a,b,o,r]),at=(0,X.useCallback)((e,t)=>{if(a){if(r){r.openCanvas({kind:`route`,location:rb(a,e,t)});return}window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:a,treeName:t,path:e}}))}},[a,r]),ot=(0,X.useCallback)(async e=>{if(!a)return;let t=l3(b),n=await ra(a,e,t),r=`${window.location.origin}${n.url}`;await navigator.clipboard?.writeText(r),alert(`Canvas share link copied:\n${r}`)},[a,b]),st=ie.toLowerCase().trim(),ct=st?O.filter(e=>e.name.toLowerCase().includes(st)||(e.label||``).toLowerCase().includes(st)||(e.description||``).toLowerCase().includes(st)):O;return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(M4,{title:m||a||`Workspace`,icon:v.icon||`ph:stack-fill`,accentColor:v.color,onBack:t,action:(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>a&&o(mS(a)),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,Z.jsx)(gn,{className:`w-3.5 h-3.5`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{i?n(`settings`,a??null):o(`/workspaces/${a}/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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})]})}),(0,Z.jsx)(`div`,{...nt,className:`flex border-b border-border shrink-0 touch-pan-y`,"aria-label":`Workspace trees`,children:xe.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>et(e),title:`${c3[e]} — drag to reorder; the first tab opens by default`,"aria-label":c3[e],"aria-pressed":b===e,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(`text/plain`,e),t.dataTransfer.effectAllowed=`move`,we(e)},onDragEnd:De,onDragOver:t=>{if(!G||G===e)return;t.preventDefault(),t.dataTransfer.dropEffect=`move`;let n=t.currentTarget.getBoundingClientRect(),r=t.clientX<n.left+n.width/2;Ee(t=>t?.id===e&&t.before===r?t:{id:e,before:r})},onDrop:e=>{e.preventDefault(),Oe()},className:K(`relative flex-1 flex items-center justify-center py-2 transition-colors`,b===e?`text-foreground border-b-2 border-foreground -mb-px`:`text-muted-foreground hover:text-foreground`,G===e&&`opacity-40`,Te?.id===e&&Te.before&&`shadow-[inset_2px_0_0_0_hsl(var(--primary))]`,Te?.id===e&&!Te.before&&`shadow-[inset_-2px_0_0_0_hsl(var(--primary))]`),children:[s3[e],e===`pins`&&pe.length>0&&(0,Z.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:pe.length})]},e))}),(0,Z.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border shrink-0 shadow-elevation-2 z-10`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5 rounded-md border bg-muted/40 px-2 py-1`,children:[(0,Z.jsx)(pr,{className:`w-3 h-3 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`input`,{className:`flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground min-w-0`,placeholder:b===`layers`?`Search layers…`:b===`pins`?`Search pins…`:`Search paths…`,value:ie,onChange:e=>ae(e.target.value)})]})}),(0,Z.jsx)(`div`,{ref:ye,className:`flex-1 overflow-y-auto`,children:b===`pins`?(0,Z.jsx)(r3,{pins:pe,isLoading:he,searchQuery:ie,activeKey:po(c,l),onOpen:Xe,onShowInTree:Ze,onUnpin:Je,onMove:Ye}):b===`layers`?(0,Z.jsx)(y3,{layers:ct,isLoading:F,wsName:a??``,onSelect:e=>{let t=new URLSearchParams;t.set(`layerId`,e.id),t.set(`layer`,`1`),o(`${rb(a,`/`)}?${t.toString()}`)},onLock:async e=>{await Ma(a,e.id,a,`context`),Fe(a)},onUnlock:async e=>{await ga(a,e.id,a,`context`),Fe(a)},onRename:async(e,t)=>{await yi(a,e.id,t,`context`),Fe(a)},onDestroy:async e=>{confirm(`Destroy layer "${e.label||e.name}"? This cannot be undone.`)&&(await Oi(a,e.id,`context`),Fe(a))}}):(0,Z.jsx)(U4,{root:Qe,treeName:b,isBackendsTree:b===`backends`,onRestoreTrash:a?e=>dv(a,e):void 0,onDiscardTrash:a?e=>pv(a,e):void 0,onShiftSelect:r?e=>at(e,l3(b)):void 0,selectedPath:L,contentPath:z,onSelect:rt,onShowContent:b===`context`?it:void 0,onOpenToSide:at,onShareCanvas:ot,onNewCanvas:a&&b!==`backends`?e=>{o(`${rb(a,e,b)}?createCanvas=1`)}:void 0,isLoading:$e,rootLabel:a??void 0,searchQuery:ie,resyncingPaths:b===`backends`?te:void 0,onAddRule:a&&b===`backends`?ce:void 0,onSyncFolderTree:a&&b===`backends`?He:void 0,onAddStoreRule:a?(e,t=`store`)=>{let n=b===`backends`?(()=>{let n=Av(e);return{kind:t,storeTo:n?.backend||``,storeFolder:n?.rel||``}})():{kind:t,path:`${b===`directory`?`dir`:`ctx`}:${e}`,storeFolder:t===`download`?`Downloads`:Nv(e)};o(`/workspaces/${a}/settings/hooks?${Mv(n).toString()}`)}:void 0,onStoragePolicy:a&&(b===`context`||b===`directory`)?e=>le(k0(b,e)):void 0,policyBadgeFor:fe,pastedDocumentIds:oe?.documentIds,isPathPinned:Ke,onTogglePin:a?qe:void 0,onPasteDocuments:a&&b!==`backends`?async(e,t)=>{let n=b===`directory`?`directory`:`context`,r=b===`directory`?`directory`:ao,i=Ve({title:`Pasting…`,description:`${t.length} document(s) → "${e}"`}),o=!1;try{o=await li(a,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(o?{title:`Success`,description:`${t.length} document(s) pasted to "${e}"`}:void 0),o&&(oe&&(se(null),window.dispatchEvent(new CustomEvent(`documents:clipboard`,{detail:null}))),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:a,path:e,treeName:r}}))),o}:void 0,...Ue})}),B&&a&&(0,Z.jsx)($4,{workspaceId:a,sourcePath:B,onClose:()=>ce(null),onManageRules:()=>{ce(null),o(`/workspaces/${a}/settings/hooks?section=rules`)}}),V&&a&&(0,Z.jsx)(U0,{workspaceId:a,path:V,onClose:()=>le(null),onSaved:()=>{de()}})]})}var p3={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}},m3=100,h3=e=>e&&e.charAt(0).toUpperCase()+e.slice(1),g3=e=>p3[e]??{label:`${h3(e)} layers`,order:m3};function _3({type:e}){return e===`canvas`?(0,Z.jsx)($n,{className:`w-3.5 h-3.5 shrink-0 text-primary`,"aria-label":`Canvas`}):e===`dataset`?(0,Z.jsx)(wt,{className:`w-3.5 h-3.5 shrink-0 text-secondary`,"aria-label":`Dataset`}):(0,Z.jsx)(Ct,{className:`w-3.5 h-3.5 shrink-0 text-muted-foreground/60`,"aria-label":`Layer`})}function v3(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:g3(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 y3({layers:e,isLoading:t,onSelect:n,onLock:r,onUnlock:i,onRename:a,onDestroy:o}){let[s,c]=(0,X.useState)(null),l=(0,X.useRef)(null);if((0,X.useEffect)(()=>{s&&l.current?.focus()},[s]),t)return(0,Z.jsx)(`div`,{className:`px-3 py-3 text-xs text-muted-foreground`,children:`Loading layers…`});if(!e.length)return(0,Z.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=v3(e);return(0,Z.jsx)(`div`,{className:`px-2 py-1.5 space-y-2`,children:f.map(e=>(0,Z.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,Z.jsxs)(`div`,{className:`px-1 pt-1 pb-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:[e.label,(0,Z.jsxs)(`span`,{className:`ml-1 text-muted-foreground/60`,children:[`(`,e.items.length,`)`]})]}),e.items.map(e=>(0,Z.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,Z.jsx)(`div`,{className:K(`w-2 h-2 rounded-full shrink-0`,!e.color&&`bg-muted-foreground/20`),style:e.color?{backgroundColor:e.color}:void 0}),(0,Z.jsx)(_3,{type:e.type}),s===e.id?(0,Z.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,Z.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:e.label||e.name}),e.locked&&s!==e.id&&(0,Z.jsx)(Dt,{className:`w-2.5 h-2.5 shrink-0 text-warning group-hover:hidden`}),s!==e.id&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[e.locked?(0,Z.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,Z.jsx)(dn,{className:`w-3 h-3`})}):(0,Z.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,Z.jsx)(Dt,{className:`w-3 h-3`})}),!e.locked&&(0,Z.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,Z.jsx)(_r,{className:`w-3 h-3`})}),!e.locked&&(0,Z.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,Z.jsx)(lt,{className:`w-3 h-3`})})]})]},e.id))]},e.type))})}function b3(){let{state:e,closeM2:t}=zS(),n=Jm(),r=al(),i=nl(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null),[c,l]=(0,X.useState)({icon:null,color:null});(0,X.useEffect)(()=>{if(!a)return;let e=!1;return Zi(a).then(t=>{e||(s(t.label||null),l({icon:t.icon??null,color:t.color??null}))}).catch(()=>{}),()=>{e=!0}},[a]);let u=i.pathname.split(`/`).filter(Boolean),d=u[2]===`settings`?UT(u[3]):null,f=(0,X.useMemo)(()=>VT.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:`Settings: ${o||a||`Workspace`}`,icon:c.icon||`ph:stack-fill`,accentColor:c.color,onBack:()=>{n||!a?t():r(`/workspaces/${a}`)},action:(0,Z.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,Z.jsx)(gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(G4,{items:f,activeId:d,onSelect:e=>a&&r(`/workspaces/${a}/settings/${e}`)})]})}function x3(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),a=(0,X.useRef)(!1),o=(0,X.useRef)(!1),s=(0,X.useCallback)(async()=>{if(!o.current){o.current=!0,i(!0);try{let e=await lE();n(e||[]),a.current=!0}catch(e){console.error(`Failed to fetch agents:`,e)}finally{o.current=!1,i(!1)}}},[]),c=(0,X.useCallback)(()=>{a.current=!1,s()},[s]);return(0,X.useEffect)(()=>{e&&!a.current&&s()},[e,s]),(0,X.useEffect)(()=>{if(!e)return;let t=()=>id.emit(`subscribe`,{channel:`agent`}),r=()=>id.emit(`unsubscribe`,{channel:`agent`}),i=id.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])=>id.on(e,t)),()=>{r(),i?.(),u.forEach(([e,t])=>id.off(e,t))}},[e,s]),(0,X.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 S3({status:e}){return(0,Z.jsx)(`span`,{className:K(`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 C3(){let e=Zx(),{state:t,selectEntity:n,openM2:r,closeM2:i}=zS(),a=Jm(),{agents:o,isLoading:s,refresh:c}=x3(t.activeSection===`agents`),{showToast:l}=Vr(),[u,d]=(0,X.useState)(new Set),f=al(),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 CE(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 wE(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,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`}),!e.local&&(0,Z.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,Z.jsx)(U,{className:`w-3.5 h-3.5`})})]}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:s&&o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading...`}):o.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`No agents found`}):(0,Z.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,Z.jsxs)(`div`,{"data-active":i||void 0,className:K(`group relative rounded-md 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`}`,borderRadius:e.color?`6px 0 0 6px`:void 0},onClick:()=>p(e),children:[(0,Z.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,Z.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Z.jsx)(S3,{status:e.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium truncate`,children:e.label||e.name})]})}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 shrink-0`,children:[e.status===`active`?(0,Z.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,Z.jsx)(nn,{className:`w-3.5 h-3.5`})}):(0,Z.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,Z.jsx)(De,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(Qt,{className:`w-3.5 h-3.5`})})]})]}),e.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-3.5`,children:e.description})]},e.id)})})})]})}function w3(e){return e.name?.trim()?e.name.trim():e.firstMessage?.trim()?e.firstMessage.trim():e.isExperimental?`Experimental`:e.id.slice(0,8)}function T3(e){let t=new Date(e.updatedAt).toLocaleString();return e.messageCount>0?`${e.messageCount} msg${e.messageCount===1?``:`s`} • ${t}`:`Empty • ${t}`}function E3(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 D3(){let{state:e,closeM2:t}=zS(),n=e.selectedEntityId||``,r=al(),{showToast:i}=Vr(),[a,o]=(0,X.useState)(null),[s,c]=(0,X.useState)(!1),[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(null),[p,m]=(0,X.useState)(``),{current:h,sessions:g,isLoading:_,error:v,refresh:y,create:b,select:x,rename:S,remove:C}=NA(n);(0,X.useEffect)(()=>{n&&(uE(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,X.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]),E=a?.name||n,D=e=>e?.slug||e?.id,O=e=>{let t=typeof e==`string`?e:D(e);r(t?`/agents/${encodeURIComponent(E)}/${encodeURIComponent(t)}`:`/agents/${encodeURIComponent(E)}`)},k=async()=>{try{let e=await b({mode:`persistent`,name:l.trim()||void 0});c(!1),u(``),O(E3(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to create session`,variant:`destructive`})}},A=async()=>{try{let e=await b({mode:`experimental`});O(E3(e))}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open experimental session`,variant:`destructive`})}},j=async()=>{try{await b({mode:`incognito`}),O()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to open incognito session`,variant:`destructive`})}},M=async e=>{try{e.isExperimental?await x({mode:`experimental`}):await x({mode:`persistent`,sessionId:e.id}),O(e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to select session`,variant:`destructive`})}},P=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&&O(t||e)}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to rename session`,variant:`destructive`})}},ee=async e=>{if(!e.isExperimental&&window.confirm(`Delete session "${w3(e)}"?`))try{await C(e.id),O()}catch(e){i({title:`Error`,description:e instanceof Error?e.message:`Failed to delete session`,variant:`destructive`})}};return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:a?.label||a?.name||n,onBack:t,action:(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(`/agents/${encodeURIComponent(E)}/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,Z.jsx)(Qt,{className:`h-3.5 w-3.5`})})}),(0,Z.jsxs)(`div`,{className:`border-b border-border px-4 py-3`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-semibold`,children:`Sessions`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:g?.mode===`incognito`?`Incognito mode`:g?.mode===`experimental`?`Experimental mode`:`Persistent history`}),(0,Z.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Z.jsxs)(Y,{size:`sm`,variant:s?`default`:`outline`,onClick:()=>{c(e=>!e),u(``)},disabled:_,children:[(0,Z.jsx)(U,{className:`mr-1 h-3.5 w-3.5`}),`New`]}),(0,Z.jsxs)(Y,{size:`sm`,variant:g?.mode===`experimental`?`default`:`outline`,onClick:A,disabled:_,children:[(0,Z.jsx)(N,{className:`mr-1 h-3.5 w-3.5`}),`Experimental`]}),(0,Z.jsx)(Y,{size:`sm`,variant:g?.mode===`incognito`?`default`:`outline`,onClick:j,disabled:_,children:`Incognito`})]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-2`,children:[v&&(0,Z.jsx)(`div`,{className:`px-2 py-2 text-xs text-destructive`,children:v}),s&&(0,Z.jsxs)(`div`,{className:`mb-2 rounded-md border bg-muted/20 p-2`,children:[(0,Z.jsx)(`div`,{className:`mb-2 text-xs text-muted-foreground`,children:`Name the new session or leave it blank.`}),(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),k()),e.key===`Escape`&&(c(!1),u(``))},placeholder:`Debugging auth`,className:`h-8`}),(0,Z.jsx)(Y,{size:`sm`,onClick:k,disabled:_,children:`Create`})]})]}),g?.sessions.length?(0,Z.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,Z.jsx)(`div`,{onClick:()=>M(e),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),M(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,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(`div`,{className:`min-w-0 flex-1`,children:n?(0,Z.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Z.jsx)(q,{value:p,onChange:e=>m(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),P(e)),t.key===`Escape`&&(f(null),m(``))},placeholder:`Session name`,className:`h-8`}),(0,Z.jsx)(Y,{size:`sm`,onClick:t=>{t.stopPropagation(),P(e)},disabled:!p.trim()||_,children:`Save`})]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:`truncate text-sm font-medium`,children:w3(e)}),e.isExperimental&&(0,Z.jsx)(`span`,{className:`rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary`,children:`∞`}),e.isCurrent&&(0,Z.jsx)(`span`,{className:`rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground`,children:`Current`})]}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs text-muted-foreground`,children:T3(e)})]})}),!n&&(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5 reveal-on-hover`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),f(e.id),m(e.name||w3(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,Z.jsx)(T,{className:`h-3.5 w-3.5`})}),!e.isExperimental&&(0,Z.jsx)(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),ee(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,Z.jsx)(lt,{className:`h-3.5 w-3.5`})})]})]})},e.id)})}):(0,Z.jsx)(`div`,{className:`flex h-full items-center justify-center text-center text-muted-foreground`,children:(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`div`,{className:`text-sm`,children:_?`Loading sessions...`:`No persistent sessions yet.`}),(0,Z.jsx)(`div`,{className:`mt-1 text-xs`,children:"Use `New`, `Experimental`, or `Incognito`."})]})}),h?.mode===`incognito`&&(0,Z.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 O3(){let{state:e,closeM2:t}=zS(),n=Jm(),r=al(),i=nl(),a=e.selectedEntityId,[o,s]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!a)return;let e=!1;return uE(a).then(t=>{e||s(t)}).catch(()=>{}),()=>{e=!0}},[a]);let c=i.pathname.split(`/`).filter(Boolean),l=c[2]===`settings`?qT(c[3]):null,u=encodeURIComponent(o?.name||a||``),d=(0,X.useMemo)(()=>KT.map(({id:e,label:t,description:n,icon:r})=>({id:e,label:t,description:n,icon:(0,Z.jsx)(r,{className:`h-4 w-4`})})),[]);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(M4,{title:`Settings: ${o?.label||o?.name||a||`Agent`}`,accentColor:o?.color??null,onBack:()=>{n||!u?t():r(`/agents/${u}`)},action:(0,Z.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,Z.jsx)(gn,{className:`h-3.5 w-3.5`})})}),(0,Z.jsx)(G4,{items:d,activeId:l,onSelect:e=>u&&r(`/agents/${u}/settings/${e}`)})]})}function k3(){let e=nl(),{state:t}=zS(),[n,r]=(0,X.useState)(``),i=(0,X.useRef)(null);(0,X.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=hS.filter(e=>e.id!==`server`||t.user?.userType===`admin`).map(e=>({...e,items:e.items.filter(t=>_S(n,e.label,t.label,t.description))})).filter(e=>e.items.length);return(0,Z.jsxs)(`nav`,{"aria-label":`Settings`,className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`shrink-0 space-y-3 border-b border-border p-3`,children:[(0,Z.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Settings`}),(0,Z.jsx)(q,{type:`search`,"aria-label":`Search settings menu`,placeholder:`Find a setting…`,value:n,onChange:e=>r(e.target.value)})]}),(0,Z.jsxs)(`div`,{ref:i,className:`min-h-0 flex-1 space-y-4 overflow-y-auto p-2`,children:[a.map(t=>(0,Z.jsxs)(`section`,{"aria-label":t.label,children:[(0,Z.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,Z.jsxs)(Su,{to:t,"aria-current":e.pathname===t?`page`:void 0,className:K(`flex items-start gap-3 rounded-md px-3 py-2 text-left hover:bg-accent/50`,e.pathname===t&&`bg-accent`),children:[(0,Z.jsx)(n,{className:`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground`}),(0,Z.jsxs)(`span`,{children:[(0,Z.jsx)(`span`,{className:`block text-sm font-medium`,children:r}),(0,Z.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-muted-foreground`,children:i})]})]},t))]},t.id)),!a.length&&(0,Z.jsx)(`p`,{role:`status`,className:`p-3 text-sm text-muted-foreground`,children:`No settings match. Try “cache”, “model” or “token”.`})]})]})}var A3=280,j3=220,M3=560;function N3(){let{state:e}=zS(),{activeSection:t,m2View:n}=e;if(t===`contexts`){if(n===`settings`)return(0,Z.jsx)(K4,{});if(n===`detail`)return(0,Z.jsx)(W4,{})}if(t===`workspaces`){if(n===`settings`)return(0,Z.jsx)(b3,{});if(n===`detail`)return(0,Z.jsx)(d3,{})}if(t===`agents`){if(n===`settings`)return(0,Z.jsx)(O3,{});if(n===`detail`)return(0,Z.jsx)(D3,{})}return null}function P3(){let{state:e,closeM1:t,closeM2:n}=zS();Ff(t,e.m1Open&&!e.m2Open),Ff(n,e.m2Open);let r=Jm(),[i,a]=(0,X.useState)(A3),[o,s]=(0,X.useState)(!1),c=(0,X.useRef)(null),l=(0,X.useCallback)(e=>{e.preventDefault(),s(!0),c.current={startX:e.clientX,startWidth:i};let t=e=>{if(!c.current)return;let t=e.clientX-c.current.startX,n=Math.min(M3,Math.max(j3,c.current.startWidth+t));a(n)},n=()=>{c.current=null,s(!1),window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[i]),u=r&&e.m1Open;return(0,Z.jsxs)(Z.Fragment,{children:[u&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-40 bg-scrim animate-fade-in`,onClick:t,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:e.m1Open&&!u?{width:i}:void 0,className:K(`flex-shrink-0 overflow-hidden bg-card surface-glass`,!o&&!u&&`transition-[width] duration-200 ease-out`,e.m1Open?`rounded-[var(--panel-radius)] shadow-elevation-2`:`w-0`,u?`fixed bottom-2 left-[calc(0.5rem+var(--spacing-rail)+0.5rem)] right-2 top-2 z-40 shadow-elevation-5 animate-fade-in`:`relative`),children:[(0,Z.jsxs)(`div`,{className:K(`absolute inset-0 flex flex-col transition-opacity duration-200 ease-out`,e.m2Open&&`opacity-0 pointer-events-none`),style:u?void 0:{minWidth:i},children:[e.activeSection===`contexts`&&(0,Z.jsx)(j4,{}),e.activeSection===`workspaces`&&(0,Z.jsx)(Y4,{}),e.activeSection===`agents`&&(0,Z.jsx)(C3,{}),e.activeSection===`admin`&&(0,Z.jsx)(k3,{}),e.activeSection===`settings`&&(0,Z.jsx)(k3,{})]}),(0,Z.jsx)(`div`,{className:K(`absolute inset-0 z-10 bg-card flex flex-col transition-transform duration-200 ease-out`,e.m2Open?`translate-x-0`:`translate-x-full`),children:e.m2Open&&(0,Z.jsx)(N3,{})}),e.m1Open&&!u&&(0,Z.jsx)(`div`,{onMouseDown:l,className:`absolute right-0 top-0 bottom-0 z-20 w-1 cursor-col-resize hover:bg-primary/20 transition-colors`})]})]})}var F3=`canvas:readerWidth`,I3=320,L3=1600;function R3(){try{let e=Number(sessionStorage.getItem(F3));return Number.isFinite(e)&&e>=I3&&e<=L3?e:null}catch{return null}}var z3=R3(),B3=new Set;function V3(e){return B3.add(e),()=>{B3.delete(e)}}function H3(e){z3=e===null?null:Math.round(Math.max(I3,Math.min(L3,e)));try{z3===null?sessionStorage.removeItem(F3):sessionStorage.setItem(F3,String(z3))}catch{}B3.forEach(e=>e())}function U3(){return(0,X.useSyncExternalStore)(V3,()=>z3,()=>null)}var W3=320,G3=1600;function K3({edge:e}){let t=U3(),n=(0,X.useRef)(null),r=e===`left`?-1:1;return(0,Z.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":W3,"aria-valuemax":G3,"aria-valuenow":t??560,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)-240:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(W3,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&H3(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:()=>H3(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`?H3(null):H3(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function q3(e){return e.schema===`data/schema/note`?xn:e.schema===`data/schema/tab`?Xt:e.schema===`data/schema/file`?bt:e.schema===`data/schema/message/email`?Cn:fn}function J3({entry:e,onClose:t,frame:n}={}){let r=hm(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=M_(i?.workspaceId,i?.document??null);if(!i||!o)return null;let{workspaceId:c}=i;return(0,Z.jsx)(Ew,{title:Ui(o).title,icon:q3(o),onClose:a,onSave:async e=>(await li(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:ng(o)===oh,children:(0,Z.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,Z.jsx)(j_,{document:o,workspaceId:c,onChanged:s,compact:!0},`${c}:${o.id}`)})})}function Y3(e){let[t]=e.split(`/`).filter(Boolean);return!t||t===`home`||t===`share-target`}function X3(e){let[t,n]=e.split(`/`).filter(Boolean);return[`contexts`,`workspaces`,`agents`].includes(t)&&!!n}var Z3=`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:pr-0 max-md:rounded-2xl max-md:shadow-elevation-5 max-md:animate-fade-in`,Q3=`fixed inset-0 z-side-scrim bg-scrim animate-fade-in md:hidden`;function $3(){let e=U3(),{pathname:t}=nl(),n=X3(t),r=Y3(t),{entry:i,close:a}=hm();return(0,Z.jsx)(`div`,{className:K(`relative flex flex-col flex-1 min-w-0`,!r&&`surface-sheet`),children:(0,Z.jsxs)(`div`,{className:`flex flex-1 min-h-0 gap-shell`,children:[(0,Z.jsx)(`main`,{id:`content-area`,className:K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!n&&!r&&`p-page max-md:pb-rail-stack`),children:(0,Z.jsx)(Ml,{})}),i&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:Q3,onClick:a,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{"data-reader-pane":!0,style:{"--reader-width":`${e??560}px`,"--document-card-width":`100%`},className:K(`relative flex shrink-0 items-stretch py-2 pr-2 md:w-[var(--reader-width)] md:max-w-[calc(100%_-_240px)]`,Z3),children:[(0,Z.jsx)(K3,{edge:`left`}),(0,Z.jsx)(J3,{})]})]})]})})}function e6(){let{state:e,setView:t}=Os(),{pathname:n}=nl();return e.t1Open||e.addOpen||!Y3(n)?null:(0,Z.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,Z.jsx)(kt,{className:`h-7 w-7`,strokeWidth:1.75,"aria-hidden":!0})})}var t6={current:null,sessions:null,isLoading:!1,error:null};function n6(e){return e instanceof Error?e.message:`Session request failed`}function r6({children:e}){let[t,n]=(0,X.useState)({}),r=(0,X.useCallback)((e,t)=>{n(n=>({...n,[e]:{...n[e]||t6,...t}}))},[]),i=(0,X.useCallback)((e,t)=>(r(e,{current:t.current,sessions:t.sessions,isLoading:!1,error:null}),t),[r]),a=(0,X.useCallback)(async e=>{if(e){r(e,{isLoading:!0,error:null});try{let[t,n]=await Promise.all([dE(e),fE(e)]);r(e,{current:t,sessions:n,isLoading:!1,error:null})}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}}},[r]),o=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await pE(e,t))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),s=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await mE(e,t))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),c=(0,X.useCallback)(async(e,t,n)=>{r(e,{isLoading:!0,error:null});try{return i(e,await hE(e,t,{name:n}))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),l=(0,X.useCallback)(async(e,t)=>{r(e,{isLoading:!0,error:null});try{return i(e,await gE(e,t))}catch(t){throw r(e,{isLoading:!1,error:n6(t)}),t}},[i,r]),u=(0,X.useMemo)(()=>({getState:e=>t[e]||t6,refresh:a,create:o,select:s,rename:c,remove:l}),[t,a,o,s,c,l]);return(0,Z.jsx)(MA.Provider,{value:u,children:e})}var i6=`data/schema/`,a6={"data/schema/file":{label:`Files`,icon:wn},"data/schema/note":{label:`Notes`,icon:xn},"data/schema/task":{label:`Todos`,icon:On},"data/schema/tab":{label:`Tabs`,icon:ae},"data/schema/message/email":{label:`Emails`,icon:Cn},"data/schema/link":{label:`Links`,icon:Xt},"data/schema/identity":{label:`Identities`,icon:Ze},"data/schema/drawing":{label:`Sketches`,icon:rt}};function o6(e){return a6[e]??{label:e.startsWith(`data/schema/`)?e.slice(12).replace(/(^|\/)(\w)/g,(e,t,n)=>t+n.toUpperCase()):e,icon:h}}function s6(e){return a6[e]?.icon??h}function c6(e){return{...e,lens:L_.lens}}function l6(e,t,n=!1){let r=n?e=>e:c6;return JSON.stringify(r(e))!==JSON.stringify(r(t??L_))}var u6={savedGeoSelection:null,liveEnabled:!1,liveError:null,t1Open:!1,t1View:null,toolsTab:`features`,appsAppletId:null,t2Open:!1,t2AgentId:null,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:L_,geoSelection:null,mapDocuments:[],mapWorkspaceId:null,savedFilters:null,savedSearchQuery:null,isDirty:!1,isSaving:!1,availableBitmaps:[],bitmapsLoading:!1,availableTimelines:[],timelineScales:{},timelinesLoading:!1};function d6(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,addKind:t.kind,addRelateTo:t.relateTo===void 0?e.addRelateTo:t.relateTo,editDocument:null,editWorkspaceId:null};case`CLOSE_ADD`:return{...e,addOpen:!1,addKind:null,addRelateTo:null,editDocument:null,editWorkspaceId:null};case`OPEN_EDIT`:return{...e,addOpen:!0,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`?l6(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`?l6(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:L_,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:l6(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??L_;return{...e,savedFilters:t.savedFilters,savedSearchQuery:t.savedSearchQuery??null,filters:r,isDirty:n?l6(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 f6=`toolbox:session:filters`;function p6(){try{let e=localStorage.getItem(f6);if(!e)return null;let t=JSON.parse(e);return{...L_,...t,features:{...L_.features,...t.features??{}},timeline:{...L_.timeline,...t.timeline??{}},geo:{...L_.geo,...t.geo??{}},lens:L_.lens,sort:I_(t.sort)}}catch{return null}}function m6(e){try{localStorage.setItem(f6,JSON.stringify(c6(e)))}catch{}}function h6(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?{...L_.lens,...n.lens??{}}:L_.lens,sort:I_(n.sort)}}catch{return null}}function g6(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 _6({children:e}){let[t,n]=(0,X.useReducer)(d6,u6),r=nl(),i=al(),a=new URLSearchParams(r.search).get(`ownerId`)||void 0,o=(0,X.useRef)(null),s=(0,X.useRef)(t);(0,X.useEffect)(()=>{s.current=t}),(0,X.useEffect)(()=>{let e=!1,t=r.pathname.split(`/`).filter(Boolean),i=t[0]===`workspaces`&&t[1]||null,a=t[0]===`contexts`&&t[1]||null,{path:o,treeName:c}=i?nb(r.pathname):{path:`/`,treeName:``},l=t=>{if(e)return;let r=t?`canvas`:a?`context`:null,l=s.current;l.activeContextType!==null&&r===null&&m6(l.filters),n({type:`SET_NAVIGATION`,workspaceName:i,treeName:i?c:null,canvasId:t,contextId:a,contextType:r,contextPath:i?o:null})};return i&&o!==`/`?(Gi(i,c).then(t=>{if(e)return;let n=g6(t,o);l(n?.type===`canvas`?n.id:null)}).catch(()=>l(null)),()=>{e=!0}):(l(null),()=>{e=!0})},[r.pathname]),(0,X.useEffect)(()=>{let e=t.activeWorkspaceName;e&&(n({type:`SET_BITMAPS_LOADING`,loading:!0}),So(e).then(e=>{n({type:`SET_BITMAPS`,keys:e})}))},[t.activeWorkspaceName]),(0,X.useEffect)(()=>{let e=t.activeWorkspaceName;e&&(n({type:`SET_TIMELINES_LOADING`,loading:!0}),Ai(e).then(e=>{n({type:`SET_TIMELINES`,names:e.map(e=>e.name),scales:Object.fromEntries(e.filter(e=>e.scales?.length).map(e=>[e.name,e.scales]))})}))},[t.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeCanvasId:r,activeWorkspaceName:i,activeTreeName:a,activeContextPath:o}=t;if(e!==`context`){if(e===`canvas`&&r&&i&&o)Gi(i,a||`context`).then(e=>{let t=g6(e,o),r=h6(t?.metadata);n({type:`SET_SAVED_FILTERS`,savedFilters:r,savedSearchQuery:t?.querySpec?.query??null,hydrating:!0})}).catch(()=>{n({type:`SET_SAVED_FILTERS`,savedFilters:null,savedSearchQuery:null,hydrating:!0})});else{let e=p6();n({type:`SET_SAVED_FILTERS`,savedFilters:e,savedSearchQuery:null})}}},[t.activeCanvasId,t.activeContextPath,t.activeContextType,t.activeTreeName,t.activeWorkspaceName]),(0,X.useEffect)(()=>{let{activeContextType:e,activeContextId:c}=t;if(e!==`context`||!c)return;let l=!1;o.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();i(`${r.pathname}${n?`?${n}`:``}`,{replace:!0})},f=(e,t,r,i=null,a=r?[r]:[])=>{let s=e?.filters??t??L_,c=e?.geoSelection??i;o.current=JSON.stringify({filters:s,geoSelection:c,queries:e?.queries??a}),n({type:`SET_SAVED_FILTERS`,savedFilters:t,savedSearchQuery:r}),n({type:`SET_FILTERS`,filters:s}),n({type:`SET_GEO_SELECTION`,selection:c}),n({type:`SET_SAVED_GEO_SELECTION`,selection:i}),n({type:`SET_LIVE`,enabled:e!==null}),d(e?.queries??a)},p=e=>{let t=++u;return fs(c,a).then(r=>{if(l||t!==u)return;let i=r.metadata,a=h6(i,!0),c=typeof i?.toolboxSearchQuery==`string`?i.toolboxSearchQuery:null;if(n({type:`SET_CONTEXT_SCOPE`,workspaceName:r.workspaceName||r.workspaceId||null,contextPath:r.path||`/`,treeId:r.treeId||null}),r.liveQuery)f(r.liveQuery,a,c,i?.toolboxGeoSelection??null,r.queryOptions?.queries);else if(e){n({type:`SET_LIVE`,enabled:!1});let e=s.current.isDirty?s.current.filters:a??L_,t=i?.toolboxGeoSelection??null;o.current=JSON.stringify({filters:e,geoSelection:t,queries:[]}),n({type:`SET_SAVED_FILTERS`,savedFilters:a,savedSearchQuery:c,hydrating:!0}),n({type:`SET_GEO_SELECTION`,selection:t}),n({type:`SET_SAVED_GEO_SELECTION`,selection:t});let l=new URLSearchParams(window.location.search),u=r.queryOptions?.queries?.length?r.queryOptions.queries:c?[c]:[];!l.has(`q`)&&!l.has(`search`)&&u.length&&d(u)}}).catch(e=>{l||t!==u||n({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not load context`})})};p(!0);let m=()=>{p(!1)},h=id.on(`context.url.set`,e=>{e?.id===c&&m()}),g=id.on(`context.updated`,e=>{let t=e;if((t.contextId||t.id)!==c)return;if(!t.metadata){p(!0);return}++u;let n=h6(t.metadata,!0);f(t.liveQuery??null,n,typeof t.metadata.toolboxSearchQuery==`string`?t.metadata.toolboxSearchQuery:null,t.metadata.toolboxGeoSelection??null,t.queryOptions?.queries)}),_=id.on(`connect`,()=>{p(!0)}),v=id.on(`disconnect`,()=>{s.current.liveEnabled&&n({type:`SET_LIVE_ERROR`,error:`Disconnected — Live updates will resume when connected.`})});return window.addEventListener(`contexts:refresh`,m),()=>{l=!0,o.current=null,h(),g(),_(),v(),window.removeEventListener(`contexts:refresh`,m)}},[t.activeContextId,t.activeContextType,a]);let c=(0,X.useMemo)(()=>{let e=new URLSearchParams(r.search),t=e.getAll(`q`).map(e=>e.trim()).filter(Boolean),n=(e.get(`search`)||``).trim();return t.length?t:n?[n]:[]},[r.search]),l=(0,X.useRef)(c);(0,X.useEffect)(()=>{l.current=c},[c]);let u=(0,X.useRef)(!1),d=(0,X.useRef)(null),[f,p]=(0,X.useState)(0);(0,X.useEffect)(()=>()=>{d.current!==null&&window.clearTimeout(d.current),d.current=null},[t.activeContextType,t.activeContextId,t.liveEnabled,a]),(0,X.useEffect)(()=>{t.activeContextType!==`context`||!t.activeContextId||a||!t.liveEnabled||o.current===null||u.current||d.current!==null||!id.isConnected()||JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:c})!==o.current&&(d.current=window.setTimeout(()=>{d.current=null;let e=s.current;if(e.activeContextId!==t.activeContextId||!e.liveEnabled)return;let r=l.current,i=JSON.stringify({filters:e.filters,geoSelection:e.geoSelection,queries:r});if(i===o.current)return;let a=o.current;u.current=!0;let c={filters:e.filters,geoSelection:e.geoSelection,queries:r,binding:H_(e.filters,e.geoSelection,r)};id.request(`context.filters.set`,{contextId:e.activeContextId,liveQuery:c}).then(()=>{s.current.activeContextId===e.activeContextId&&o.current===a&&(o.current=i,n({type:`SET_LIVE_ERROR`,error:null}))}).catch(t=>{s.current.activeContextId===e.activeContextId&&n({type:`SET_LIVE_ERROR`,error:t instanceof Error?t.message:`Live update failed`})}).finally(()=>{u.current=!1,p(e=>e+1)})},t.liveError?1500:100))},[t.activeContextType,t.activeContextId,t.liveEnabled,t.filters,t.geoSelection,c,a,f,t.liveError]);let m=(0,X.useCallback)(async e=>{let t=s.current;if(t.activeContextType!==`context`||!t.activeContextId||a)return;let r=c,i=e?{filters:t.filters,geoSelection:t.geoSelection,queries:r,binding:H_(t.filters,t.geoSelection,r)}:null;try{await id.request(`context.filters.set`,{contextId:t.activeContextId,liveQuery:i}),o.current=JSON.stringify({filters:t.filters,geoSelection:t.geoSelection,queries:r}),n({type:`SET_LIVE`,enabled:e})}catch(e){n({type:`SET_LIVE_ERROR`,error:e instanceof Error?e.message:`Could not change Live mode`})}},[a,c]);(0,X.useEffect)(()=>{t.activeContextType===null&&m6(t.filters)},[t.filters,t.activeContextType]);let h=(0,X.useCallback)(e=>n({type:`SET_VIEW`,view:e}),[]),g=(0,X.useCallback)(e=>n({type:`TOGGLE_VIEW`,view:e}),[]),_=(0,X.useCallback)(()=>n({type:`CLOSE_T1`}),[]),v=(0,X.useCallback)(e=>n({type:`OPEN_T2_AGENT`,agentId:e}),[]),y=(0,X.useCallback)(()=>n({type:`CLOSE_T2`}),[]),b=(0,X.useCallback)(e=>n({type:`OPEN_ADD`,kind:e}),[]),x=(0,X.useCallback)(()=>n({type:`OPEN_ADD`,kind:null,relateTo:null}),[]),S=(0,X.useCallback)(e=>n({type:`OPEN_ADD`,kind:null,relateTo:e}),[]),C=(0,X.useCallback)(()=>n({type:`CLOSE_ADD`}),[]),w=(0,X.useCallback)((e,t)=>n({type:`OPEN_EDIT`,document:e,workspaceId:t}),[]),T=(0,X.useCallback)(e=>n({type:`SET_TOOLS_TAB`,tab:e}),[]),E=(0,X.useCallback)(e=>n({type:`SET_APPS_APPLET`,appletId:e}),[]),D=(0,X.useCallback)(e=>n({type:`SET_ACCENT_COLOR`,color:e}),[]),O=(0,X.useCallback)(e=>{n({type:`SET_FILTERS`,filters:e})},[]),k=(0,X.useCallback)((e,t)=>{let{filters:r}=s.current,i=e.startsWith(i6),a=i?r.features.allOf.filter(t=>t!==e):t?[...new Set([...r.features.allOf,e])]:r.features.allOf.filter(t=>t!==e),o=i&&t?[...new Set([...r.features.anyOf,e])]:r.features.anyOf.filter(t=>t!==e),c=r.features.noneOf.filter(t=>t!==e);n({type:`SET_FILTERS`,filters:{...r,features:{allOf:a,anyOf:o,noneOf:c}}})},[]),A=(0,X.useCallback)((e,t)=>{let{filters:r}=s.current,i=r.features.allOf.filter(t=>t!==e),a=r.features.anyOf.filter(t=>t!==e),o=r.features.noneOf.filter(t=>t!==e);t===`allOf`?i.push(e):t===`anyOf`?a.push(e):t===`noneOf`&&o.push(e),n({type:`SET_FILTERS`,filters:{...r,features:{allOf:i,anyOf:a,noneOf:o}}})},[]),j=(0,X.useCallback)(()=>{let{filters:e}=s.current;n({type:`SET_GEO_SELECTION`,selection:null}),n({type:`SET_FILTERS`,filters:{...L_,timeline:{...e.timeline,quickFilter:null,customRanges:[],customRange:null,selectedTimelines:[]}}})},[]),M=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,sort:e}})},[]),N=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,timeline:{...t.timeline,...e}}})},[]),P=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,geo:{...t.geo,bbox:e}}})},[]),ee=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,gps:e}}})},[]),F=(0,X.useCallback)(e=>{let{filters:t}=s.current;n({type:`SET_FILTERS`,filters:{...t,lens:{...t.lens,ids:e}}})},[]),I=(0,X.useCallback)(e=>{n({type:`SET_GEO_SELECTION`,selection:e})},[]),L=(0,X.useCallback)((e,t=null)=>{n({type:`SET_MAP_DOCUMENTS`,documents:e,workspaceId:t})},[]),R=(0,X.useCallback)(async()=>{let{activeContextType:e,activeContextId:t,activeWorkspaceName:i,activeTreeName:o,activeContextPath:l,filters:u,geoSelection:d,isSaving:f}=s.current;if(!f){n({type:`SET_SAVING`,isSaving:!0});try{if(e===`canvas`&&i&&l){let e=o||`context`,t=g6(await Gi(i,e),l),n=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;await ia(i,l,{metadata:{...t?.metadata||{},toolbox:c6(u)},querySpec:{features:u.features,filters:[...V_(u.timeline),...R_(u.geo)],query:n.trim()||void 0,sort:u.sort?.sortBy?u.sort:null}},e),Sa(i,e)}else if(e===`context`&&t){let e=(await fs(t,a)).metadata||{},n=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;await Go(t,{metadata:{...e,toolbox:u,toolboxGeoSelection:d,toolboxSearchQuery:n.trim()||void 0},...H_(u,d,c)},a)}let s=new URLSearchParams(r.search).get(`q`)||new URLSearchParams(r.search).get(`search`)||``;n({type:`SET_SAVED_FILTERS`,savedFilters:u,savedSearchQuery:s.trim()||null,hydrating:!0}),e===`context`&&n({type:`SET_SAVED_GEO_SELECTION`,selection:d})}finally{n({type:`SET_SAVING`,isSaving:!1})}}},[r.search,a,c]),te=(0,X.useCallback)(e=>{let t=s.current.availableBitmaps.filter(t=>t!==e);n({type:`SET_BITMAPS`,keys:t});let r=s.current.filters,i={...r,features:{allOf:r.features.allOf.filter(t=>t!==e),anyOf:r.features.anyOf.filter(t=>t!==e),noneOf:r.features.noneOf.filter(t=>t!==e)}};JSON.stringify(i.features)!==JSON.stringify(r.features)&&n({type:`SET_FILTERS`,filters:i})},[]),ne=(0,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await zi(t,e),te(e)},[te]),z=(0,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);let n=await $r(t,e);return te(e),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t}})),n.documentsDeleted},[te]),re=(0,X.useCallback)(()=>{let e=s.current.activeWorkspaceName;e&&(n({type:`SET_TIMELINES_LOADING`,loading:!0}),Ai(e).then(e=>{n({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,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await la(t,e),re()},[re]),ae=(0,X.useCallback)(async e=>{let t=s.current.activeWorkspaceName;if(!t)throw Error(`No active workspace`);await ai(t,e);let r=s.current.availableTimelines.filter(t=>t!==e);n({type:`SET_TIMELINES`,names:r});let i=s.current.filters,a=i.timeline.selectedTimelines.filter(t=>t!==e);a.length!==i.timeline.selectedTimelines.length&&n({type:`SET_FILTERS`,filters:{...i,timeline:{...i.timeline,selectedTimelines:a}}})},[]),{features:oe,timeline:se,geo:B,lens:ce}=t.filters,V=oe.allOf.length>0||oe.anyOf.length>0||oe.noneOf.length>0||se.quickFilter!==null||(se.customRanges?.length??0)>0||(se.selectedTimelines?.length??0)>0||B.bbox!==null||ce.gps!==null||ce.ids!==null||t.geoSelection!==null;return(0,Z.jsx)(ts.Provider,{value:{state:t,setView:h,toggleView:g,closeT1:_,openAgentT2:v,closeT2:y,openAdd:b,openAddPicker:x,openAddRelated:S,closeAdd:C,openEdit:w,setToolsTab:T,openApplet:E,setAccentColor:D,setFilters:O,setFeatureToggle:k,setFeatureMode:A,clearFilters:j,hasActiveFilters:V,setTimelineFilter:N,setGeoBBox:P,setLensGps:ee,setLensIds:F,setGeoSelection:I,setMapDocuments:L,setSort:M,setLiveEnabled:m,saveFilters:R,deleteBitmap:ne,deleteDataset:z,createTimeline:ie,deleteTimeline:ae,refreshTimelines:re},children:e})}var v6=`references`;function y6(e){return e?e.documents.map(e=>({predicate:v6,direction:`out`,targetId:e.id,document:e})):[]}function b6(e,t){let[n,r]=(0,X.useState)(()=>y6(t)),[i,a]=(0,X.useState)([...$a]),o=e?.mode===`context`?e.contextId:null,[s,c]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(!o)return;let e=!1;return xs({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,X.useEffect)(()=>{let e=!1;if(l)return $i(l).then(t=>{e||a(t)}),()=>{e=!0}},[l]),{rows:n,predicates:i,workspaceName:l,add:(0,X.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?qr(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,X.useCallback)((e,t)=>{r(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),remove:(0,X.useCallback)(e=>{r(t=>t.filter((t,n)=>n!==e))},[]),write:(0,X.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 Ca(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&&Dm(),r},[n,l]),hasRows:n.length>0}}function x6({f:e,idPrefix:t}){let[n,r]=(0,X.useState)(!1),[i,a]=(0,X.useState)(!1),o=!e.workspaceName;return(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsx)(Pu,{children:`Related documents`}),(0,Z.jsxs)(Y,{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,Z.jsx)(U,{className:`mr-1 h-3 w-3`}),` Add`]})]}),e.rows.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None. Relations are written right after the document is created.`}):(0,Z.jsx)(`ul`,{className:`space-y-1`,children:e.rows.map((n,r)=>{let i=n.document?Ui(n.document).title:`Document ${n.targetId}`,a=`${t}-relation-${r}`;return(0,Z.jsxs)(`li`,{className:`flex items-center gap-1.5 rounded-md border border-input px-2 py-1.5 text-sm`,children:[(0,Z.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,Z.jsx)(qn,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Bt,{className:`h-3.5 w-3.5`})}),(0,Z.jsx)(`label`,{htmlFor:a,className:`sr-only`,children:`Predicate`}),(0,Z.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,Z.jsx)(`option`,{value:e,children:e},e))}),n.document?(0,Z.jsx)(Dp,{document:n.document,size:3.5}):null,(0,Z.jsx)(`span`,{className:K(`min-w-0 flex-1 truncate`,!n.document&&`italic text-muted-foreground`),title:i,children:i}),(0,Z.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,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]},`${n.direction}:${n.predicate}:${n.targetId}`)})}),n&&e.workspaceName&&(0,Z.jsx)(Hp,{onClose:()=>{i||r(!1)},children:(0,Z.jsx)(Bp,{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 S6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=Sw(),o=b6(n,t.addRelateTo),s=Ww(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`note-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Body`}),(0,Z.jsx)(Io,{kind:`markdown`,value:a.content,onChange:a.setContent,placeholder:`Write your note…`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`note-comment`,children:`Comment`}),(0,Z.jsx)(`textarea`,{id:`note-comment`,value:a.comment,onChange:e=>a.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,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsx)(ww,{geotag:a.geotag,idPrefix:`note-geotag`}),(0,Z.jsx)(x6,{f:o,idPrefix:`note`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{if(n)try{let t=await a.save(n),i=await o.write(t);r(i?`Note created; some relations failed`:`Note created`),e()}catch(e){i(e instanceof Error?e.message:`Failed to create note`)}},disabled:!c,children:a.saving?`Saving…`:`Save note`})]})]})}function C6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=jw(),o=b6(n,t.addRelateTo),s=Ww(t.activeWorkspaceName),c=!!n&&a.canSave;return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`link-url`,children:`URL`}),(0,Z.jsx)(q,{id:`link-url`,value:a.url,onChange:e=>a.setUrl(e.target.value),placeholder:`https://example.com`,autoFocus:!0}),a.showUrlError&&(0,Z.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`link-title`,children:`Title`}),(0,Z.jsx)(q,{id:`link-title`,value:a.title,onChange:e=>a.setTitle(e.target.value),placeholder:`Optional display title`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsx)(ww,{geotag:a.geotag,idPrefix:`link-geotag`}),(0,Z.jsx)(x6,{f:o,idPrefix:`link`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{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 w6(e){let[t,n]=(0,X.useState)({key:``,list:[]});return(0,X.useEffect)(()=>{if(!e)return;let t=!1;return Ta(e,`github`).then(async r=>{let i=r.filter(e=>e.capabilities?.write),a=[];for(let t of i){let n=await Xa(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 T6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=Nh(),o=b6(n,t.addRelateTo),s=Ww(t.activeWorkspaceName),c=w6(t.activeWorkspaceName),[l,u]=(0,X.useState)(`canvas`),[d,f]=(0,X.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 Ea(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(Ig,{...a}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`todo-comment`,children:`Comment`}),(0,Z.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,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`todo-destination`,children:`Save to`}),(0,Z.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,Z.jsxs)(`option`,{value:`canvas`,children:[`Canvas: `,bs(n)]}),c.map(e=>(0,Z.jsx)(`option`,{value:`${e.driver}:${e.address}:${e.container}`,children:e.label},`${e.driver}:${e.address}:${e.container}`))]}),p&&(0,Z.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,Z.jsx)(ww,{geotag:a.geotag,idPrefix:`todo-geotag`}),!p&&(0,Z.jsx)(x6,{f:o,idPrefix:`todo`}),!p&&(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving||d,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:h,disabled:!m,children:a.saving||d?`Saving…`:p?`Create issue`:`Save todo`})]})]})}function E6(){let{closeAdd:e,state:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),a=Gg(),o=b6(n,t.addRelateTo),s=Ww(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsx)(Xg,{idPrefix:`add-identity`,workspaceName:t.activeWorkspaceName??void 0,...a,emailValid:a.emailValid}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:a.tags,onChange:a.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`identity-comment`,children:`Comment`}),(0,Z.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,Z.jsx)(x6,{f:o,idPrefix:`identity`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:bs(n)}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:a.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:c,disabled:!n||!a.canSave,children:a.saving?`Saving…`:`Save identity`})]})]})}function D6({capture:e=!1}={}){let{closeAdd:t,state:n}=Os(),r=gs(),i=r?.mode===`workspace`&&r.treeName===`backends`,a=b6(r,n.addRelateTo),{showSuccessToast:o,showErrorToast:s}=Wr(),c=(0,X.useRef)(null),[l,u]=(0,X.useState)(!1),d=Lw(),{items:f,running:p}=d,[m,h]=(0,X.useState)(null);(0,X.useEffect)(()=>{if(r?.mode!==`context`)return;let e=!1;return xs(r).then(t=>{e||h({contextId:r.contextId,workspaceName:t.workspaceName})}).catch(()=>{}),()=>{e=!0}},[r]);let g=qw(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:v,onClick:()=>c.current?.click(),className:K(`flex cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed px-4 py-8 text-center transition-colors`,l?`border-primary bg-primary/5`:`border-input hover:bg-muted/40`),children:[(0,Z.jsx)(te,{className:`h-6 w-6 text-muted-foreground touch-target`}),(0,Z.jsx)(`p`,{className:`text-sm`,children:e?`Take a photo or video`:`Drag & drop files here`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e?`click to open the camera`:`or click to browse`}),(0,Z.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,Z.jsx)(Hw,{items:f,running:p,onRemove:d.removeItem}),!i&&(0,Z.jsx)(Xw,{fields:g,idPrefix:`file`,multiple:f.length>1}),(0,Z.jsx)(x6,{f:a,idPrefix:`file`}),(0,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[bs(r),i?`. Existing files are never overwritten.`:``]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:()=>p?d.cancel():t(),children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{if(!(!S||!r))try{let e=i?null:await g.geotag.capture(),n=await d.start(r,(t,n)=>Jw(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,Z.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,Z.jsx)(He,{className:`h-3.5 w-3.5`}),`Retry failed (`,y,`)`]}):`Add files`})]})]})}function O6(){let{closeAdd:e}=Os(),t=gs(),{showSuccessToast:n,showErrorToast:r}=Wr(),[i,a]=(0,X.useState)(``),[o,s]=(0,X.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 xs(t),o=i===`/`?``:i;if(a===`backends`){let e=await vs(r,i);await oa(r,e.driver,e.address,[[e.key,c].filter(Boolean).join(`/`)]),os(t)}else await _a(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`add-folder-name`,children:`Folder name`}),(0,Z.jsx)(q,{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,Z.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Nested paths are created as needed. Target: `,bs(t)]})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:e,disabled:o,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:u,disabled:!l,children:o?`Creating…`:`Create folder`})]})]})}function k6(){let{openAddPicker:e,closeAdd:t}=Os(),n=gs(),{showSuccessToast:r,showErrorToast:i}=Wr(),[a,o]=(0,X.useState)(!1);return(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:e,"aria-hidden":!0}),(0,Z.jsx)(`div`,{className:`fixed inset-y-0 right-0 z-picker flex items-stretch py-2 pr-2 max-md:bottom-2 max-md:left-2 max-md:top-2 max-md:py-0 max-md:pr-0 max-md:animate-fade-in`,children:(0,Z.jsx)(fm,{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 ps(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 A6(e,t){let[n,r]=(0,X.useState)(String(e.data?.title??``)),[i,a]=(0,X.useState)(String(e.data?.content??``)),[o,s]=(0,X.useState)(qp(e.metadata?.features)),[c,l]=(0,X.useState)(!1),u=i.trim().length>0&&!c;async function d(){l(!0);try{await Da(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...n.trim()?{title:n.trim()}:{},content:i},metadata:{features:Kp(o)}}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}finally{l(!1)}}return{title:n,setTitle:r,content:i,setContent:a,tags:o,setTags:s,saving:c,canSave:u,save:d}}function j6(){let{state:e,closeAdd:t}=Os(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,Z.jsx)(M6,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function M6({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=A6(e,t),s=Ww(t);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-note-title`,children:`Title`}),(0,Z.jsx)(q,{id:`edit-note-title`,value:o.title,onChange:e=>o.setTitle(e.target.value),placeholder:`Optional; defaults to today's date`})]}),(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col gap-1.5`,children:[(0,Z.jsx)(Pu,{children:`Body`}),(0,Z.jsx)(`div`,{className:`flex-1`,children:(0,Z.jsx)(Io,{kind:`markdown`,value:o.content,onChange:o.setContent,placeholder:`Write your note…`})})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Z.jsx)(Y,{size:`sm`,onClick:async()=>{try{await o.save(),i(`Note updated`),r()}catch(e){a(e instanceof Error?e.message:`Failed to update note`)}},disabled:!o.canSave,children:o.saving?`Saving…`:`Save note`})]})]})}function N6(e,t){let n=qp(e.metadata?.features),[r,i]=(0,X.useState)(String(e.data?.label??``)),[a,o]=(0,X.useState)(n.length?n:e.data?.tags??[]),[s,c]=(0,X.useState)(!1),l=!s;async function u(){c(!0);try{let n=a.map(e=>e.trim()).filter(Boolean);await Da(t,{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,data:{...e.data,...r.trim()?{label:r.trim()}:{},tags:n},metadata:{features:Kp(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 P6(){let{state:e,closeAdd:t}=Os(),{editDocument:n,editWorkspaceId:r}=e,{showSuccessToast:i,showErrorToast:a}=Wr();return!n||!r?null:(0,Z.jsx)(F6,{doc:n,workspaceId:r,onCancel:t,onSaved:t,showSuccessToast:i,showErrorToast:a})}function F6({doc:e,workspaceId:t,onCancel:n,onSaved:r,showSuccessToast:i,showErrorToast:a}){let o=N6(e,t),s=Ww(t);return(0,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-4`,children:[(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsxs)(Pu,{children:[`URL `,(0,Z.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`(frozen)`})]}),(0,Z.jsx)(q,{value:o.url,disabled:!0,className:`font-mono text-xs`})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{htmlFor:`edit-link-label`,children:`Label`}),(0,Z.jsx)(q,{id:`edit-link-label`,value:o.label,onChange:e=>o.setLabel(e.target.value),placeholder:`Optional display name`,autoFocus:!0})]}),(0,Z.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Z.jsx)(Pu,{children:`Tags`}),(0,Z.jsx)(Gp,{tags:o.tags,onChange:o.setTags,suggestions:s})]}),(0,Z.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Z.jsx)(Y,{variant:`outline`,size:`sm`,onClick:n,disabled:o.saving,children:`Cancel`}),(0,Z.jsx)(Y,{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 I6=380,L6=300,R6=560,z6={message:{label:`New Message`,icon:It},note:{label:`New Note`,icon:xn},link:{label:`New Link`,icon:Xt},todo:{label:`New Todo`,icon:On},identity:{label:`New Identity`,icon:Ze},sketch:{label:`New Sketch`,icon:rt},file:{label:`Add Files`,icon:te},photo:{label:`Photo/Video`,icon:z},existing:{label:`Add Existing`,icon:Ot},folder:{label:`New Folder`,icon:ut}};function B6(){let{state:e,openAdd:t,closeAdd:n}=Os();Ff(n,e.addOpen);let{addOpen:r,addKind:i,editDocument:a}=e,o=gs(),s=Cs(o),c=s.isBackend&&!!i&&![`file`,`photo`,`folder`,`message`].includes(i),l=e.activeWorkspaceName,u=!l||!!e.addRelateTo,d=c||i===`message`&&u,f=s.isBackend?[`note`,`link`,`todo`,`identity`,`sketch`,`existing`]:[];u&&f.push(`message`);let p=o?.mode===`workspace`?`${o.workspaceName}:${o.treeName}:${o.path}`:o?.contextId,m=al();(0,X.useEffect)(()=>{!r||i!==`sketch`||s.isBackend||(n(),m(gw.createUrl(o)))},[r,i,o,n,m,s.isBackend]);let h=Ym(),[g,_]=(0,X.useState)(I6),v=(0,X.useRef)(null),y=(0,X.useCallback)(e=>{e.preventDefault(),v.current={startX:e.clientX,startWidth:g};let t=e=>{if(!v.current)return;let t=v.current.startX-e.clientX,n=Math.min(R6,Math.max(L6,v.current.startWidth+t));_(n)},n=()=>{v.current=null,window.removeEventListener(`mousemove`,t),window.removeEventListener(`mouseup`,n)};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[g]);if(!r)return null;let b=!!a,x=!b&&(!i||d),S,C;return b?(S=a.schema===`data/schema/note`?`Edit Note`:`Edit Link`,C=a.schema===`data/schema/note`?xn:Xt):i&&!d?(S=z6[i].label,C=z6[i].icon):(S=`Add`,C=U),(0,Z.jsxs)(Z.Fragment,{children:[h&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:h?void 0:{width:g},className:K(`flex flex-col overflow-hidden rounded-[var(--panel-radius)] border bg-card surface-glass`,h?`fixed bottom-2 left-2 right-2 top-2 z-panel shadow-elevation-5 animate-fade-in`:`relative shrink-0 shadow-elevation-3`),children:[!h&&(0,Z.jsx)(`div`,{onMouseDown:y,className:`absolute left-0 top-0 bottom-0 z-10 w-1 cursor-col-resize transition-colors hover:bg-primary/20`}),(0,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[b?(0,Z.jsx)(Fe,{className:`h-4 w-4`}):(0,Z.jsx)(C,{className:`h-4 w-4`}),S]}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`text-muted-foreground transition-colors hover:text-foreground`,"aria-label":`Close`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto`,children:[b&&a.schema===`data/schema/note`&&(0,Z.jsx)(j6,{}),b&&a.schema===`data/schema/link`&&(0,Z.jsx)(P6,{}),!b&&x&&e.addRelateTo&&(0,Z.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`,`.`]}),!b&&s.isBackend&&i!==`message`&&(0,Z.jsx)(`p`,{className:`border-b px-4 py-3 text-xs text-muted-foreground`,children:s.loading?`Checking storage destination…`:s.error||`Files are saved directly to this backend folder. Notes and other database documents belong in context or directory trees.`}),!b&&x&&(!s.isBackend||s.destination)&&(0,Z.jsx)(yw,{onSelect:t,omit:f}),!b&&i===`message`&&!u&&l&&(0,Z.jsx)(gg,{workspaceId:l,onClose:n},l),!b&&!s.isBackend&&i===`note`&&(0,Z.jsx)(S6,{}),!b&&!s.isBackend&&i===`link`&&(0,Z.jsx)(C6,{}),!b&&!s.isBackend&&i===`todo`&&(0,Z.jsx)(T6,{}),!b&&!s.isBackend&&i===`identity`&&(0,Z.jsx)(E6,{}),!b&&(!s.isBackend||s.destination)&&i===`file`&&(0,Z.jsx)(D6,{},p),!b&&(!s.isBackend||s.destination)&&i===`photo`&&(0,Z.jsx)(D6,{capture:!0},p),!b&&!s.isBackend&&i===`existing`&&(0,Z.jsx)(k6,{}),!b&&(!s.isBackend||s.destination)&&i===`folder`&&(0,Z.jsx)(O6,{},p)]})]})]})}var V6=(0,X.createContext)(null);function H6(){return(0,X.useContext)(V6)}function U6(){let e=H6(),t=e?.notifications??[];return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 bg-foreground shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-medium text-background`,children:`Home`})}),(0,Z.jsx)(`div`,{className:`px-4 py-4 border-b border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,Z.jsx)(cn,{className:`w-4 h-4`}),(0,Z.jsx)(`span`,{className:`text-xs font-mono`,children:new Date().toLocaleTimeString()})]})}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)($t,{className:`w-3.5 h-3.5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:`Notifications`})]}),t.length>0&&(0,Z.jsx)(Y,{size:`sm`,variant:`ghost`,className:`h-6 px-1.5 text-xs text-muted-foreground`,onClick:()=>void e?.clear(),title:`Clear notifications`,children:(0,Z.jsx)(lt,{className:`w-3 h-3`})})]}),t.length===0?(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground text-center py-10 border border-dashed rounded-lg`,children:`No notifications`}):(0,Z.jsx)(`div`,{className:`space-y-2`,children:[...t].reverse().map(e=>(0,Z.jsxs)(`div`,{className:`rounded-lg border p-2.5`,children:[(0,Z.jsx)(`p`,{className:`text-xs whitespace-pre-wrap break-words`,children:e.text}),(0,Z.jsx)(`p`,{className:`mt-1 text-[10px] text-muted-foreground`,children:new Date(e.timestamp).toLocaleString()})]},e.id))})]})]})}function W6(){let{state:e,setFilters:t}=Os();return(0,Z.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,Z.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 G6=l();Do();var K6=`#8b5cf6`,q6=`#94a3b8`,J6={color:K6,weight:2,fillColor:K6,fillOpacity:.12},Y6={color:K6,weight:2,dashArray:`5,5`,fillColor:K6,fillOpacity:.06},X6=e=>Math.round(e*1e6)/1e6;function Z6(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:${K6};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 Xp.default.divIcon({html:n,className:`canvas-map-cluster`,iconSize:[t,t],iconAnchor:[t/2,t/2]})}var Q6=e=>e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e]),$6=new Map;function e8(e){let t=$6.get(e);return t??(t=(0,G6.renderToStaticMarkup)((0,X.createElement)(s6(e),{width:13,height:13,strokeWidth:2.5})),$6.set(e,t)),t}var t8=new Map;function n8(e,t){let n=`${e}|${+!!t}`,r=t8.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?K6:q6};color:#fff;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.4);cursor:pointer">${e8(e)}</div>`;r=Xp.default.divIcon({html:i,className:`canvas-map-pin`,iconSize:[26,26],iconAnchor:[13,13]}),t8.set(n,r)}return r}function r8(){let{state:e,setGeoSelection:t,setGeoBBox:n}=Os(),{mapDocuments:r,geoSelection:i,mapWorkspaceId:a}=e,o=e.filters.geo.bbox,{open:s}=i_(),c=(0,X.useRef)(null),l=(0,X.useRef)(null),u=(0,X.useRef)(null),d=(0,X.useRef)(null),f=(0,X.useRef)(null),p=(0,X.useRef)([]),m=(0,X.useRef)(!1),[h,g]=(0,X.useState)(`idle`),[_,v]=(0,X.useState)(0),y=(0,X.useRef)(h),b=(0,X.useMemo)(()=>r.reduce((e,t)=>e+ +!!T_(t),0),[r]),x=(0,X.useMemo)(()=>i?r.reduce((e,t)=>{let n=T_(t);return e+(n&&D_(n.lat,n.lon,i)?1:0)},0):0,[r,i]),S=(0,X.useCallback)(()=>{let e=f.current;if(!e)return;e.clearLayers();let t=p.current;t.length!==0&&(t.length>=2&&Xp.default.polyline(t,Y6).addTo(e),t.forEach(t=>Xp.default.circleMarker(t,{radius:4,color:K6,weight:2,fillColor:`#fff`,fillOpacity:1}).addTo(e)))},[]),C=(0,X.useCallback)(()=>{p.current=[],v(0),f.current?.clearLayers()},[]),w=(0,X.useCallback)(()=>{let e=p.current;e.length>=3&&t({kind:`polygon`,points:e.map(e=>({lat:X6(e.lat),lon:X6(e.lng)}))}),C(),g(`idle`)},[t,C]),T=(0,X.useCallback)(()=>{C(),g(`idle`),t(null),n(null)},[C,t,n]);(0,X.useEffect)(()=>{let e=c.current;if(!e||l.current)return;let t=Xp.default.map(e,{center:[20,0],zoom:2,worldCopyJump:!0});Xp.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© OpenStreetMap contributors`,maxZoom:19}).addTo(t),u.current=Xp.default.markerClusterGroup({showCoverageOnHover:!1,maxClusterRadius:44,spiderfyOnMaxZoom:!0,chunkedLoading:!0,iconCreateFunction:e=>Z6(e.getChildCount())}).addTo(t),f.current=Xp.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=Xp.default.latLngBounds(i,t.mouseEventToLatLng(e));a?a.setBounds(n):a=Xp.default.rectangle(n,Y6).addTo(t)},h=e=>{if(y.current!==`rect`||!i)return;let a=Xp.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:X6(s.lat),minLon:X6(s.lng),maxLat:X6(c.lat),maxLon:X6(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,X.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,X.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,X.useEffect)(()=>{let e=l.current,t=u.current;if(!e||!t)return;t.clearLayers();let n=[],o=[];for(let e of r){let t=T_(e);if(!t)continue;n.push([t.lat,t.lon]);let r=!i||D_(t.lat,t.lon,i),c=Xp.default.marker([t.lat,t.lon],{icon:n8(e.schema,r),opacity:i&&!r?.55:1,zIndexOffset:r?1e3:0});c.bindTooltip(Q6(Ui(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(Xp.default.latLngBounds(n),{padding:[30,30],maxZoom:14,animate:!1}))},[r,i,s,a]),(0,X.useEffect)(()=>{let e=l.current;if(!e||(d.current&&=(d.current.remove(),null),!o&&!i))return;let t=Xp.default.layerGroup();o&&Xp.default.rectangle(Xp.default.latLngBounds([o.minLat,o.minLon],[o.maxLat,o.maxLon]),J6).addTo(t),i?.kind===`polygon`&&Xp.default.polygon(i.points.map(e=>[e.lat,e.lon]),J6).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,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 border-b border-border px-3 py-2 shrink-0`,children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`rect`?`idle`:`rect`),className:K(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,Z.jsx)(nn,{className:`h-3.5 w-3.5`}),`Box`]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>g(h===`polygon`?`idle`:`polygon`),className:K(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,Z.jsx)(I,{className:`h-3.5 w-3.5`}),`Polygon`]}),h===`polygon`&&(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`button`,{type:`button`,onClick:w,disabled:_<3,className:K(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,Z.jsx)($e,{className:`h-3.5 w-3.5`}),`Finish`]}),_>0&&(0,Z.jsx)(`button`,{type:`button`,onClick:C,className:K(D,`border-border text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Discard the points placed so far`,children:(0,Z.jsx)(Me,{className:`h-3.5 w-3.5`})})]}),(0,Z.jsxs)(`button`,{type:`button`,onClick:T,disabled:!o&&!i&&h===`idle`,className:K(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,Z.jsx)(lt,{className:`h-3.5 w-3.5`}),`Clear`]}),(0,Z.jsx)(`span`,{className:`ml-auto text-[11px] text-muted-foreground`,children:E})]}),(0,Z.jsxs)(`div`,{className:`relative isolate flex-1 min-h-0`,children:[(0,Z.jsx)(`div`,{ref:c,className:`absolute inset-0`}),b===0&&(0,Z.jsx)(`div`,{className:`pointer-events-none absolute inset-0 z-[2] flex items-center justify-center`,children:(0,Z.jsxs)(`div`,{className:`rounded-lg border bg-card/95 px-4 py-3 text-center shadow-elevation-2`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No located documents`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None of the current results carry location metadata.`})]})})]}),(0,Z.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,Z.jsx)(yt,{className:`h-3 w-3`}),b,` of `,r.length,` located`,i&&(0,Z.jsxs)(`span`,{className:`text-foreground font-medium`,children:[`· `,x,` in area`]})]})]})}var i8=[{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}],a8=`h-7 rounded-md border border-input bg-transparent px-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,o8=`h-7 rounded-md border border-input bg-transparent px-2 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring`,s8=e=>Math.round(e*1e4)/1e4;function c8(){let{state:e,setLensGps:t,setLensIds:n}=Os(),r=e.filters.lens,i=e.activeWorkspaceName,a=r.gps?.radiusM??100,[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(r.gps?.radiusM??100),[u,d]=(0,X.useState)(null),[f,p]=(0,X.useState)(0),[m,h]=(0,X.useState)(`prompt`),g=(0,X.useRef)(null),_=(0,X.useRef)(c);(0,X.useEffect)(()=>{_.current=c},[c]);let v=`geolocation`in navigator&&window.isSecureContext;(0,X.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,X.useEffect)(()=>{if(!o||!v)return;let e=navigator.geolocation.watchPosition(e=>{let n=s8(e.coords.latitude),r=s8(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=ix(),{rateMs:C,setRateMs:w,maxDistance:T,setMaxDistance:E,error:D}=S,O=S.running&&S.consumer===`filter`,k=S.running&&S.consumer!==`filter`;ax(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,Z.jsxs)(`div`,{className:`flex flex-col gap-4 p-3 text-sm`,children:[e.activeContextType===`context`&&(0,Z.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,Z.jsx)(W6,{}),(0,Z.jsxs)(`section`,{className:`space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Z.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`input`,{type:`checkbox`,checked:o,disabled:!v,onChange:e=>y(e.target.checked)}),(0,Z.jsx)(Jn,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{children:`Track this device’s GPS`})]}),(0,Z.jsx)(`select`,{className:a8,value:c,onChange:e=>x(Number(e.target.value)),disabled:!o,children:i8.map(e=>(0,Z.jsx)(`option`,{value:e.m,children:e.label},e.m))})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v?m===`denied`?(0,Z.jsx)(`span`,{className:`text-destructive`,children:`Location is blocked for this site. Allow it in your browser/app settings, then retry.`}):u?(0,Z.jsxs)(`span`,{className:`text-destructive`,children:[u,` `,(0,Z.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,Z.jsxs)(`section`,{className:`space-y-2 border-t border-border pt-3`,children:[(0,Z.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[j?(0,Z.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,Z.jsx)(Se,{className:`h-3.5 w-3.5`}),` `,S.source===`photo`?`Close photo`:`Stop ${S.source===`camera`?`camera`:`recording`}`]}):(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.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,Z.jsx)(z,{className:`h-3.5 w-3.5`}),` Camera`]}),(0,Z.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,Z.jsx)(fe,{className:`h-3.5 w-3.5`}),` Desktop`]})]}),(0,Z.jsx)(Ex,{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,Z.jsx)(`select`,{className:a8,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:px.map(e=>(0,Z.jsx)(`option`,{value:e.ms,children:e.label},e.ms))}),(0,Z.jsx)(`input`,{className:K(o8,`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,Z.jsxs)(`div`,{className:K(`relative overflow-hidden rounded-lg border border-border bg-black/80`,j?N?`aspect-[3/4] max-h-[60vh]`:`aspect-video`:`hidden`),children:[(0,Z.jsx)(vx,{className:`h-full w-full`,interactive:!0}),(0,Z.jsx)(wx,{})]}),j&&(0,Z.jsx)(Cx,{}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:D?(0,Z.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,Z.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 l8={"crud:created":`var(--data-5)`,"crud:updated":`var(--data-8)`,"crud:deleted":`var(--data-3)`,content:`var(--data-10)`,tasks:`var(--data-1)`};function u8(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 d8(e){return l8[e]??`oklch(var(--data-l) var(--data-c) ${u8(e)})`}var f8=[{label:`Day`,cells:[`yesterday`,`today`,`tomorrow`]},{label:`Week`,cells:[`lastWeek`,`thisWeek`,`nextWeek`]},{label:`Month`,cells:[`lastMonth`,`thisMonth`,`nextMonth`]},{label:`Year`,cells:[`lastYear`,`thisYear`,`nextYear`]}],p8=[{label:`Decade`,cells:[`lastDecade`,`thisDecade`,`nextDecade`]},{label:`Century`,cells:[`lastCentury`,`thisCentury`,`nextCentury`]},{label:`Millennium`,cells:[`lastMillennium`,`thisMillennium`,`nextMillennium`]}],m8=[`Yesterday`,`Today`,`Tomorrow`],h8=[{label:`Millennium`,unit:`millennium`},{label:`Century`,unit:`century`},{label:`Decade`,unit:`decade`},{label:`Year`,unit:`year`},{label:`Month`,unit:`month`},{label:`Week`,unit:`week`}],g8=10,_8=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function v8(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 y8(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 b8(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`${_8[t.getMonth()]} ${t.getFullYear()}`;case`week`:{let e=new Date(t);return e.setDate(e.getDate()+6),`${t.getDate()} ${_8[t.getMonth()]} – ${e.getDate()} ${_8[e.getMonth()]}`}}}function x8(e,t){return Array.from({length:t},(t,n)=>{let r=v8(e,n),i=y8(e,r);return{offset:n,label:b8(e,r,n),start:r,end:i,isNow:n===0}})}var S8={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 C8(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function w8(e,t){let n=k8(e);return n?(n.setDate(n.getDate()+t),C8(n)):e}function T8(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<=w8(t.end,1)?e.end>t.end&&(t.end=e.end):n.push({...e})}return n}function E8(e,t){let n=e.find(e=>t>=e.start&&t<=e.end);if(!n)return T8([...e,{start:t,end:t}]);let r=e.filter(e=>e!==n);return n.start<=w8(t,-1)&&r.push({start:n.start,end:w8(t,-1)}),w8(t,1)<=n.end&&r.push({start:w8(t,1),end:n.end}),r.sort((e,t)=>e.start.localeCompare(t.start))}function D8(e,t){if(e===`week`||e===`month`){let e=new Date(t.end);return e.setDate(e.getDate()-1),{start:C8(t.start),end:C8(e)}}return{start:String(t.start.getFullYear()),end:String(t.end.getFullYear()-1)}}function O8({quickFilterKey:e,activeRangeCount:t,onSelectRanges:n,histogramNames:r}){let{state:i}=Os(),{activeWorkspaceName:a,activeTreeName:o,activeContextPath:s,filters:c}=i,[l,u]=(0,X.useState)(3),[d,f]=(0,X.useState)(g8),[p,m]=(0,X.useState)(new Set),[h,g]=(0,X.useState)([]),[_,v]=(0,X.useState)(e);e!==_&&(v(e),e&&S8[e]!==void 0&&u(S8[e]),m(new Set));let[y,b]=(0,X.useState)(t);t!==y&&(b(t),t===0&&m(new Set));let x=h8[l],S=x8(x.unit,d),C=JSON.stringify(c.features)+JSON.stringify(c.geo),w=r.join(`,`);(0,X.useEffect)(()=>{if(!a||r.length===0)return;let e=!1,t=setTimeout(()=>{Co(a,{names:r,buckets:x8(x.unit,d).map(e=>D8(x.unit,e)),context:s??`/`,...o?{treeNameOrTreeId:o}:{},allOf:c.features.allOf,anyOf:c.features.anyOf,noneOf:c.features.noneOf,filters:R_(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(g8),m(new Set)},O=(0,X.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:C8(n),end:C8(r)}})),i})},[S,n]);return(0,Z.jsxs)(`div`,{className:`w-48 shrink-0 flex flex-col border-r border-border bg-muted/20`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between gap-1 px-2 py-1.5 border-b border-border shrink-0`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] font-semibold text-foreground/80 select-none`,children:x.label}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[(0,Z.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,Z.jsx)(B,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(F,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.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,Z.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:K(`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,Z.jsx)(cn,{className:`w-3 h-3 shrink-0`}),(0,Z.jsxs)(`span`,{className:`flex-1 min-w-0 flex flex-col`,children:[(0,Z.jsxs)(`span`,{className:`flex items-baseline justify-between gap-1`,children:[(0,Z.jsx)(`span`,{className:`truncate`,children:e.label}),r>0&&(0,Z.jsx)(`span`,{className:K(`text-[9px] tabular-nums shrink-0`,t?`text-primary-foreground/80`:`text-muted-foreground/70`),children:r})]}),r>0&&(0,Z.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,Z.jsx)(`span`,{style:{width:`${t/r*100}%`,backgroundColor:d8(e)}},e))})]})]},e.offset)}),d<200&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(e=>e+g8),className:`w-full text-[11px] text-muted-foreground/60 hover:text-muted-foreground py-1.5 transition-colors text-center`,children:`Show older…`})]})]})}function k8(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 A8({ranges:e,onCommitRange:t,onToggleDay:n}){let r=new Date,[i,a]=(0,X.useState)(()=>{let t=e[0]?.start&&k8(e[0].start)||r;return{y:t.getFullYear(),m:t.getMonth()}}),[o,s]=(0,X.useState)(null),[c,l]=(0,X.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=C8(r);return(0,Z.jsxs)(`div`,{className:`select-none`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-1.5`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.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,Z.jsx)(w,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(oe,{className:`w-3.5 h-3.5`})})]}),(0,Z.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:[_8[i.m],` `,i.y]}),(0,Z.jsxs)(`div`,{className:`flex items-center`,children:[(0,Z.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,Z.jsx)(Ye,{className:`w-3.5 h-3.5`})}),(0,Z.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,Z.jsx)(gr,{className:`w-3.5 h-3.5`})})]})]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 mb-0.5`,children:[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase text-muted-foreground/60 py-0.5`,children:e},e))}),(0,Z.jsx)(`div`,{className:`grid grid-cols-7 gap-y-0.5`,children:m.map(e=>{let t=C8(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,Z.jsx)(`button`,{type:`button`,onClick:e=>d(t,e.ctrlKey||e.metaKey),onMouseEnter:()=>o&&l(t),className:K(`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,Z.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 j8({label:e,checked:t,onChange:n,color:r}){return(0,Z.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,Z.jsxs)(`span`,{className:`flex items-center gap-2 min-w-0`,children:[(0,Z.jsx)(`span`,{className:`w-2 h-2 rounded-full shrink-0`,style:{backgroundColor:r}}),(0,Z.jsx)(`span`,{className:`text-sm text-foreground truncate`,children:e})]}),(0,Z.jsx)(`div`,{className:K(`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,Z.jsx)(`div`,{className:K(`absolute top-[2px] w-4 h-4 rounded-full bg-background shadow-elevation-1 transition-transform`,t?`translate-x-[22px]`:`translate-x-[2px]`)})})]})}function M8(){let{state:e,setTimelineFilter:t,createTimeline:n,deleteTimeline:r,refreshTimelines:i}=Os(),{timeline:a}=e.filters,{availableTimelines:o,timelineScales:s,timelinesLoading:c}=e,[l,u]=(0,X.useState)(``),[d,f]=(0,X.useState)(!1),[p,m]=(0,X.useState)(null),[h,g]=(0,X.useState)(`quick`),[_,v]=(0,X.useState)(!1),{showToast:y}=Vr(),b=new Set(a.selectedTimelines??[]),x=(0,X.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=B_(a),D=E.length>0,O=(0,X.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,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1 items-center`,children:[(0,Z.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e.label}),e.cells.map((e,n)=>{let r=a.quickFilter===e&&!D;return(0,Z.jsx)(`button`,{type:`button`,onClick:()=>k(e),className:K(`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?m8[n]:[`Last`,`This`,`Next`][n]},e)})]},e.label);return(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0`,children:[(0,Z.jsx)(O8,{quickFilterKey:a.quickFilter,activeRangeCount:E.length,onSelectRanges:O,histogramNames:x}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:h===`quick`?`Quick filter`:`Date range`}),(0,Z.jsxs)(`div`,{className:`flex rounded-md overflow-hidden border border-border divide-x divide-border`,children:[(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`quick`),className:K(`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,Z.jsx)(_e,{className:`w-3 h-3`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>g(`calendar`),className:K(`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,Z.jsx)(Nn,{className:`w-3 h-3`})})]})]}),h===`quick`?(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsxs)(`div`,{className:`grid grid-cols-[3.5rem_1fr_1fr_1fr] gap-1`,children:[(0,Z.jsx)(`span`,{}),[`Last`,`This`,`Next`].map(e=>(0,Z.jsx)(`span`,{className:`text-center text-[9px] font-semibold uppercase tracking-wide text-muted-foreground/60`,children:e},e))]}),f8.map((e,t)=>j(e,t===0)),(0,Z.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,Z.jsx)(Ge,{className:K(`w-3 h-3 transition-transform`,!_&&`-rotate-90`)}),`Deep time`]}),_&&p8.map(e=>j(e,!1))]}):(0,Z.jsx)(A8,{ranges:E,onCommitRange:(e,n)=>t({customRanges:[{start:e,end:n}],customRange:null,quickFilter:null}),onToggleDay:e=>t({customRanges:E8(E,e),customRange:null,quickFilter:null})}),D&&(0,Z.jsx)(`div`,{className:`mt-2 space-y-1`,children:E.map((e,t)=>(0,Z.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,Z.jsx)(`span`,{className:`text-xs text-foreground truncate`,children:e.start===e.end?e.start:`${e.start} → ${e.end}`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>A(t),className:`text-muted-foreground hover:text-foreground shrink-0`,title:`Remove range`,children:(0,Z.jsx)(Me,{className:`w-3.5 h-3.5`})})]},`${e.start}..${e.end}`))})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Apply to`}),(0,Z.jsxs)(`div`,{className:`space-y-2`,children:[(0,Z.jsx)(j8,{label:`crud:created`,checked:a.indexCreated,onChange:e=>t({indexCreated:e}),color:d8(`crud:created`)}),(0,Z.jsx)(j8,{label:`crud:updated`,checked:a.indexUpdated,onChange:e=>t({indexUpdated:e}),color:d8(`crud:updated`)}),(0,Z.jsx)(j8,{label:`crud:deleted`,checked:a.indexDeleted,onChange:e=>t({indexDeleted:e}),color:d8(`crud:deleted`)}),(0,Z.jsx)(j8,{label:`content`,checked:a.contentEvents,onChange:e=>t({contentEvents:e}),color:d8(`content`)})]}),(0,Z.jsx)(`p`,{className:`text-[10px] text-muted-foreground/70 mt-1`,children:`content = content-derived timestamps (EXIF, logs, extracted periods)`})]}),(0,Z.jsxs)(`div`,{children:[(0,Z.jsxs)(`div`,{className:`flex items-center justify-between mb-2`,children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground`,children:`Domain timelines`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>i(),className:`text-muted-foreground/60 hover:text-muted-foreground transition-colors`,title:`Refresh timelines`,children:(0,Z.jsx)(we,{className:`w-3 h-3`})})]}),c?(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 py-2 text-xs text-muted-foreground`,children:[(0,Z.jsx)(Mt,{className:`w-3 h-3 animate-spin`}),`Loading…`]}):T.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground py-1`,children:`No domain timelines yet`}):(0,Z.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:T.map(e=>{let t=b.has(e),n=d8(e);return(0,Z.jsxs)(`div`,{className:K(`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,Z.jsx)(`div`,{className:K(`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,Z.jsx)(`svg`,{className:K(`w-2.5 h-2.5`,gp(n)),viewBox:`0 0 10 10`,fill:`none`,children:(0,Z.jsx)(`path`,{d:`M2 5l2.5 2.5L8 3`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}),(0,Z.jsx)(`span`,{className:`flex-1 text-sm text-foreground truncate select-none`,children:e}),(s[e]?.length??0)>0&&(0,Z.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,Z.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,Z.jsx)(Mt,{className:`w-3 h-3 animate-spin`}):(0,Z.jsx)(lt,{className:`w-3 h-3`})})]},e)})}),(0,Z.jsxs)(`div`,{className:`mt-3 flex gap-1.5`,children:[(0,Z.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,Z.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,Z.jsx)(Mt,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(U,{className:`w-3.5 h-3.5`})})]})]})]})]})}var N8={data:`Data`,"data/backend":`Backends`,"data/mime":`MIME types`,"data/dataset":`Datasets`,client:`Client`,tag:`Tags`,device:`Device`,custom:`Custom`,feature:`Feature`},P8=`data/dataset/default`;function F8(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 I8=[`off`,`anyOf`,`allOf`,`noneOf`];function L8(e){return I8[(I8.indexOf(e)+1)%I8.length]}var R8=[{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 z8({mode:e,onSet:t}){return(0,Z.jsx)(`div`,{className:`flex shrink-0 rounded-md overflow-hidden border border-border divide-x divide-border`,children:R8.map(n=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e===n.m?`off`:n.m),className:K(`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 B8({keys:e,modeOf:t,onCycle:n}){return e.length?(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:`Document types`}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let{label:r,icon:i}=o6(e),a=t(e),o=R8.find(e=>e.m===a);return(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>n(e),title:`${e}: ${a===`off`?`tap to filter`:a}`,className:K(`relative flex flex-col items-center justify-center gap-1.5 rounded-lg 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,Z.jsx)(`span`,{className:K(`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,Z.jsx)(i,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:r})]},e)})})]}):null}function V8(){let{state:e,setFeatureMode:t,clearFilters:n,hasActiveFilters:r,deleteBitmap:i,deleteDataset:a}=Os(),{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,X.useState)(``),[h,g]=(0,X.useState)(null),{showToast:_}=Vr(),v=async e=>{if(e.startsWith(`data/dataset/`)&&e!==P8){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,Z.jsx)(`div`,{className:`flex items-center justify-center py-10`,children:(0,Z.jsx)(Mt,{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,Z.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(i6)).sort((e,t)=>{let n=Object.keys(a6),r=n.indexOf(e),i=n.indexOf(t);return(r===-1?n.length:r)-(i===-1?n.length:i)||e.localeCompare(t)}),w=F8(S.filter(e=>!e.startsWith(i6))),T=w.get(`data/dataset`);return T&&!T.includes(P8)&&(!x||P8.includes(x))&&T.unshift(P8),(0,Z.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`px-4 py-2 border-b border-border shrink-0 space-y-2`,children:[(0,Z.jsxs)(`div`,{className:`relative`,children:[(0,Z.jsx)(pr,{className:`absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none`}),(0,Z.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,Z.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,Z.jsx)(Me,{className:`w-3 h-3`}),`Clear all filters`]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 space-y-5`,children:[(0,Z.jsx)(B8,{keys:C,modeOf:f,onCycle:e=>t(e,L8(f(e)))}),w.size===0&&C.length===0?(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground text-center py-6`,children:`No matches`}):Array.from(w.entries()).map(([e,n])=>(0,Z.jsxs)(`div`,{children:[(0,Z.jsx)(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-muted-foreground mb-2`,children:N8[e]??e}),(0,Z.jsx)(`div`,{className:`flex flex-col gap-1`,children:n.map((e,n)=>{let r=e.startsWith(`data/`),i=e===P8,a=e.startsWith(`data/dataset/`)&&!i,o=f(e);return(0,Z.jsxs)(`div`,{onClick:()=>t(e,L8(o)),role:`button`,tabIndex:0,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e,L8(o)))},className:K(`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,Z.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,Z.jsx)(`span`,{className:`ml-1.5 text-[10px] text-muted-foreground font-sans`,children:`virtual · on by default`})]}),(0,Z.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,Z.jsx)(z8,{mode:o,onSet:n=>t(e,n)})}),(!r||a)&&(0,Z.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,Z.jsx)(Mt,{className:`w-3.5 h-3.5 animate-spin`}):(0,Z.jsx)(lt,{className:`w-3.5 h-3.5`})})]},e)})})]},e))]})]})}function H8(){let{state:e,setToolsTab:t,saveFilters:n,clearFilters:r,hasActiveFilters:i,setLiveEnabled:a}=Os(),{toolsTab:o,isDirty:s,isSaving:c,activeContextType:l,savedSearchQuery:u}=e,d=nl(),f=new URLSearchParams(d.search).get(`q`)||new URLSearchParams(d.search).get(`search`)||``,p=l!==null&&f.trim()!==(u||``),m=l!==null&&(s||p);return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e.id),className:K(`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,Z.jsxs)(`div`,{className:`space-y-2 border-b border-border px-3 py-2 shrink-0`,children:[(0,Z.jsxs)(`label`,{className:`flex min-h-10 cursor-pointer items-center justify-between gap-3 text-sm font-medium`,children:[(0,Z.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(`span`,{className:K(`h-2 w-2 rounded-full`,e.liveEnabled?`bg-success`:`bg-muted-foreground`)}),`Live`]}),(0,Z.jsx)(`input`,{type:`checkbox`,className:`h-5 w-5 accent-current`,checked:e.liveEnabled,disabled:new URLSearchParams(d.search).has(`ownerId`),onChange:e=>{a(e.target.checked)}})]}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.liveEnabled?`Filters and camera matches update every device bound to this context. Save to keep the current view.`:`Preview on this device. Turn on Live to update bound devices.`}),e.liveError&&(0,Z.jsx)(`p`,{role:`status`,className:`text-xs text-destructive`,children:e.liveError})]}),(i||m)&&(0,Z.jsxs)(`div`,{className:`flex items-center justify-end gap-2 border-b border-border px-3 py-1.5 shrink-0`,children:[i&&(0,Z.jsxs)(`button`,{type:`button`,onClick:r,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`,title:`Clear all active filters`,children:[(0,Z.jsx)(Me,{className:`w-3 h-3`}),`Clear`]}),m&&(0,Z.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,Z.jsx)(Mt,{className:`w-3 h-3 animate-spin`}):(0,Z.jsx)(k,{className:`w-3 h-3`}),l===`context`&&e.liveEnabled?`Save current view`:`Save filters`]})]}),(0,Z.jsxs)(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[o===`features`&&(0,Z.jsx)(V8,{}),o===`timeline`&&(0,Z.jsx)(M8,{}),o===`map`&&(0,Z.jsx)(r8,{}),o===`lens`&&(0,Z.jsx)(c8,{})]})]})}function U8({status:e}){return(0,Z.jsx)(`span`,{className:K(`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 W8(){let{openAgentT2:e}=Os(),{setSection:t}=zS(),n=al(),{agents:r,isLoading:i,refresh:a}=x3(!0),{showToast:o}=Vr(),[s,c]=(0,X.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 CE(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 wE(t.id),a()}catch(e){o({title:`Error`,description:e instanceof Error?e.message:`Failed`,variant:`destructive`})}finally{l(t.id,!1)}};return(0,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsx)(`div`,{className:`flex items-center justify-between px-4 h-12 border-b border-border shrink-0`,children:(0,Z.jsx)(`span`,{className:`text-sm font-semibold`,children:`Agents`})}),(0,Z.jsx)(`div`,{className:`flex-1 overflow-y-auto py-2`,children:i&&r.length===0?(0,Z.jsx)(`div`,{className:`px-4 py-3 text-xs text-muted-foreground`,children:`Loading…`}):r.length===0?(0,Z.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-12 text-muted-foreground`,children:[(0,Z.jsx)(dt,{className:`w-8 h-8 opacity-30`}),(0,Z.jsx)(`span`,{className:`text-xs`,children:`No agents yet`}),(0,Z.jsx)(`button`,{type:`button`,onClick:()=>{t(`agents`),n(`/agents?create=1`)},className:`text-xs text-primary hover:underline`,children:`Create an agent`})]}):(0,Z.jsx)(`div`,{className:`space-y-1 px-2`,children:r.map(t=>{let n=s.has(t.id);return(0,Z.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,Z.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Z.jsx)(U8,{status:t.status}),(0,Z.jsx)(`span`,{className:`text-sm font-medium flex-1 truncate`,children:t.label||t.name}),(0,Z.jsx)(`div`,{className:`flex items-center gap-0.5 shrink-0 reveal-on-hover`,children:t.status===`active`?(0,Z.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,Z.jsx)(nn,{className:`w-3 h-3`})}):(0,Z.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,Z.jsx)(De,{className:`w-3 h-3`})})})]}),t.description&&(0,Z.jsx)(`div`,{className:`text-xs text-muted-foreground truncate mt-0.5 pl-4`,children:t.description})]},t.id)})})})]})}function G8(){return(0,Z.jsx)(`div`,{className:`flex h-full flex-col`,children:(0,Z.jsxs)(`div`,{className:`flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,Z.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,Z.jsx)($t,{className:`h-5 w-5 text-muted-foreground`})}),(0,Z.jsxs)(`div`,{className:`space-y-1`,children:[(0,Z.jsx)(`p`,{className:`text-sm font-medium text-foreground`,children:`No notifications yet`}),(0,Z.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This is where activity, agent updates, and alerts will appear once notifications are wired in.`})]})]})})}function K8(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(`
|
|
96
96
|
`)||``}function q8(e){let[t,n]=(0,X.useState)([]),[r,i]=(0,X.useState)(!1),[a,o]=(0,X.useState)(null),s=(0,X.useRef)(null),[c,l]=(0,X.useState)(e);return c!==e&&(l(e),e||n([])),(0,X.useEffect)(()=>{let t=!1;if(e)return dE(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,X.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 CE(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 J.stream(`${Rr}/agents/${e}/prompt/stream`,{message:t},{signal:s.current.signal,onChunk:e=>{a+=e;let t=a.split(`
|
|
97
|
-
`);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=K8(t),i=QT(t)||l;u=$T(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,X.useCallback)(async t=>{if(!(r||!e)){o(null),i(!0),n(e=>[...e,{role:`user`,content:`🎤 Transcribing…`,isComplete:!1}]);try{let r=await AE(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,X.useCallback)(()=>{s.current?.abort(),i(!1)},[]),clear:(0,X.useCallback)(()=>{n([]),o(null)},[])}}function J8(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(null),i=(0,X.useRef)(null),a=(0,X.useRef)([]);return{isRecording:e,recorderError:n,start:(0,X.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,X.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,X.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 Y8({agentId:e,onClose:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),{showToast:m}=Vr(),h=Uo(),g=h?.state.activeContextType===`context`?h.state.activeContextId:null,_=h?.state.activeContextPath??null,v=(0,X.useRef)(null),y=(0,X.useRef)(null),{messages:b,isStreaming:x,error:S,send:C,sendVoice:w,stop:T,clear:E}=q8(e),{isRecording:D,recorderError:O,start:k,stop:A}=J8();(0,X.useEffect)(()=>{uE(e).then(r).catch(()=>{}),iE(e).then(l).catch(()=>l(null))},[e]),(0,X.useEffect)(()=>{kE().then(e=>s(!!(e.enabled&&e.stt))).catch(()=>s(!1))},[]),(0,X.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 aE(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,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 h-12 border-b border-border shrink-0`,children:[(0,Z.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,Z.jsx)(Bt,{className:`w-4 h-4`})}),n?.color&&(0,Z.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0`,style:{backgroundColor:n.color}}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:n?.label||n?.name||e}),(0,Z.jsx)(`div`,{className:`text-[10px] leading-tight text-muted-foreground truncate`,title:M,children:M})]}),(0,Z.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,Z.jsx)(lt,{className:`w-3.5 h-3.5`})})]}),g&&!j&&(0,Z.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,Z.jsxs)(`span`,{className:`flex-1 truncate text-muted-foreground`,title:g||_||void 0,children:[`Toolbox context: `,g||_]}),(0,Z.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,Z.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,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:`Token (shown once):`}),(0,Z.jsx)(`code`,{className:`flex-1 truncate font-mono`,children:f}),(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>p(null),className:`shrink-0 rounded px-1.5 py-1 hover:bg-accent`,title:`Dismiss`,children:`×`})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3 space-y-3`,children:[b.length===0&&(0,Z.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,Z.jsxs)(`div`,{className:K(`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,Z.jsx)(AA,{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,Z.jsx)(dh,{content:e.content||(e.isComplete?``:`…`)}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap`,children:e.content})]},t)),(S||O)&&(0,Z.jsx)(`div`,{className:`text-xs text-destructive text-center py-1`,children:S||O}),(0,Z.jsx)(`div`,{ref:v})]}),(0,Z.jsx)(`div`,{className:`p-3 border-t border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2 items-end`,children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(D){let e=await A();e&&await w(e)}else x||await k()},disabled:x&&!D,className:K(`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,Z.jsx)(nn,{className:`w-4 h-4`}):(0,Z.jsx)(ft,{className:`w-4 h-4`})}),x?(0,Z.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,Z.jsx)(nn,{className:`w-4 h-4`})}):(0,Z.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,Z.jsx)(tr,{className:`w-4 h-4`})})]})})]})}function X8(){let{state:e,openApplet:t}=Os(),[n,r]=(0,X.useState)(`context`),i=e.appsAppletId,a=i?Nx.find(e=>e.id===i):null;if(a)return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5`,children:[(0,Z.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,Z.jsx)(Bt,{className:`h-4 w-4`})}),(0,Z.jsx)(a.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:a.label})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(a.Component,{})})]});let o=Px(n);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(`div`,{className:`flex shrink-0 border-b border-border`,children:[`context`,`global`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:K(`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,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[!o.length&&(0,Z.jsxs)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:[`No `,n,` applets yet.`]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:o.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex min-h-[4.5rem] flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-muted/40 p-3 text-foreground transition-colors hover:bg-muted`,title:e.description,children:[(0,Z.jsx)(e.icon,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:e.label})]},e.id))})]})]})}var Z8=[{view:`apps`,icon:dr,label:`Apps`},{view:`tools`,icon:kt,label:`Filters`},{view:`agents`,icon:dt,label:`Agents`},{view:`notifications`,icon:$t,label:`Notifications`}],Q8=420,$8=340,e5=`toolbox:width`,t5=360,n5=48,r5=e=>{let t=typeof window<`u`?window.innerWidth:1600,n=Math.max($8,Math.min(Math.round(t*.7),t-n5-t5));return Math.max($8,Math.min(e,n))},i5=()=>typeof window<`u`?Math.round(window.innerWidth/2):720;function a5(){let{state:e,setView:t,closeT1:n,closeT2:r}=Os();Ff(n,e.t1Open&&!e.t2Open),Ff(r,e.t2Open);let{t1Open:i,t1View:a,t2Open:o,t2AgentId:s,activeAccentColor:c}=e,l=Ym(),[u,d]=(0,X.useState)(()=>{let e=typeof window<`u`?Number(localStorage.getItem(e5)):NaN;return Number.isFinite(e)&&e>0?e:Q8}),f=(0,X.useCallback)(e=>{d(e);try{localStorage.setItem(e5,String(e))}catch{}},[]),p=(0,X.useRef)(null),m=(0,X.useCallback)(e=>{e.preventDefault(),p.current={startX:e.clientX,startWidth:u};let t=e=>{if(!p.current)return;let t=r5(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(e5,String(e))}catch{}return e})};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[u]),h=u>=i5()*.9;return(0,X.useEffect)(()=>{let e=()=>d(e=>r5(e));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),!i||!a?null:(0,Z.jsxs)(Z.Fragment,{children:[l&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:l?void 0:{width:u},className:K(`flex flex-col overflow-hidden border bg-card surface-glass text-foreground`,l?`fixed bottom-2 left-2 right-2 top-2 z-panel rounded-2xl shadow-elevation-5 animate-fade-in`:`relative shrink-0 rounded-[var(--panel-radius)] shadow-elevation-3`),children:[!l&&(0,Z.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,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-1 border-b-[3px] px-2`,style:c?{borderBottomColor:c}:void 0,children:[(0,Z.jsx)(`div`,{className:`flex items-center gap-1`,children:Z8.map(({view:e,icon:n,label:r})=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e),"aria-label":r,title:r,className:K(`flex h-8 w-8 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,Z.jsx)(n,{className:`h-4 w-4 shrink-0`})},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[!l&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(h?Q8:r5(i5())),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,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Close toolbox`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]})]}),(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${o&&s?`invisible`:``}`,children:[a===`home`&&(0,Z.jsx)(U6,{}),a===`apps`&&(0,Z.jsx)(X8,{}),a===`tools`&&(0,Z.jsx)(H8,{}),a===`agents`&&(0,Z.jsx)(W8,{}),a===`notifications`&&(0,Z.jsx)(G8,{})]}),o&&s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex flex-col bg-background`,children:(0,Z.jsx)(Y8,{agentId:s,onClose:r})})]})]})]})}function o5(){let{running:e,hasViewer:t,paused:n,snapshot:r,source:i,lastCount:a,error:o,setPaused:s,stop:c,reopen:l}=ix();if(!e||t)return null;let u=i===`screen`?fe:i===`photo`?y:z;return(0,Z.jsxs)(`div`,{className:K(`fixed right-4 w-56 overflow-hidden rounded-xl 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,Z.jsxs)(`button`,{type:`button`,onClick:l,title:`Back to Lens`,className:`relative block w-full cursor-pointer bg-black/80 aspect-video`,children:[(0,Z.jsx)(vx,{className:`h-full w-full`}),r&&(0,Z.jsx)(`img`,{src:r,alt:``,className:`absolute inset-0 h-full w-full bg-black object-contain`}),n&&(0,Z.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white`,children:`paused`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1.5`,children:[(0,Z.jsx)(u,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-muted-foreground`,children:o?(0,Z.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,Z.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,Z.jsx)(De,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Xe,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(Fn,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(Se,{className:`h-3.5 w-3.5`})})]})]})}function s5({children:e}){let[t,n]=(0,X.useState)(null),r={entry:t,open:(e,t)=>n({document:e,workspaceId:t}),close:()=>n(null)};return(0,Z.jsx)(pm.Provider,{value:r,children:e})}var c5={key:`desk`,label:`Desk`,main:`/`,mainExpanded:!1,entries:[]},l5=0,u5=()=>`c${++l5}`;function d5(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 f5({children:e}){let t=nl(),n=al(),[r,i]=(0,X.useState)([c5]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(a_),l=(0,X.useRef)(r),u=(0,X.useRef)(a),d=(0,X.useRef)(s);(0,X.useEffect)(()=>{l.current=r,u.current=a,d.current=s},[r,a,s]);let f=(0,X.useCallback)((e,t)=>{let n=l.current.slice();n[e]=t,l.current=n,i(n)},[]),p=(0,X.useCallback)(e=>{let t=u.current,n=l.current[t];n&&f(t,e(n))},[f]),m=t.pathname+t.search;(0,X.useEffect)(()=>{p(e=>e.main===m?e:{...e,main:m})},[m,p]);let h=(0,X.useCallback)(e=>{let t=l.current[u.current];if(!t)return;let n=t.entries.find(t=>d5(e,t));if(n){c(n.id);return}let r={...e,id:u5()},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,X.useCallback)((e,t)=>{h({kind:`document`,document:e,workspaceId:t})},[h]),_=(0,X.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,X.useCallback)(e=>{p(t=>({...t,entries:t.entries.filter(t=>t.id!==e)})),c(t=>t===e?a_:t)},[p]),y=(0,X.useCallback)((e,t)=>{p(n=>({...n,entries:n.entries.map(n=>n.id===e&&n.kind===`route`?{...n,location:t}:n)}))},[p]),b=(0,X.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,X.useCallback)(e=>{let t=l.current[e];t&&(u.current=e,o(e),c(a_),n(t.main))},[n]),S=(0,X.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,X.useCallback)(e=>{x(u.current+e)},[x]),w=(0,X.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,X.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,X.useMemo)(()=>({entry:null,open:g,preview:_,close:()=>{}}),[g,_]);return(0,Z.jsx)(o_.Provider,{value:T,children:(0,Z.jsx)(pm.Provider,{value:E,children:e})})}function p5(e){return Ks(typeof e==`string`?qs(e):e)}function m5({location:e,onNavigate:t}){let n=(0,X.useMemo)(()=>{let t=qs(e);return{pathname:t.pathname||`/`,search:t.search||``,hash:t.hash||``,state:null,key:e}},[e]),r=(0,X.useMemo)(()=>({basename:`/`,static:!1,useTransitions:void 0,future:{},navigator:{createHref:p5,go:()=>{},push:e=>t(p5(e)),replace:e=>t(p5(e))}}),[t]);return(0,Z.jsx)(Gc.Provider,{value:r,children:(0,Z.jsx)(Kc.Provider,{value:{location:n,navigationType:Ls.Push},children:(0,Z.jsx)(qc.Provider,{value:{outlet:null,matches:[],isDataRoute:!1},children:(0,Z.jsx)(Fl,{children:i4})})})})}var h5=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,g5=420,_5=e=>e<=0?0:e>=1?1:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2;function v5(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)/g5);e.scrollLeft=r+i*_5(l),l<1?s=requestAnimationFrame(c):(e.style.scrollSnapType=a,n?.())};return s=requestAnimationFrame(c),()=>{cancelAnimationFrame(s),e.style.scrollSnapType=a}}function y5(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 b5({section:e}){return e===`contexts`?(0,Z.jsx)(j4,{}):e===`workspaces`?(0,Z.jsx)(Y4,{}):e===`agents`?(0,Z.jsx)(C3,{}):e===`admin`||e===`settings`?(0,Z.jsx)(k3,{}):null}function x5(e,t){if(e?.kind===`document`)return Ui(e.document).title;let n=(e?.kind===`route`?e.location:t).split(/[?#]/)[0];if(n===`/settings`)return`Settings`;let r=hS.flatMap(e=>[...e.items]).find(e=>e.path===n);if(r)return r.label;let i=n.split(`/`).filter(Boolean);return i.length===0?`Desk`:decodeURIComponent(i[i.length-1])}function S5({id:e,title:t,expanded:n,focused:r,onFocus:i,onToggleExpanded:a,onClose:o,badge:s,contentHeader:c,children:l}){let u=U3();return(0,Z.jsxs)(`section`,{"data-reader-pane":c?!0:void 0,style:c&&!n&&u?{"--reader-width":`${u}px`,transition:`none`}:void 0,"data-strip-col":e,className:K(`strip-canvas surface-sheet relative`,n&&`strip-canvas--wide`,r&&`strip-canvas--focused`),onPointerDownCapture:()=>i(e),"aria-label":t,children:[c&&!n&&(0,Z.jsx)(K3,{edge:`right`}),!c&&(0,Z.jsxs)(`header`,{className:`strip-canvas-bar`,children:[s&&(0,Z.jsx)(`span`,{className:`strip-row-label`,children:s}),(0,Z.jsx)(`span`,{className:`strip-canvas-title`,title:t,children:t}),(0,Z.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,Z.jsx)(it,{className:`size-3.5`}):(0,Z.jsx)(Fn,{className:`size-3.5`})}),o&&(0,Z.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:s?`Close row`:`Close canvas`,onClick:()=>o(e),children:(0,Z.jsx)(Me,{className:`size-3.5`})})]}),(0,Z.jsx)(`div`,{className:`strip-canvas-body`,children:l})]})}function C5(e){return K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!X3(e)&&!Y3(e)&&`p-page`)}function w5({row:e,pathname:t,rowLabel:n,onCloseRow:r}){let{focus:i,setFocus:a,toggleExpanded:o,closeCanvas:s,navigateCanvas:c}=s_(),l=(0,X.useCallback)(e=>t=>c(e,t),[c]);return(0,Z.jsxs)(Z.Fragment,{children:[t===`/`?(0,Z.jsx)(`div`,{hidden:!0,children:(0,Z.jsx)(Ml,{})}):(0,Z.jsx)(S5,{id:a_,title:x5(null,t),expanded:e.mainExpanded,focused:i===a_,onFocus:a,onToggleExpanded:o,badge:n,onClose:r,children:(0,Z.jsx)(`main`,{id:`content-area`,className:C5(t),children:(0,Z.jsx)(Ml,{})})}),e.entries.map(e=>(0,Z.jsx)(S5,{id:e.id,title:x5(e,t),expanded:!!e.expanded,focused:i===e.id,onFocus:a,onToggleExpanded:o,contentHeader:e.kind===`document`,onClose:s,children:e.kind===`route`?(0,Z.jsx)(`div`,{className:C5(e.location.split(`?`)[0]),children:(0,Z.jsx)(m5,{location:e.location,onNavigate:l(e.id)})}):(0,Z.jsx)(`div`,{className:`flex flex-1 min-h-0 min-w-0 items-stretch`,children:(0,Z.jsx)(J3,{entry:e,onClose:()=>s(e.id),frame:{expanded:!!e.expanded,onToggleExpanded:()=>o(e.id)}})})},e.id))]})}function T5({row:e}){return(0,Z.jsxs)(`div`,{className:`strip-ghost-row`,"aria-hidden":!0,children:[(0,Z.jsx)(`span`,{className:`strip-ghost-chip strip-ghost-chip--main`,children:x5(null,e.main)}),e.entries.map(t=>(0,Z.jsx)(`span`,{className:`strip-ghost-chip`,children:x5(t,e.main)},t.id))]})}function E5(){let{state:e,closeM1:t,closeM2:n}=zS(),{rows:r,activeRow:i,focus:a,setFocus:o,moveRow:s,closeRow:c}=s_(),{pathname:l}=nl(),u=IS(),d=(0,X.useRef)(null);Ff(t,e.m1Open&&!e.m2Open),Ff(n,e.m2Open),(0,X.useLayoutEffect)(()=>{let e=d.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 f=(0,X.useRef)(e.m1Open);(0,X.useEffect)(()=>{e.m1Open&&!f.current&&!e.m2Open&&o(`m1`),f.current=e.m1Open},[e.m1Open,e.m2Open,o]);let p=(0,X.useRef)(e.m2Open);(0,X.useEffect)(()=>{e.m2Open&&!p.current&&o(`m2`),!e.m2Open&&p.current&&a===`m2`&&o(e.m1Open?`m1`:a_),p.current=e.m2Open},[e.m2Open,e.m1Open,a,o]),(0,X.useEffect)(()=>{!e.m1Open&&a===`m1`&&o(a_)},[e.m1Open,a,o]),(0,X.useEffect)(()=>{let e=d.current,t=e?.querySelector(`[data-strip-col="${CSS.escape(a)}"]`);if(!(!e||!t))return v5(e,y5(e,t))},[a,r,i,e.m1Open,e.m2Open]);let m=(0,X.useCallback)(()=>{let t=r[i];return[...e.m1Open?[`m1`]:[],...e.m2Open?[`m2`]:[],...l===`/`?[]:[a_],...t?t.entries.map(e=>e.id):[]]},[r,i,e.m1Open,e.m2Open,l]);return(0,X.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||!e.key.startsWith(`Arrow`)||!LS(e,u))return;let t=e.target;if(!(t?.closest(h5)||t?.closest(`[role="dialog"]`))){if(e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=m(),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)},[m,a,o,s,r.length,u]),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`strip-shell flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(k4,{}),(0,Z.jsxs)(`div`,{ref:d,className:`strip-scroller`,children:[e.m1Open&&(0,Z.jsx)(`div`,{"data-strip-col":`m1`,className:K(`strip-col strip-menu-col`,a===`m1`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m1`),children:(0,Z.jsx)(b5,{section:e.activeSection})}),e.m2Open&&(0,Z.jsx)(`div`,{"data-strip-col":`m2`,className:K(`strip-col strip-menu-col`,a===`m2`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m2`),children:(0,Z.jsx)(N3,{})}),(0,Z.jsx)(`div`,{className:`strip-rows`,style:{transform:`translateY(${-i*100}%)`},children:r.map((e,t)=>(0,Z.jsx)(`div`,{className:K(`strip-row`,t===i&&`strip-row--active`),children:(0,Z.jsx)(`div`,{className:`strip-row-canvases`,children:t===i?(0,Z.jsx)(w5,{row:e,pathname:l,rowLabel:r.length>1?e.label:void 0,onCloseRow:t>0?()=>c(e.key):void 0}):(0,Z.jsx)(T5,{row:e})})},e.key))})]}),(0,Z.jsx)(B6,{}),(0,Z.jsx)(a5,{})]}),(0,Z.jsx)(e6,{}),(0,Z.jsx)(O4,{}),(0,Z.jsx)(o5,{})]})}function D5(){let e=DS();return(0,Z.jsx)(f4,{children:(0,Z.jsx)(r6,{children:(0,Z.jsx)(_6,{children:(0,Z.jsx)(yx,{children:(0,Z.jsx)(s5,{children:e===`strip`?(0,Z.jsx)(f5,{children:(0,Z.jsx)(Ix,{children:(0,Z.jsx)(E5,{})})}):(0,Z.jsxs)(Ix,{children:[(0,Z.jsxs)(`div`,{className:`flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(k4,{}),(0,Z.jsx)(P3,{}),(0,Z.jsx)($3,{}),(0,Z.jsx)(B6,{}),(0,Z.jsx)(a5,{})]}),(0,Z.jsx)(e6,{}),(0,Z.jsx)(O4,{}),(0,Z.jsx)(o5,{})]})})})})})})}var O5=En,k5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Ut,{ref:n,className:K(`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}));k5.displayName=Ut.displayName;var A5=vr(`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 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`}}),j5=X.forwardRef(({className:e,variant:t,...n},r)=>(0,Z.jsx)(mn,{ref:r,className:K(A5({variant:t}),e),...n}));j5.displayName=mn.displayName;var M5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Kn,{ref:n,className:K(`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}));M5.displayName=Kn.displayName;var N5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(At,{ref:n,className:K(`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,Z.jsx)(Me,{className:`h-4 w-4`})}));N5.displayName=At.displayName;var P5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Jt,{ref:n,className:K(`text-sm font-semibold`,e),...t}));P5.displayName=Jt.displayName;var F5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(zt,{ref:n,className:K(`text-sm opacity-90`,e),...t}));F5.displayName=zt.displayName;function I5({children:e}){let[t,n]=(0,X.useState)([]),r=(0,X.useRef)(new Set),i=(0,X.useCallback)(e=>{if(Tr(e.description)||Tr(e.title))return;let t=`${e.title}:${e.description??``}`;if(r.current.has(t))return;r.current.add(t);let i=Math.random().toString(36).substring(2,9);n(t=>[...t,{...e,id:i}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==i)),r.current.delete(t)},5e3)},[]),a=(0,X.useCallback)(e=>{let t=Math.random().toString(36).substring(2,9);n(n=>[...n,{...e,id:t,busy:!0}]);let r=!1,a=e=>{r||(r=!0,n(e=>e.filter(e=>e.id!==t)),e&&i(e))};return{done:a,fail:a}},[i]),o=(0,X.useMemo)(()=>({showToast:i,showProgress:a}),[i,a]);return(0,Z.jsx)(Gr.Provider,{value:o,children:(0,Z.jsxs)(O5,{children:[e,t.map(e=>(0,Z.jsxs)(j5,{variant:e.variant,duration:e.busy?1/0:void 0,children:[(0,Z.jsxs)(`div`,{className:`grid gap-1`,children:[(0,Z.jsxs)(P5,{className:`flex items-center gap-2`,children:[e.busy&&(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 shrink-0 animate-spin`}),e.title]}),e.description!=null&&(0,Z.jsx)(F5,{children:e.description})]}),!e.busy&&(0,Z.jsx)(N5,{})]},e.id)),(0,Z.jsx)(k5,{})]})})}async function L5(){return await J.get(`/messaging/notifications`,{noAuthRedirect:!0})||[]}async function R5(){await J.delete(`/messaging/notifications`,{noAuthRedirect:!0})}function z5({children:e}){let[t,n]=(0,X.useState)([]),{showToast:r}=Vr();(0,X.useEffect)(()=>{let e=!1;L5().then(t=>{e||n(t)}).catch(()=>{});let t=id.on(`notification`,e=>{let t=e;!t?.id||!t?.text||(n(e=>e.some(e=>e.id===t.id)?e:[...e,t].slice(-50)),r({title:`Notification`,description:t.text}))});return()=>{e=!0,t?.()}},[r]);let i=(0,X.useCallback)(async()=>{n([]),await R5().catch(()=>{})},[]);return(0,Z.jsx)(V6.Provider,{value:{notifications:t,clear:i},children:e})}var B5=e=>`${e.workspaceName}\0${e.treeName}\0${e.path}`;function V5({children:e}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0);(0,X.useEffect)(()=>{let e=!1;return e3().then(t=>{e||n(t)}).catch(()=>{e||n({})}).finally(()=>{e||i(!1)}),()=>{e=!0}},[]);let a=(0,X.useMemo)(()=>t?.home?.pinnedCanvases??[],[t]),[o]=(0,X.useState)(()=>fT(e3,t3,n)),s=(0,X.useCallback)(e=>a.some(t=>B5(t)===B5(e)),[a]),c=(0,X.useCallback)(async e=>{let t=crypto.randomUUID();await o(n=>n.some(t=>B5(t)===B5(e))?n:[...n,{id:t,...e}])},[o]),l=(0,X.useCallback)(async e=>{await o(t=>t.filter(t=>t.id!==e))},[o]),u=(0,X.useCallback)(async(e,t)=>{await o(n=>n.map(n=>n.id===e?{...n,minimized:t}:n))},[o]),d=(0,X.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,X.useMemo)(()=>({pins:a,isLoading:r,isPinned:s,pin:c,unpin:l,movePin:d,setMinimized:u}),[a,r,s,c,l,d,u]);return(0,Z.jsx)(LC.Provider,{value:f,children:e})}var H5=(0,X.lazy)(()=>m(()=>import(`./NextShell-CjpKDJo8.js`),__vite__mapDeps([29,3,4,15,12,10,11,13,30])));function U5(){let{showToast:e}=Vr();return(0,X.useEffect)(()=>{Dr((t,n)=>{e({title:`Error`,description:n?`${t.message} (${n})`:t.message,variant:`destructive`})})},[e]),(0,X.useEffect)(()=>g4(),[]),(0,Z.jsxs)(xu,{children:[(0,Z.jsx)(l4,{}),(0,Z.jsx)(Yx,{}),(0,Z.jsxs)(Fl,{children:[(0,Z.jsx)(Nl,{path:`/login`,element:(0,Z.jsx)(Cd,{children:(0,Z.jsx)(vd,{})})}),(0,Z.jsx)(Nl,{path:`/register`,element:(0,Z.jsx)(Cd,{children:(0,Z.jsx)(yd,{})})}),(0,Z.jsx)(Nl,{path:`/auth/google/callback`,element:(0,Z.jsx)(Cd,{children:(0,Z.jsx)(bd,{})})}),(0,Z.jsx)(Nl,{path:`/pub/c/:code`,element:(0,Z.jsx)(Rb,{})}),(0,Z.jsx)(Nl,{path:`/apps/:appletId`,element:(0,Z.jsx)(Sd,{children:(0,Z.jsx)(Rx,{})})}),(0,Z.jsx)(Nl,{path:`/next/*`,element:(0,Z.jsx)(Sd,{children:(0,Z.jsx)(X.Suspense,{fallback:null,children:(0,Z.jsx)(H5,{})})})}),(0,Z.jsx)(Nl,{path:`/`,element:(0,Z.jsx)(Sd,{children:(0,Z.jsx)(z5,{children:(0,Z.jsx)(V5,{children:(0,Z.jsx)(D5,{})})})}),children:i4}),(0,Z.jsx)(Nl,{path:`*`,element:(0,Z.jsx)(jl,{to:`/`,replace:!0})})]})]})}function W5(){return(0,Z.jsx)(KD,{children:(0,Z.jsx)(I5,{children:(0,Z.jsx)(U5,{})})})}uD(),nD(),(0,Ns.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(X.StrictMode,{children:(0,Z.jsx)(W5,{})}));
|
|
97
|
+
`);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=K8(t),i=QT(t)||l;u=$T(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,X.useCallback)(async t=>{if(!(r||!e)){o(null),i(!0),n(e=>[...e,{role:`user`,content:`🎤 Transcribing…`,isComplete:!1}]);try{let r=await AE(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,X.useCallback)(()=>{s.current?.abort(),i(!1)},[]),clear:(0,X.useCallback)(()=>{n([]),o(null)},[])}}function J8(){let[e,t]=(0,X.useState)(!1),[n,r]=(0,X.useState)(null),i=(0,X.useRef)(null),a=(0,X.useRef)([]);return{isRecording:e,recorderError:n,start:(0,X.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,X.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,X.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 Y8({agentId:e,onClose:t}){let[n,r]=(0,X.useState)(null),[i,a]=(0,X.useState)(``),[o,s]=(0,X.useState)(!1),[c,l]=(0,X.useState)(null),[u,d]=(0,X.useState)(!1),[f,p]=(0,X.useState)(null),{showToast:m}=Vr(),h=Uo(),g=h?.state.activeContextType===`context`?h.state.activeContextId:null,_=h?.state.activeContextPath??null,v=(0,X.useRef)(null),y=(0,X.useRef)(null),{messages:b,isStreaming:x,error:S,send:C,sendVoice:w,stop:T,clear:E}=q8(e),{isRecording:D,recorderError:O,start:k,stop:A}=J8();(0,X.useEffect)(()=>{uE(e).then(r).catch(()=>{}),iE(e).then(l).catch(()=>l(null))},[e]),(0,X.useEffect)(()=>{kE().then(e=>s(!!(e.enabled&&e.stt))).catch(()=>s(!1))},[]),(0,X.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 aE(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,Z.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,Z.jsxs)(`div`,{className:`flex items-center gap-2 px-3 h-12 border-b border-border shrink-0`,children:[(0,Z.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,Z.jsx)(Bt,{className:`w-4 h-4`})}),n?.color&&(0,Z.jsx)(`span`,{className:`w-2.5 h-2.5 rounded-full shrink-0`,style:{backgroundColor:n.color}}),(0,Z.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Z.jsx)(`div`,{className:`text-sm font-medium truncate`,children:n?.label||n?.name||e}),(0,Z.jsx)(`div`,{className:`text-[10px] leading-tight text-muted-foreground truncate`,title:M,children:M})]}),(0,Z.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,Z.jsx)(lt,{className:`w-3.5 h-3.5`})})]}),g&&!j&&(0,Z.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,Z.jsxs)(`span`,{className:`flex-1 truncate text-muted-foreground`,title:g||_||void 0,children:[`Toolbox context: `,g||_]}),(0,Z.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,Z.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,Z.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,children:`Token (shown once):`}),(0,Z.jsx)(`code`,{className:`flex-1 truncate font-mono`,children:f}),(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:()=>p(null),className:`shrink-0 rounded px-1.5 py-1 hover:bg-accent`,title:`Dismiss`,children:`×`})]}),(0,Z.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-4 py-3 space-y-3`,children:[b.length===0&&(0,Z.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,Z.jsxs)(`div`,{className:K(`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,Z.jsx)(AA,{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,Z.jsx)(dh,{content:e.content||(e.isComplete?``:`…`)}):(0,Z.jsx)(`span`,{className:`whitespace-pre-wrap`,children:e.content})]},t)),(S||O)&&(0,Z.jsx)(`div`,{className:`text-xs text-destructive text-center py-1`,children:S||O}),(0,Z.jsx)(`div`,{ref:v})]}),(0,Z.jsx)(`div`,{className:`p-3 border-t border-border shrink-0`,children:(0,Z.jsxs)(`div`,{className:`flex gap-2 items-end`,children:[(0,Z.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,Z.jsx)(`button`,{type:`button`,onClick:async()=>{if(D){let e=await A();e&&await w(e)}else x||await k()},disabled:x&&!D,className:K(`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,Z.jsx)(nn,{className:`w-4 h-4`}):(0,Z.jsx)(ft,{className:`w-4 h-4`})}),x?(0,Z.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,Z.jsx)(nn,{className:`w-4 h-4`})}):(0,Z.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,Z.jsx)(tr,{className:`w-4 h-4`})})]})})]})}function X8(){let{state:e,openApplet:t}=Os(),[n,r]=(0,X.useState)(`context`),i=e.appsAppletId,a=i?Nx.find(e=>e.id===i):null;if(a)return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2 border-b border-border px-2 py-1.5`,children:[(0,Z.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,Z.jsx)(Bt,{className:`h-4 w-4`})}),(0,Z.jsx)(a.icon,{className:`h-4 w-4 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-sm font-medium`,children:a.label})]}),(0,Z.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Z.jsx)(a.Component,{})})]});let o=Px(n);return(0,Z.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,Z.jsx)(`div`,{className:`flex shrink-0 border-b border-border`,children:[`context`,`global`].map(e=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>r(e),className:K(`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,Z.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3`,children:[!o.length&&(0,Z.jsxs)(`p`,{className:`py-10 text-center text-sm text-muted-foreground`,children:[`No `,n,` applets yet.`]}),(0,Z.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:o.map(e=>(0,Z.jsxs)(`button`,{type:`button`,onClick:()=>t(e.id),className:`flex min-h-[4.5rem] flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-muted/40 p-3 text-foreground transition-colors hover:bg-muted`,title:e.description,children:[(0,Z.jsx)(e.icon,{className:`h-5 w-5 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`text-xs font-medium leading-none`,children:e.label})]},e.id))})]})]})}var Z8=[{view:`apps`,icon:dr,label:`Apps`},{view:`tools`,icon:kt,label:`Filters`},{view:`agents`,icon:dt,label:`Agents`},{view:`notifications`,icon:$t,label:`Notifications`}],Q8=420,$8=340,e5=`toolbox:width`,t5=360,n5=48,r5=e=>{let t=typeof window<`u`?window.innerWidth:1600,n=Math.max($8,Math.min(Math.round(t*.7),t-n5-t5));return Math.max($8,Math.min(e,n))},i5=()=>typeof window<`u`?Math.round(window.innerWidth/2):720;function a5(){let{state:e,setView:t,closeT1:n,closeT2:r}=Os();Ff(n,e.t1Open&&!e.t2Open),Ff(r,e.t2Open);let{t1Open:i,t1View:a,t2Open:o,t2AgentId:s,activeAccentColor:c}=e,l=Ym(),[u,d]=(0,X.useState)(()=>{let e=typeof window<`u`?Number(localStorage.getItem(e5)):NaN;return Number.isFinite(e)&&e>0?e:Q8}),f=(0,X.useCallback)(e=>{d(e);try{localStorage.setItem(e5,String(e))}catch{}},[]),p=(0,X.useRef)(null),m=(0,X.useCallback)(e=>{e.preventDefault(),p.current={startX:e.clientX,startWidth:u};let t=e=>{if(!p.current)return;let t=r5(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(e5,String(e))}catch{}return e})};window.addEventListener(`mousemove`,t),window.addEventListener(`mouseup`,n)},[u]),h=u>=i5()*.9;return(0,X.useEffect)(()=>{let e=()=>d(e=>r5(e));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),!i||!a?null:(0,Z.jsxs)(Z.Fragment,{children:[l&&(0,Z.jsx)(`div`,{className:`fixed inset-0 z-panel-scrim bg-scrim animate-fade-in`,onClick:n,"aria-hidden":!0}),(0,Z.jsxs)(`div`,{style:l?void 0:{width:u},className:K(`flex flex-col overflow-hidden border bg-card surface-glass text-foreground`,l?`fixed bottom-2 left-2 right-2 top-2 z-panel rounded-2xl shadow-elevation-5 animate-fade-in`:`relative shrink-0 rounded-[var(--panel-radius)] shadow-elevation-3`),children:[!l&&(0,Z.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,Z.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-1 border-b-[3px] px-2`,style:c?{borderBottomColor:c}:void 0,children:[(0,Z.jsx)(`div`,{className:`flex items-center gap-1`,children:Z8.map(({view:e,icon:n,label:r})=>(0,Z.jsx)(`button`,{type:`button`,onClick:()=>t(e),"aria-label":r,title:r,className:K(`flex h-8 w-8 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,Z.jsx)(n,{className:`h-4 w-4 shrink-0`})},e))}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-0.5`,children:[!l&&(0,Z.jsx)(`button`,{type:`button`,onClick:()=>f(h?Q8:r5(i5())),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,Z.jsx)(it,{className:`h-4 w-4`}):(0,Z.jsx)(Fn,{className:`h-4 w-4`})}),(0,Z.jsx)(`button`,{type:`button`,onClick:n,className:`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground touch-target`,"aria-label":`Close toolbox`,children:(0,Z.jsx)(Me,{className:`h-4 w-4`})})]})]}),(0,Z.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 flex-col`,children:[(0,Z.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col ${o&&s?`invisible`:``}`,children:[a===`home`&&(0,Z.jsx)(U6,{}),a===`apps`&&(0,Z.jsx)(X8,{}),a===`tools`&&(0,Z.jsx)(H8,{}),a===`agents`&&(0,Z.jsx)(W8,{}),a===`notifications`&&(0,Z.jsx)(G8,{})]}),o&&s&&(0,Z.jsx)(`div`,{className:`absolute inset-0 z-10 flex flex-col bg-background`,children:(0,Z.jsx)(Y8,{agentId:s,onClose:r})})]})]})]})}function o5(){let{running:e,hasViewer:t,paused:n,snapshot:r,source:i,lastCount:a,error:o,setPaused:s,stop:c,reopen:l}=ix();if(!e||t)return null;let u=i===`screen`?fe:i===`photo`?y:z;return(0,Z.jsxs)(`div`,{className:K(`fixed right-4 w-56 overflow-hidden rounded-xl 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,Z.jsxs)(`button`,{type:`button`,onClick:l,title:`Back to Lens`,className:`relative block w-full cursor-pointer bg-black/80 aspect-video`,children:[(0,Z.jsx)(vx,{className:`h-full w-full`}),r&&(0,Z.jsx)(`img`,{src:r,alt:``,className:`absolute inset-0 h-full w-full bg-black object-contain`}),n&&(0,Z.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white`,children:`paused`})]}),(0,Z.jsxs)(`div`,{className:`flex items-center gap-1 px-2 py-1.5`,children:[(0,Z.jsx)(u,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Z.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-muted-foreground`,children:o?(0,Z.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,Z.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,Z.jsx)(De,{className:`h-3.5 w-3.5`}):(0,Z.jsx)(Xe,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(Fn,{className:`h-3.5 w-3.5`})}),(0,Z.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,Z.jsx)(Se,{className:`h-3.5 w-3.5`})})]})]})}function s5({children:e}){let[t,n]=(0,X.useState)(null),r={entry:t,open:(e,t)=>n({document:e,workspaceId:t}),close:()=>n(null)};return(0,Z.jsx)(pm.Provider,{value:r,children:e})}var c5={key:`desk`,label:`Desk`,main:`/`,mainExpanded:!1,entries:[]},l5=0,u5=()=>`c${++l5}`;function d5(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 f5({children:e}){let t=nl(),n=al(),[r,i]=(0,X.useState)([c5]),[a,o]=(0,X.useState)(0),[s,c]=(0,X.useState)(a_),l=(0,X.useRef)(r),u=(0,X.useRef)(a),d=(0,X.useRef)(s);(0,X.useEffect)(()=>{l.current=r,u.current=a,d.current=s},[r,a,s]);let f=(0,X.useCallback)((e,t)=>{let n=l.current.slice();n[e]=t,l.current=n,i(n)},[]),p=(0,X.useCallback)(e=>{let t=u.current,n=l.current[t];n&&f(t,e(n))},[f]),m=t.pathname+t.search;(0,X.useEffect)(()=>{p(e=>e.main===m?e:{...e,main:m})},[m,p]);let h=(0,X.useCallback)(e=>{let t=l.current[u.current];if(!t)return;let n=t.entries.find(t=>d5(e,t));if(n){c(n.id);return}let r={...e,id:u5()},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,X.useCallback)((e,t)=>{h({kind:`document`,document:e,workspaceId:t})},[h]),_=(0,X.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,X.useCallback)(e=>{p(t=>({...t,entries:t.entries.filter(t=>t.id!==e)})),c(t=>t===e?a_:t)},[p]),y=(0,X.useCallback)((e,t)=>{p(n=>({...n,entries:n.entries.map(n=>n.id===e&&n.kind===`route`?{...n,location:t}:n)}))},[p]),b=(0,X.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,X.useCallback)(e=>{let t=l.current[e];t&&(u.current=e,o(e),c(a_),n(t.main))},[n]),S=(0,X.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,X.useCallback)(e=>{x(u.current+e)},[x]),w=(0,X.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,X.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,X.useMemo)(()=>({entry:null,open:g,preview:_,close:()=>{}}),[g,_]);return(0,Z.jsx)(o_.Provider,{value:T,children:(0,Z.jsx)(pm.Provider,{value:E,children:e})})}function p5(e){return Ks(typeof e==`string`?qs(e):e)}function m5({location:e,onNavigate:t}){let n=(0,X.useMemo)(()=>{let t=qs(e);return{pathname:t.pathname||`/`,search:t.search||``,hash:t.hash||``,state:null,key:e}},[e]),r=(0,X.useMemo)(()=>({basename:`/`,static:!1,useTransitions:void 0,future:{},navigator:{createHref:p5,go:()=>{},push:e=>t(p5(e)),replace:e=>t(p5(e))}}),[t]);return(0,Z.jsx)(Gc.Provider,{value:r,children:(0,Z.jsx)(Kc.Provider,{value:{location:n,navigationType:Ls.Push},children:(0,Z.jsx)(qc.Provider,{value:{outlet:null,matches:[],isDataRoute:!1},children:(0,Z.jsx)(Fl,{children:i4})})})})}var h5=`input, textarea, select, [contenteditable=""], [contenteditable="true"]`,g5=420,_5=e=>e<=0?0:e>=1?1:e<.5?2**(20*e-10)/2:(2-2**(-20*e+10))/2;function v5(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)/g5);e.scrollLeft=r+i*_5(l),l<1?s=requestAnimationFrame(c):(e.style.scrollSnapType=a,n?.())};return s=requestAnimationFrame(c),()=>{cancelAnimationFrame(s),e.style.scrollSnapType=a}}function y5(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 b5({section:e}){return e===`contexts`?(0,Z.jsx)(j4,{}):e===`workspaces`?(0,Z.jsx)(Y4,{}):e===`agents`?(0,Z.jsx)(C3,{}):e===`admin`||e===`settings`?(0,Z.jsx)(k3,{}):null}function x5(e,t){if(e?.kind===`document`)return Ui(e.document).title;let n=(e?.kind===`route`?e.location:t).split(/[?#]/)[0];if(n===`/settings`)return`Settings`;let r=hS.flatMap(e=>[...e.items]).find(e=>e.path===n);if(r)return r.label;let i=n.split(`/`).filter(Boolean);return i.length===0?`Desk`:decodeURIComponent(i[i.length-1])}function S5({id:e,title:t,expanded:n,focused:r,onFocus:i,onToggleExpanded:a,onClose:o,badge:s,contentHeader:c,children:l}){let u=U3();return(0,Z.jsxs)(`section`,{"data-reader-pane":c?!0:void 0,style:c&&!n&&u?{"--reader-width":`${u}px`,transition:`none`}:void 0,"data-strip-col":e,className:K(`strip-canvas surface-sheet relative`,n&&`strip-canvas--wide`,r&&`strip-canvas--focused`),onPointerDownCapture:()=>i(e),"aria-label":t,children:[c&&!n&&(0,Z.jsx)(K3,{edge:`right`}),!c&&(0,Z.jsxs)(`header`,{className:`strip-canvas-bar`,children:[s&&(0,Z.jsx)(`span`,{className:`strip-row-label`,children:s}),(0,Z.jsx)(`span`,{className:`strip-canvas-title`,title:t,children:t}),(0,Z.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,Z.jsx)(it,{className:`size-3.5`}):(0,Z.jsx)(Fn,{className:`size-3.5`})}),o&&(0,Z.jsx)(`button`,{type:`button`,className:`strip-canvas-btn`,title:s?`Close row`:`Close canvas`,onClick:()=>o(e),children:(0,Z.jsx)(Me,{className:`size-3.5`})})]}),(0,Z.jsx)(`div`,{className:`strip-canvas-body`,children:l})]})}function C5(e){return K(`relative flex-1 min-h-0 min-w-0 overflow-auto`,!X3(e)&&!Y3(e)&&`p-page`)}function w5({row:e,pathname:t,rowLabel:n,onCloseRow:r}){let{focus:i,setFocus:a,toggleExpanded:o,closeCanvas:s,navigateCanvas:c}=s_(),l=(0,X.useCallback)(e=>t=>c(e,t),[c]);return(0,Z.jsxs)(Z.Fragment,{children:[t===`/`?(0,Z.jsx)(`div`,{hidden:!0,children:(0,Z.jsx)(Ml,{})}):(0,Z.jsx)(S5,{id:a_,title:x5(null,t),expanded:e.mainExpanded,focused:i===a_,onFocus:a,onToggleExpanded:o,badge:n,onClose:r,children:(0,Z.jsx)(`main`,{id:`content-area`,className:C5(t),children:(0,Z.jsx)(Ml,{})})}),e.entries.map(e=>(0,Z.jsx)(S5,{id:e.id,title:x5(e,t),expanded:!!e.expanded,focused:i===e.id,onFocus:a,onToggleExpanded:o,contentHeader:e.kind===`document`,onClose:s,children:e.kind===`route`?(0,Z.jsx)(`div`,{className:C5(e.location.split(`?`)[0]),children:(0,Z.jsx)(m5,{location:e.location,onNavigate:l(e.id)})}):(0,Z.jsx)(`div`,{className:`flex flex-1 min-h-0 min-w-0 items-stretch`,children:(0,Z.jsx)(J3,{entry:e,onClose:()=>s(e.id),frame:{expanded:!!e.expanded,onToggleExpanded:()=>o(e.id)}})})},e.id))]})}function T5({row:e}){return(0,Z.jsxs)(`div`,{className:`strip-ghost-row`,"aria-hidden":!0,children:[(0,Z.jsx)(`span`,{className:`strip-ghost-chip strip-ghost-chip--main`,children:x5(null,e.main)}),e.entries.map(t=>(0,Z.jsx)(`span`,{className:`strip-ghost-chip`,children:x5(t,e.main)},t.id))]})}function E5(){let{state:e,closeM1:t,closeM2:n}=zS(),{rows:r,activeRow:i,focus:a,setFocus:o,moveRow:s,closeRow:c}=s_(),{pathname:l}=nl(),u=IS(),d=(0,X.useRef)(null);Ff(t,e.m1Open&&!e.m2Open),Ff(n,e.m2Open),(0,X.useLayoutEffect)(()=>{let e=d.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 f=(0,X.useRef)(e.m1Open);(0,X.useEffect)(()=>{e.m1Open&&!f.current&&!e.m2Open&&o(`m1`),f.current=e.m1Open},[e.m1Open,e.m2Open,o]);let p=(0,X.useRef)(e.m2Open);(0,X.useEffect)(()=>{e.m2Open&&!p.current&&o(`m2`),!e.m2Open&&p.current&&a===`m2`&&o(e.m1Open?`m1`:a_),p.current=e.m2Open},[e.m2Open,e.m1Open,a,o]),(0,X.useEffect)(()=>{!e.m1Open&&a===`m1`&&o(a_)},[e.m1Open,a,o]),(0,X.useEffect)(()=>{let e=d.current,t=e?.querySelector(`[data-strip-col="${CSS.escape(a)}"]`);if(!(!e||!t))return v5(e,y5(e,t))},[a,r,i,e.m1Open,e.m2Open]);let m=(0,X.useCallback)(()=>{let t=r[i];return[...e.m1Open?[`m1`]:[],...e.m2Open?[`m2`]:[],...l===`/`?[]:[a_],...t?t.entries.map(e=>e.id):[]]},[r,i,e.m1Open,e.m2Open,l]);return(0,X.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||!e.key.startsWith(`Arrow`)||!LS(e,u))return;let t=e.target;if(!(t?.closest(h5)||t?.closest(`[role="dialog"]`))){if(e.key===`ArrowLeft`||e.key===`ArrowRight`){let t=m(),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)},[m,a,o,s,r.length,u]),(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`div`,{className:`strip-shell flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(k4,{}),(0,Z.jsxs)(`div`,{ref:d,className:`strip-scroller`,children:[e.m1Open&&(0,Z.jsx)(`div`,{"data-strip-col":`m1`,className:K(`strip-col strip-menu-col`,a===`m1`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m1`),children:(0,Z.jsx)(b5,{section:e.activeSection})}),e.m2Open&&(0,Z.jsx)(`div`,{"data-strip-col":`m2`,className:K(`strip-col strip-menu-col`,a===`m2`&&`strip-col--focused`),onPointerDownCapture:()=>o(`m2`),children:(0,Z.jsx)(N3,{})}),(0,Z.jsx)(`div`,{className:`strip-rows`,style:{transform:`translateY(${-i*100}%)`},children:r.map((e,t)=>(0,Z.jsx)(`div`,{className:K(`strip-row`,t===i&&`strip-row--active`),children:(0,Z.jsx)(`div`,{className:`strip-row-canvases`,children:t===i?(0,Z.jsx)(w5,{row:e,pathname:l,rowLabel:r.length>1?e.label:void 0,onCloseRow:t>0?()=>c(e.key):void 0}):(0,Z.jsx)(T5,{row:e})})},e.key))})]}),(0,Z.jsx)(B6,{}),(0,Z.jsx)(a5,{})]}),(0,Z.jsx)(e6,{}),(0,Z.jsx)(O4,{}),(0,Z.jsx)(o5,{})]})}function D5(){let e=DS();return(0,Z.jsx)(f4,{children:(0,Z.jsx)(r6,{children:(0,Z.jsx)(_6,{children:(0,Z.jsx)(yx,{children:(0,Z.jsx)(s5,{children:e===`strip`?(0,Z.jsx)(f5,{children:(0,Z.jsx)(Ix,{children:(0,Z.jsx)(E5,{})})}):(0,Z.jsxs)(Ix,{children:[(0,Z.jsxs)(`div`,{className:`flex h-viewport w-full overflow-hidden surface-desk gap-shell p-shell`,children:[(0,Z.jsx)(k4,{}),(0,Z.jsx)(P3,{}),(0,Z.jsx)($3,{}),(0,Z.jsx)(B6,{}),(0,Z.jsx)(a5,{})]}),(0,Z.jsx)(e6,{}),(0,Z.jsx)(O4,{}),(0,Z.jsx)(o5,{})]})})})})})})}var O5=En,k5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Ut,{ref:n,className:K(`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}));k5.displayName=Ut.displayName;var A5=vr(`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 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`}}),j5=X.forwardRef(({className:e,variant:t,...n},r)=>(0,Z.jsx)(mn,{ref:r,className:K(A5({variant:t}),e),...n}));j5.displayName=mn.displayName;var M5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Kn,{ref:n,className:K(`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}));M5.displayName=Kn.displayName;var N5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(At,{ref:n,className:K(`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,Z.jsx)(Me,{className:`h-4 w-4`})}));N5.displayName=At.displayName;var P5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(Jt,{ref:n,className:K(`text-sm font-semibold`,e),...t}));P5.displayName=Jt.displayName;var F5=X.forwardRef(({className:e,...t},n)=>(0,Z.jsx)(zt,{ref:n,className:K(`text-sm opacity-90`,e),...t}));F5.displayName=zt.displayName;function I5({children:e}){let[t,n]=(0,X.useState)([]),r=(0,X.useRef)(new Set),i=(0,X.useCallback)(e=>{if(Tr(e.description)||Tr(e.title))return;let t=`${e.title}:${e.description??``}`;if(r.current.has(t))return;r.current.add(t);let i=Math.random().toString(36).substring(2,9);n(t=>[...t,{...e,id:i}]),setTimeout(()=>{n(e=>e.filter(e=>e.id!==i)),r.current.delete(t)},5e3)},[]),a=(0,X.useCallback)(e=>{let t=Math.random().toString(36).substring(2,9);n(n=>[...n,{...e,id:t,busy:!0}]);let r=!1,a=e=>{r||(r=!0,n(e=>e.filter(e=>e.id!==t)),e&&i(e))};return{done:a,fail:a}},[i]),o=(0,X.useMemo)(()=>({showToast:i,showProgress:a}),[i,a]);return(0,Z.jsx)(Gr.Provider,{value:o,children:(0,Z.jsxs)(O5,{children:[e,t.map(e=>(0,Z.jsxs)(j5,{variant:e.variant,duration:e.busy?1/0:void 0,children:[(0,Z.jsxs)(`div`,{className:`grid gap-1`,children:[(0,Z.jsxs)(P5,{className:`flex items-center gap-2`,children:[e.busy&&(0,Z.jsx)(Mt,{className:`h-3.5 w-3.5 shrink-0 animate-spin`}),e.title]}),e.description!=null&&(0,Z.jsx)(F5,{children:e.description})]}),!e.busy&&(0,Z.jsx)(N5,{})]},e.id)),(0,Z.jsx)(k5,{})]})})}async function L5(){return await J.get(`/messaging/notifications`,{noAuthRedirect:!0})||[]}async function R5(){await J.delete(`/messaging/notifications`,{noAuthRedirect:!0})}function z5({children:e}){let[t,n]=(0,X.useState)([]),{showToast:r}=Vr();(0,X.useEffect)(()=>{let e=!1;L5().then(t=>{e||n(t)}).catch(()=>{});let t=id.on(`notification`,e=>{let t=e;!t?.id||!t?.text||(n(e=>e.some(e=>e.id===t.id)?e:[...e,t].slice(-50)),r({title:`Notification`,description:t.text}))});return()=>{e=!0,t?.()}},[r]);let i=(0,X.useCallback)(async()=>{n([]),await R5().catch(()=>{})},[]);return(0,Z.jsx)(V6.Provider,{value:{notifications:t,clear:i},children:e})}var B5=e=>`${e.workspaceName}\0${e.treeName}\0${e.path}`;function V5({children:e}){let[t,n]=(0,X.useState)(null),[r,i]=(0,X.useState)(!0);(0,X.useEffect)(()=>{let e=!1;return e3().then(t=>{e||n(t)}).catch(()=>{e||n({})}).finally(()=>{e||i(!1)}),()=>{e=!0}},[]);let a=(0,X.useMemo)(()=>t?.home?.pinnedCanvases??[],[t]),[o]=(0,X.useState)(()=>fT(e3,t3,n)),s=(0,X.useCallback)(e=>a.some(t=>B5(t)===B5(e)),[a]),c=(0,X.useCallback)(async e=>{let t=crypto.randomUUID();await o(n=>n.some(t=>B5(t)===B5(e))?n:[...n,{id:t,...e}])},[o]),l=(0,X.useCallback)(async e=>{await o(t=>t.filter(t=>t.id!==e))},[o]),u=(0,X.useCallback)(async(e,t)=>{await o(n=>n.map(n=>n.id===e?{...n,minimized:t}:n))},[o]),d=(0,X.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,X.useMemo)(()=>({pins:a,isLoading:r,isPinned:s,pin:c,unpin:l,movePin:d,setMinimized:u}),[a,r,s,c,l,d,u]);return(0,Z.jsx)(LC.Provider,{value:f,children:e})}var H5=(0,X.lazy)(()=>m(()=>import(`./NextShell-CichxWps.js`),__vite__mapDeps([29,3,4,15,12,10,11,13,30])));function U5(){let{showToast:e}=Vr();return(0,X.useEffect)(()=>{Dr((t,n)=>{e({title:`Error`,description:n?`${t.message} (${n})`:t.message,variant:`destructive`})})},[e]),(0,X.useEffect)(()=>g4(),[]),(0,Z.jsxs)(xu,{children:[(0,Z.jsx)(l4,{}),(0,Z.jsx)(Yx,{}),(0,Z.jsxs)(Fl,{children:[(0,Z.jsx)(Nl,{path:`/login`,element:(0,Z.jsx)(Cd,{children:(0,Z.jsx)(vd,{})})}),(0,Z.jsx)(Nl,{path:`/register`,element:(0,Z.jsx)(Cd,{children:(0,Z.jsx)(yd,{})})}),(0,Z.jsx)(Nl,{path:`/auth/google/callback`,element:(0,Z.jsx)(Cd,{children:(0,Z.jsx)(bd,{})})}),(0,Z.jsx)(Nl,{path:`/pub/c/:code`,element:(0,Z.jsx)(Rb,{})}),(0,Z.jsx)(Nl,{path:`/apps/:appletId`,element:(0,Z.jsx)(Sd,{children:(0,Z.jsx)(Rx,{})})}),(0,Z.jsx)(Nl,{path:`/next/*`,element:(0,Z.jsx)(Sd,{children:(0,Z.jsx)(X.Suspense,{fallback:null,children:(0,Z.jsx)(H5,{})})})}),(0,Z.jsx)(Nl,{path:`/`,element:(0,Z.jsx)(Sd,{children:(0,Z.jsx)(z5,{children:(0,Z.jsx)(V5,{children:(0,Z.jsx)(D5,{})})})}),children:i4}),(0,Z.jsx)(Nl,{path:`*`,element:(0,Z.jsx)(jl,{to:`/`,replace:!0})})]})]})}function W5(){return(0,Z.jsx)(KD,{children:(0,Z.jsx)(I5,{children:(0,Z.jsx)(U5,{})})})}uD(),nD(),(0,Ns.createRoot)(document.getElementById(`root`)).render((0,Z.jsx)(X.StrictMode,{children:(0,Z.jsx)(W5,{})}));
|