@augmentd-labs/canvas-web 2.26.9 → 2.26.10

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.
@@ -0,0 +1,19 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdf-Ciz5_WNq.js","assets/preload-helper-Czpn1I53.js","assets/markdown-html-XoABNf32.js","assets/rolldown-runtime-C0FnF6B9.js","assets/code-editor-BQnKd3jw.js","assets/sanitize-DrVcFY1Q.js","assets/markdown-it-DRESbtwK.js","assets/punycode.es6-ZbLrB_Dn.js","assets/markdown-html-DtQ7-esK.css","assets/SketchEditor-CRJF-Jp4.js","assets/react-BzqgEMSQ.js","assets/ui-NWo4bzrd.js","assets/utils-BxVxyehK.js","assets/alert-dialog-CDKOX-MP.js","assets/utils-2pl1SbIp.js","assets/blobs-B3DY8Rsp.js","assets/workspace-BYMC2sfI.js","assets/useAddTarget-Bprwjjdn.js","assets/sha256-65KIjGvZ.js","assets/chunk-K2UTITRG-zQFDOW3Q.js","assets/chunk-SRAX5OIU-Dhm3gOdh.js","assets/chunk-6U3AYISY-C6-Mtja1.js","assets/chunk-Z3N5DIM6-D9TMVU7m.js","assets/EditorOverlay-DqlaCJe7.js","assets/SketchEditor-DtRVLazd.css","assets/TextDocumentEditor-BKueFXia.js","assets/text-documents-D4tmVh-7.js","assets/LocationTab-BONJQfYM.js","assets/map-BxCwdK0d.js","assets/map-BcsP_QXj.css","assets/subtree-transfer-dialog-CSjPDp4d.js"])))=>i.map(i=>d[i]);
2
+ import{o as e,r as t}from"./rolldown-runtime-C0FnF6B9.js";import{l as n,u as r}from"./code-editor-BQnKd3jw.js";import{_t as i,vt as a,yt as o}from"./react-BzqgEMSQ.js";import{t as s}from"./preload-helper-Czpn1I53.js";import{$ as c,Br as l,Cr as u,Ct as d,En as f,Er as p,Et as m,Ft as h,Gn as g,Gr as _,Gt as v,Hn as y,Hr as b,Ir as x,It as S,J as C,Jr as w,Kr as T,L as E,Ln as D,Lr as O,Lt as k,Mr as A,Nt as j,Or as ee,Pt as M,Q as N,Qr as P,Rn as F,Rr as I,Rt as L,Sr as te,St as ne,Tr as re,Tt as ie,U as ae,Un as oe,Ut as R,Vn as se,Vr as ce,Vt as le,W as ue,Wn as de,Wr as z,Wt as fe,X as pe,Xn as me,Xr as he,Y as ge,Yn as _e,Yt as ve,Z as ye,Zt as be,_i as xe,ai as B,an as Se,at as Ce,bt as we,ci as Te,cr as Ee,di as De,er as Oe,fi as ke,fr as Ae,gn as je,gr as Me,hn as Ne,hr as Pe,ht as V,ii as Fe,in as Ie,ir as Le,jn as Re,jt as ze,kn as Be,li as Ve,ln as He,lr as Ue,mn as We,mr as Ge,ni as Ke,nn as qe,nr as Je,nt as Ye,or as Xe,ot as Ze,pt as Qe,qn as $e,qr as et,qt as tt,rn as nt,rr as rt,rt as it,sr as at,st as ot,tr as st,tt as ct,ui as lt,un as ut,ur as dt,vn as ft,vr as pt,vt as mt,wt as ht,xr as gt,yr as _t,zr as vt,zt as yt}from"./ui-NWo4bzrd.js";import{t as H}from"./utils-2pl1SbIp.js";import{_ as bt,b as U,u as W,v as xt,x as G,y as St}from"./alert-dialog-CDKOX-MP.js";import{t as Ct}from"./socket-hM4c-ZSl.js";import{l as wt,s as Tt}from"./blobs-B3DY8Rsp.js";import{$ as Et,$t as Dt,A as Ot,At as kt,En as At,Fn as jt,Ft as Mt,Gn as Nt,Ht as Pt,In as Ft,It,J as Lt,Jn as Rt,Jt as zt,K as Bt,Kn as Vt,Lt as Ht,On as K,Ot as Ut,P as Wt,Pn as Gt,Pt as Kt,Rn as qt,Tt as Jt,Un as Yt,Vn as Xt,Vt as Zt,W as Qt,X as $t,Y as en,Yt as tn,a as nn,bn as rn,bt as an,c as on,d as sn,dt as cn,en as q,g as ln,gt as un,h as dn,hn as fn,ht as pn,it as mn,jn as hn,jt as gn,k as _n,kn as vn,l as yn,mn as bn,nt as xn,pn as Sn,q as Cn,qn as wn,r as Tn,s as En,t as Dn,u as On,v as kn,vn as An,wn as jn,xn as Mn,yn as Nn,zt as Pn}from"./workspace-BYMC2sfI.js";import{a as Fn,c as In,d as Ln,f as Rn,h as zn,i as Bn,m as Vn,n as Hn,o as Un,p as Wn,r as Gn,s as Kn,t as qn,v as Jn,y as Yn}from"./text-documents-D4tmVh-7.js";import{A as Xn,C as Zn,E as Qn,M as $n,R as er,S as tr,k as nr,l as rr,o as ir,v as ar,x as or}from"./useAddTarget-Bprwjjdn.js";import{t as sr}from"./sanitize-DrVcFY1Q.js";import{t as cr}from"./markdown-it-DRESbtwK.js";import{n as lr}from"./map-BxCwdK0d.js";import{t as ur}from"./search-COMZIxA7.js";var J=e(r(),1),dr=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,fr=/^[\\/]{2}/;function pr(e,t){return t+e.replace(/\\/g,`/`)}var mr=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(mr||{}),hr=`popstate`;function gr(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function _r(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return xr(``,{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:Sr(t)}return wr(t,n,null,e)}function Y(e,t){if(e===!1||e==null)throw Error(t)}function vr(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function yr(){return Math.random().toString(36).substring(2,10)}function br(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 xr(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?Cr(t):t,state:n,key:t&&t.key||r||yr(),mask:i}}function Sr({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 Cr(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 wr(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=gr(e)?e:xr(h.location,e,t);n&&n(r,e),l=u()+1;let d=br(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=gr(e)?e:xr(h.location,e,t);n&&n(r,e),l=u();let i=br(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 Tr(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(hr,d),c=e,()=>{i.removeEventListener(hr,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 Tr(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),Y(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:Sr(t);return i=i.replace(/ $/,`%20`),!n&&fr.test(i)&&(i=r+i),new URL(i,r)}function Er(e,t,n=`/`){return Dr(e,t,n,!1)}function Dr(e,t,n,r,i){let a=Kr((typeof t==`string`?Cr(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Or(e),s=null,c=Gr(a);for(let e=0;s==null&&e<o.length;++e)s=Vr(o[e],c,r);return s}function Or(e){let t=kr(e);return jr(t),t}function kr(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;Y(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=ei([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(Y(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),kr(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:zr(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Wr(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 Ar(e.path))a(e,t,!0,n)}),t}function Ar(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=Ar(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 jr(e){e.sort((e,t)=>e.score===t.score?Br(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var Mr=/^:[\w-]+$/,Nr=3,Pr=2,Fr=1,Ir=10,Lr=-2,Rr=e=>e===`*`;function zr(e,t){let n=e.split(`/`),r=n.length;return n.some(Rr)&&(r+=Lr),t&&(r+=Pr),n.filter(e=>!Rr(e)).reduce((e,t)=>e+(Mr.test(t)?Nr:t===``?Fr:Ir),r)}function Br(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 Vr(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?Ur(u,l,s.matcher,s.compiledParams):Hr(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=Hr({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:ei([a,d.pathname]),pathnameBase:ni(ei([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=ei([a,d.pathnameBase]))}return o}function Hr(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Wr(e.path,e.caseSensitive,e.end);return Ur(e,t,n,r)}function Ur(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 Wr(e,t=!1,n=!0){vr(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 Gr(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return vr(!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 Kr(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 qr(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?Cr(e):e,a;return n?(n=$r(n),a=n.startsWith(`/`)?Jr(n.substring(1),`/`):Jr(n,t)):a=t,{pathname:a,search:ri(r),hash:ii(i)}}function Jr(e,t){let n=ti(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Yr(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 Xr(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Zr(e){let t=Xr(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function Qr(e,t,n,r=!1){let i;typeof e==`string`?i=Cr(e):(i={...e},Y(!i.pathname||!i.pathname.includes(`?`),Yr(`?`,`pathname`,`search`,i)),Y(!i.pathname||!i.pathname.includes(`#`),Yr(`#`,`pathname`,`hash`,i)),Y(!i.search||!i.search.includes(`#`),Yr(`#`,`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=qr(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var $r=e=>e.replace(/[\\/]{2,}/g,`/`),ei=e=>$r(e.join(`/`)),ti=e=>e.replace(/\/+$/,``),ni=e=>ti(e).replace(/^\/*/,`/`),ri=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,ii=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,ai=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 oi(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function si(e){return ei(e.map(e=>e.route.path).filter(Boolean))||`/`}var ci=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function li(e,t){let n=e;if(typeof n!=`string`||!dr.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(ci)try{let e=new URL(window.location.href),r=fr.test(n)?new URL(pr(n,e.protocol)):new URL(n),a=Kr(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{vr(!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 ui=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(ui);var di=[`GET`,...ui];new Set(di);var fi=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function pi(e){try{return fi.includes(new URL(e).protocol)}catch{return!1}}var mi=J.createContext(null);mi.displayName=`DataRouter`;var hi=J.createContext(null);hi.displayName=`DataRouterState`;var gi=J.createContext(!1);function _i(){return J.useContext(gi)}var vi=J.createContext({isTransitioning:!1});vi.displayName=`ViewTransition`;var yi=J.createContext(new Map);yi.displayName=`Fetchers`;var bi=J.createContext(null);bi.displayName=`Await`;var xi=J.createContext(null);xi.displayName=`Navigation`;var Si=J.createContext(null);Si.displayName=`Location`;var Ci=J.createContext({outlet:null,matches:[],isDataRoute:!1});Ci.displayName=`Route`;var wi=J.createContext(null);wi.displayName=`RouteError`;var Ti=`REACT_ROUTER_ERROR`,Ei=`REDIRECT`,Di=`ROUTE_ERROR_RESPONSE`;function Oi(e){if(e.startsWith(`${Ti}:${Ei}:{`))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 ki(e){if(e.startsWith(`${Ti}:${Di}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new ai(t.status,t.statusText,t.data)}catch{}}function Ai(e,{relative:t}={}){Y(ji(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=J.useContext(xi),{hash:i,pathname:a,search:o}=Bi(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:ei([n,a])),r.createHref({pathname:s,search:o,hash:i})}function ji(){return J.useContext(Si)!=null}function Mi(){return Y(ji(),`useLocation() may be used only in the context of a <Router> component.`),J.useContext(Si).location}var Ni=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Pi(e){J.useContext(xi).static||J.useLayoutEffect(e)}function Fi(){let{isDataRoute:e}=J.useContext(Ci);return e?ra():Ii()}function Ii(){Y(ji(),`useNavigate() may be used only in the context of a <Router> component.`);let e=J.useContext(mi),{basename:t,navigator:n}=J.useContext(xi),{matches:r}=J.useContext(Ci),{pathname:i}=Mi(),a=JSON.stringify(Zr(r)),o=J.useRef(!1);return Pi(()=>{o.current=!0}),J.useCallback((r,s={})=>{if(vr(o.current,Ni),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=Qr(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:ei([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var Li=J.createContext(null);function Ri(e){let t=J.useContext(Ci).outlet;return J.useMemo(()=>t&&J.createElement(Li.Provider,{value:e},t),[t,e])}function zi(){let{matches:e}=J.useContext(Ci);return e[e.length-1]?.params??{}}function Bi(e,{relative:t}={}){let{matches:n}=J.useContext(Ci),{pathname:r}=Mi(),i=JSON.stringify(Zr(n));return J.useMemo(()=>Qr(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Vi(e,t){return Hi(e,t)}function Hi(e,t,n){Y(ji(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=J.useContext(xi),{matches:i}=J.useContext(Ci),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||``;aa(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
+
4
+ Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=Mi(),d;if(t){let e=typeof t==`string`?Cr(t):t;Y(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})):Er(e,{pathname:p});vr(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),vr(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=Yi(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:ei([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:ei([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?J.createElement(Si.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function Ui(){let e=na(),t=oi(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=J.createElement(J.Fragment,null,J.createElement(`p`,null,`💿 Hey developer 👋`),J.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,J.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,J.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),J.createElement(J.Fragment,null,J.createElement(`h2`,null,`Unexpected Application Error!`),J.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?J.createElement(`pre`,{style:i},n):null,o)}var Wi=J.createElement(Ui,null),Gi=class extends J.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=ki(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:J.createElement(Ci.Provider,{value:this.props.routeContext},J.createElement(wi.Provider,{value:e,children:this.props.component}));return this.context?J.createElement(qi,{error:e},t):t}};Gi.contextType=gi;var Ki=new WeakMap;function qi({children:e,error:t}){let{basename:n}=J.useContext(xi);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Oi(t.digest);if(e){let r=Ki.get(t);if(r)throw r;let i=li(e.location,n),a=i.absoluteURL||i.to;if(pi(a))throw Error(`Invalid redirect location`);if(ci&&!Ki.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 Ki.set(t,n),n}}return J.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function Ji({routeContext:e,match:t,children:n}){let r=J.useContext(mi);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),J.createElement(Ci.Provider,{value:e},n)}function Yi(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);Y(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:si(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||Wi,o&&(s<0&&c===0?(aa(`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?J.createElement(n.route.Component,null):n.route.element?n.route.element:e,J.createElement(Ji,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?J.createElement(Gi,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Xi(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Zi(e){let t=J.useContext(mi);return Y(t,Xi(e)),t}function Qi(e){let t=J.useContext(hi);return Y(t,Xi(e)),t}function $i(e){let t=J.useContext(Ci);return Y(t,Xi(e)),t}function ea(e){let t=$i(e),n=t.matches[t.matches.length-1];return Y(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function ta(){return ea(`useRouteId`)}function na(){let e=J.useContext(wi),t=Qi(`useRouteError`),n=ea(`useRouteError`);return e===void 0?t.errors?.[n]:e}function ra(){let{router:e}=Zi(`useNavigate`),t=ea(`useNavigate`),n=J.useRef(!1);return Pi(()=>{n.current=!0}),J.useCallback(async(r,i={})=>{vr(n.current,Ni),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var ia={};function aa(e,t,n){!t&&!ia[e]&&(ia[e]=!0,vr(!1,n))}J.memo(oa);function oa({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Hi(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function sa({to:e,replace:t,state:n,relative:r}){Y(ji(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=J.useContext(xi);vr(!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}=J.useContext(Ci),{pathname:o}=Mi(),s=Fi(),c=Qr(e,Zr(a),o,r===`path`),l=JSON.stringify(c);return J.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function ca(e){return Ri(e.context)}function la(e){Y(!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 ua({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){Y(!ji(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=J.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=Cr(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=J.useMemo(()=>{let e=Kr(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 vr(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:J.createElement(xi.Provider,{value:c},J.createElement(Si.Provider,{children:t,value:h}))}function da({children:e,location:t}){return Vi(fa(e),t)}J.Component;function fa(e,t=[]){let n=[];return J.Children.forEach(e,(e,r)=>{if(!J.isValidElement(e))return;let i=[...t,r];if(e.type===J.Fragment){n.push.apply(n,fa(e.props.children,i));return}Y(e.type===la,`[${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>`),Y(!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=fa(e.props.children,i)),n.push(a)}),n}var pa=`get`,ma=`application/x-www-form-urlencoded`;function ha(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function ga(e){return ha(e)&&e.tagName.toLowerCase()===`button`}function _a(e){return ha(e)&&e.tagName.toLowerCase()===`form`}function va(e){return ha(e)&&e.tagName.toLowerCase()===`input`}function ya(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function ba(e,t){return e.button===0&&(!t||t===`_self`)&&!ya(e)}function xa(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 Sa(e,t){let n=xa(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Ca=null;function wa(){if(Ca===null)try{new FormData(document.createElement(`form`),0),Ca=!1}catch{Ca=!0}return Ca}var Ta=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Ea(e){return e!=null&&!Ta.has(e)?(vr(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${ma}"`),null):e}function Da(e,t){let n,r,i,a,o;if(_a(e)){let o=e.getAttribute(`action`);r=o?Kr(o,t):null,n=e.getAttribute(`method`)||pa,i=Ea(e.getAttribute(`enctype`))||ma,a=new FormData(e)}else if(ga(e)||va(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?Kr(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||pa,i=Ea(e.getAttribute(`formenctype`))||Ea(o.getAttribute(`enctype`))||ma,a=new FormData(o,e),!wa()){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(ha(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=pa,r=null,i=ma,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 Oa(e,t){if(e===!1||e==null)throw Error(t)}function ka(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&&Kr(i.pathname,t)===`/`?`${ti(t)}/_root.${r}`:`${ti(i.pathname)}.${r}`,i}async function Aa(e,t){if(e.id in t)return t[e.id];try{let n=await s(()=>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 ja(e){return e!=null&&typeof e.page==`string`}function Ma(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 Na(e,t,n){return Ra((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await Aa(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Ma).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Pa(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 Fa(e,t,{includeHydrateFallback:n}={}){return Ia(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 Ia(e){return[...new Set(e)]}function La(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Ra(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!ja(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(La(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function za(){let e=J.useContext(mi);return Oa(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function Ba(){let e=J.useContext(hi);return Oa(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Va=J.createContext(void 0);Va.displayName=`FrameworkContext`;function Ha(){let e=J.useContext(Va);return Oa(e,`You must render this element inside a <HydratedRouter> element`),e}function Ua(e,t){let n=J.useContext(Va),[r,i]=J.useState(!1),[a,o]=J.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=J.useRef(null);J.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]),J.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:Wa(s,p),onBlur:Wa(c,m),onMouseEnter:Wa(l,p),onMouseLeave:Wa(u,m),onTouchStart:Wa(d,p)}]:[a,f,{}]:[!1,f,{}]}function Wa(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Ga({page:e,...t}){let n=_i(),{nonce:r}=Ha(),{router:i}=za(),a=J.useMemo(()=>Er(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?J.createElement(qa,{page:e,matches:a,...t}):J.createElement(Ja,{page:e,matches:a,...t})):null}function Ka(e){let{manifest:t,routeModules:n}=Ha(),[r,i]=J.useState([]);return J.useEffect(()=>{let r=!1;return Na(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function qa({page:e,matches:t,...n}){let r=Mi(),{future:i}=Ha(),{basename:a}=za(),o=J.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=ka(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 J.createElement(J.Fragment,null,o.map(e=>J.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function Ja({page:e,matches:t,...n}){let r=Mi(),{future:i,manifest:a,routeModules:o}=Ha(),{basename:s}=za(),{loaderData:c,matches:l}=Ba(),u=J.useMemo(()=>Pa(e,t,l,a,r,`data`),[e,t,l,a,r]),d=J.useMemo(()=>Pa(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=J.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=ka(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=J.useMemo(()=>Fa(d,a),[d,a]),m=Ka(d);return J.createElement(J.Fragment,null,f.map(e=>J.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>J.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>J.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Ya(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}J.Component;var Xa=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Xa&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Za({basename:e,children:t,useTransitions:n,window:r}){let i=J.useRef();i.current??=_r({window:r,v5Compat:!0});let a=i.current,[o,s]=J.useState({action:a.action,location:a.location}),c=J.useCallback(e=>{n===!1?s(e):J.startTransition(()=>s(e))},[n]);return J.useLayoutEffect(()=>a.listen(c),[a,c]),J.createElement(ua,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var Qa=J.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:_}=J.useContext(xi),v=typeof l==`string`&&dr.test(l),y=li(l,h);l=y.to;let b=Ai(l,{relative:r}),x=Mi(),S=null;if(o){let e=Qr(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:ei([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=Ua(n,p),E=ro(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=J.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:Ya(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?J.createElement(J.Fragment,null,k,J.createElement(Ga,{page:b})):k});Qa.displayName=`Link`;var $a=J.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=Bi(a,{relative:c.relative}),d=Mi(),f=J.useContext(hi),{navigator:p,basename:m}=J.useContext(xi),h=f!=null&&lo(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=Kr(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 J.createElement(Qa,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});$a.displayName=`NavLink`;var eo=J.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=pa,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=J.useContext(xi),g=so(),_=co(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&dr.test(s);return J.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?J.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});eo.displayName=`Form`;function to(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function no(e){let t=J.useContext(mi);return Y(t,to(e)),t}function ro(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Fi(),d=Mi(),f=Bi(e,{relative:o});return J.useCallback(p=>{if(ba(p,t)){p.preventDefault();let t=n===void 0?Sr(d)===Sr(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?J.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function io(e){vr(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=J.useRef(xa(e)),n=J.useRef(!1),r=Mi(),i=J.useMemo(()=>Sa(r.search,n.current?null:t.current),[r.search]),a=Fi();return[i,J.useCallback((e,t)=>{let r=xa(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var ao=0,oo=()=>`__${String(++ao)}__`;function so(){let{router:e}=no(`useSubmit`),{basename:t}=J.useContext(xi),n=ta(),r=e.fetch,i=e.navigate;return J.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Da(e,t);if(a.navigate===!1){let e=a.fetcherKey||oo();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 co(e,{relative:t}={}){let{basename:n}=J.useContext(xi),r=J.useContext(Ci);Y(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...Bi(e||`.`,{relative:t})},o=Mi();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:ei([n,a.pathname])),Sr(a)}function lo(e,{relative:t}={}){let n=J.useContext(vi);Y(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=no(`useViewTransitionState`),i=Bi(e,{relative:t});if(!n.isTransitioning)return!1;let a=Kr(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Kr(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Hr(i.pathname,o)!=null||Hr(i.pathname,a)!=null}var uo=e(o(),1),X=n(),fo=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(xe,{ref:n,className:H(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));fo.displayName=xe.displayName;var po=a();function mo(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var ho=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=St,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||mo();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=Ct(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()}};function go({className:e=`h-5 w-5`,...t}){return(0,X.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,X.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,X.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`})]})}var _o=`canvas:alwaysOnReader`;function vo(){try{return localStorage.getItem(_o)!==`off`}catch{return!0}}var yo=vo(),bo=new Set;function xo(){return yo}function So(e){try{localStorage.setItem(_o,e?`on`:`off`)}catch{}yo=e;for(let e of bo)e()}function Co(e){bo.add(e);let t=t=>{(t.key===_o||t.key===null)&&(yo=vo(),e())};return window.addEventListener(`storage`,t),()=>{bo.delete(e),window.removeEventListener(`storage`,t)}}function wo(){return(0,J.useSyncExternalStore)(Co,xo,()=>!0)}var To=`canvas:readerWidth`,Eo=320,Do=1600;function Oo(){try{let e=Number(sessionStorage.getItem(To));return Number.isFinite(e)&&e>=Eo&&e<=Do?e:null}catch{return null}}var ko=Oo(),Ao=new Set;function jo(e){return Ao.add(e),()=>{Ao.delete(e)}}function Mo(e){ko=e===null?null:Math.round(Math.max(Eo,Math.min(Do,e)));try{ko===null?sessionStorage.removeItem(To):sessionStorage.setItem(To,String(ko))}catch{}Ao.forEach(e=>e())}function No(){return(0,J.useSyncExternalStore)(jo,()=>ko,()=>null)}var Po=`(max-width: 767px)`,Fo=new Map;function Io(e){let t=Fo.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},Fo.set(e,t)}return t}function Lo(){let e=Io(Po);return(0,J.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>!1)}function Ro(){return zo(`(max-width: 1023px)`)}function zo(e){let t=Io(e);return(0,J.useSyncExternalStore)(t.subscribe,t.getSnapshot,()=>!1)}var Bo=1,Vo=8,Ho=320,Uo=28,Wo=2.5,Go={scale:1,x:0,y:0};function Ko({src:e,alt:t,className:n=``,onZoomChange:r}){let i=(0,J.useRef)(null),a=(0,J.useRef)(null),[o,s]=(0,J.useState)(Go),c=(0,J.useRef)(new Map),l=(0,J.useRef)(null),u=(0,J.useRef)(null),d=(0,J.useRef)(!1),f=(0,J.useRef)(null),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(e);h!==e&&(g(e),s(Go)),(0,J.useEffect)(()=>{r?.(o.scale>1.001)},[o.scale,r]);let _=(0,J.useCallback)(e=>{let t=i.current,n=a.current;if(!t||!n)return e;let r=Math.min(Vo,Math.max(Bo,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,J.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,J.useCallback)(()=>{let e=i.current,t=a.current;if(!e||!t||!t.offsetWidth||!t.offsetHeight)return Wo;let n=Math.max(e.clientWidth/t.offsetWidth,e.clientHeight/t.offsetHeight),r=Math.max(t.naturalWidth/t.offsetWidth,t.naturalHeight/t.offsetHeight)||Vo;return Math.min(Vo,Math.max(Wo,Math.min(Math.max(n,Wo),r)))},[]),b=(0,J.useCallback)((e,t)=>{o.scale>1.001?s(Go):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<Ho&&Math.hypot(e.clientX-n.x,e.clientY-n.y)<Uo){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<=Bo?s(Go):v(Math.min(Vo,t),e.clientX,e.clientY)},T=o.scale>1.001;return(0,X.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<Ho)&&b(e.clientX,e.clientY)},children:(0,X.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 var(--duration-normal) ease-out`,willChange:`transform`}})})}var qo=(0,J.createContext)(null);function Jo(){return!/android|iphone|ipad|mobile/i.test(navigator.userAgent)&&navigator.pdfViewerEnabled!==!1}var Yo=40,Xo=1600;function Zo({blob:e,filename:t}){let n=(0,J.useRef)(null),[r,i]=(0,J.useState)({error:null,pages:0,truncated:!1});return(0,J.useEffect)(()=>{let r=n.current;if(!r)return;let a=!1,o=null;return(async()=>{let n=await s(()=>import(`./pdf-Ciz5_WNq.js`),__vite__mapDeps([0,1])),c=(await s(async()=>{let{default:e}=await import(`./pdf.worker.min-C8Ts8bNu.js`);return{default:e}},[])).default;n.GlobalWorkerOptions.workerSrc=c;let l=await e.arrayBuffer();if(a)return;let u=n.getDocument({data:l});o=()=>{u.destroy()};let d=await u.promise;if(a)return;let f=Math.min(d.numPages,Yo),p=r.clientWidth||600,m=window.devicePixelRatio||1;for(let e=1;e<=f;e++){if(a)return;let n=await d.getPage(e),o=n.getViewport({scale:1}),s=Math.min(p*m,Xo*m)/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:d.numPages>Yo})}})().catch(e=>{a||i(t=>({...t,error:e instanceof Error?e.message:String(e)}))}),()=>{a=!0,o?.(),r.replaceChildren()}},[e,t]),(0,X.jsxs)(`div`,{className:`space-y-2`,children:[r.error&&(0,X.jsxs)(`p`,{className:`text-sm text-destructive`,children:[`Could not render PDF: `,r.error]}),!r.error&&r.pages===0&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering PDF…`}),(0,X.jsx)(`div`,{ref:n,className:`space-y-2`}),r.truncated&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,Yo,` pages. Download the file for the full document.`]})]})}function Qo({blob:e,blobUrl:t,filename:n,className:r=``}){let i=(0,J.useMemo)(()=>e&&e.type!==`application/pdf`?URL.createObjectURL(e.slice(0,e.size,`application/pdf`)):null,[e]);return(0,J.useEffect)(()=>()=>{i&&URL.revokeObjectURL(i)},[i]),Jo()||!e?(0,X.jsx)(`div`,{className:`min-h-[300px] ${r}`,children:(0,X.jsx)(`iframe`,{src:i??t,className:`h-full min-h-[300px] w-full rounded border`,title:n})}):(0,X.jsx)(`div`,{className:`max-h-viewport-pane overflow-y-auto ${r}`,children:(0,X.jsx)(Zo,{blob:e,filename:n})})}function $o(e,t,n=256,{enabled:r=!0,blobFallback:i=!0,version:a=null}={}){let{isPublic:o,fetchBlob:s,fetchThumbnail:c}=Jn(e),l=`${o?`pub`:`ws`}:${e}:${t}:${n}:${r}:${a??``}`,[u,d]=(0,J.useState)({blobUrl:null,error:null,loading:r}),[f,p]=(0,J.useState)(l);return l!==f&&(p(l),d({blobUrl:null,error:null,loading:r})),(0,J.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 es({workspaceId:e,document:t}){let{download:n}=Jn(e),[r,i]=(0,J.useState)(!1),a=Ft(t)||`document-${t.id}`;return(0,X.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,X.jsx)(Me,{className:`h-3.5 w-3.5`}),r?`Preparing…`:`Download`]})}var ts=1600;function ns({error:e,loading:t,children:n}){return e?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:e}):t?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading preview...`}):(0,X.jsx)(X.Fragment,{children:n})}function rs({workspaceId:e,document:t,className:n=``}){let r=(0,J.useContext)(qo),i=Lo(),a=zo(`(pointer: coarse)`),{blobUrl:o,error:s,loading:c}=$o(e,t.id,ts,{version:t.checksumArray?.[0]??null}),{fetchBlob:l}=Jn(e),u=Ft(t)||`document-${t.id}`,[d,f]=(0,J.useState)(!1);return(0,X.jsx)(ns,{error:s,loading:c,children:o&&(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[i||a?(0,X.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,X.jsx)(Ko,{src:o,alt:u,className:`max-h-full max-w-full object-contain`})}):(0,X.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,X.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,X.jsx)(Me,{className:`h-3.5 w-3.5`}),d?`Preparing…`:`Download original`]})]})})}function is({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=zn(e,t.id);return(0,X.jsx)(ns,{error:i,loading:a,children:r&&(0,X.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,X.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`,className:`w-full`}),(0,X.jsx)(es,{workspaceId:e,document:t})]})})}function as({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=zn(e,t.id),[o,s]=(0,J.useState)(!1);return(0,X.jsx)(ns,{error:i,loading:a,children:r&&(0,X.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,X.jsx)(`video`,{src:r,controls:!0,playsInline:!0,preload:`metadata`,onError:()=>s(!0),className:`max-h-viewport-pane w-full rounded border`}),o&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This video can’t be played inline in your browser. Download it to view.`}),(0,X.jsx)(es,{workspaceId:e,document:t})]})})}function os({workspaceId:e,document:t,className:n=``}){let{blobUrl:r,blob:i,error:a,loading:o}=Vn(e,t.id,{typeHint:`application/pdf`}),s=Ft(t)||`document-${t.id}`;return(0,X.jsx)(ns,{error:a,loading:o,children:r&&(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[(0,X.jsx)(Qo,{blob:i,blobUrl:r,filename:s,className:`min-h-0 flex-1`}),(0,X.jsx)(`div`,{children:(0,X.jsx)(es,{workspaceId:e,document:t})})]})})}var ss=(0,J.lazy)(()=>s(()=>import(`./markdown-html-XoABNf32.js`),__vite__mapDeps([2,3,4,5,6,7,8])));function cs({content:e,className:t=``,preview:n=!1}){return(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`div`,{className:`whitespace-pre-wrap break-words ${t}`,children:e}),children:(0,X.jsx)(ss,{content:e,className:t,preview:n})})}function ls({workspaceId:e,document:t,className:n=``}){let{text:r,error:i,loading:a}=Vn(e,t.id,{mode:`text`,version:t.checksumArray?.[0]});return i?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):a||r==null?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,X.jsx)(`pre`,{className:`bg-muted p-3 rounded text-xs overflow-auto max-h-viewport-pane whitespace-pre-wrap ${n}`,children:r})}function us({workspaceId:e,document:t,className:n=``}){let r=t.schema===Yt,{text:i,error:a,loading:o}=Vn(e,t.id,{mode:`text`,enabled:!r,version:t.checksumArray?.[0]});return r?(0,X.jsxs)(`div`,{className:`markdown-note space-y-3 ${n}`,children:[t.data?.title?(0,X.jsx)(`h3`,{className:`text-lg font-semibold`,children:String(t.data.title)}):null,(0,X.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent`,children:(0,X.jsx)(cs,{content:String(t.data?.content??``),className:`markdown-doc px-4 py-3`})})]}):a?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:a}):o||i==null?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,X.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent overflow-auto max-h-viewport-pane ${n}`,children:(0,X.jsx)(cs,{content:i,className:`markdown-doc px-4 py-3`})})}function ds({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),r=Rt(n);return r?(0,X.jsx)(`div`,{className:`aspect-video w-full ${t}`,children:(0,X.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 fs({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),[r,i]=(0,J.useState)({blobUrl:null,blob:null,failed:!1,loading:!0}),[a,o]=(0,J.useState)(n);n!==a&&(o(n),i({blobUrl:null,blob:null,failed:!1,loading:!0})),(0,J.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(`${xt}/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,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${t}`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3`,children:[(0,X.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs text-primary hover:underline`,children:[(0,X.jsx)(Ae,{className:`h-3 w-3`}),` `,n]}),c&&(0,X.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,X.jsx)(Me,{className:`h-3.5 w-3.5`}),` Download`]})]}),u&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading PDF…`}),l&&(0,X.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,X.jsx)(Qo,{blob:c,blobUrl:s,filename:d,className:`min-h-[300px] flex-1`})]})}function ps(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 ms(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function hs({document:e,className:t=``}){let n=e.data||{},r=String(n.url??n.uri??``),i=String(n.title??n.label??``)||ms(r),a=typeof n.favIconUrl==`string`?n.favIconUrl:``,o=n.pinned===!0,s=typeof n.timestamp==`string`?n.timestamp:null,[c,l]=(0,J.useState)(!1);return(0,X.jsxs)(`div`,{className:`space-y-3 ${t}`,children:[(0,X.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,X.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,X.jsx)(`img`,{src:a,alt:``,className:`h-5 w-5`,onError:()=>l(!0)}):(0,X.jsx)(se,{className:`h-4 w-4 text-muted-foreground`})}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,X.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:i}),o&&(0,X.jsx)(M,{className:`h-3 w-3 shrink-0 fill-warning text-warning`})]}),(0,X.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-muted-foreground`,children:ms(r)}),(0,X.jsx)(`div`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground/70`,children:r})]}),(0,X.jsx)(Ae,{className:`mt-1 h-4 w-4 shrink-0 text-muted-foreground reveal-on-hover`})]}),s&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Saved `,new Date(s).toLocaleString()]})]})}var gs={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4};function _s(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 vs(){return new Promise((e,t)=>navigator.geolocation.getCurrentPosition(e,t,gs))}function ys(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 bs(){let e=typeof navigator<`u`&&`geolocation`in navigator&&typeof window<`u`&&window.isSecureContext,[t,n]=(0,J.useState)(e?`prompt`:`unsupported`),[r,i]=(0,J.useState)(!1),[a,o]=(0,J.useState)(!1),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(null),[d,f]=(0,J.useState)(null),[p,m]=(0,J.useState)(null),h=(0,J.useRef)(!1),g=(0,J.useRef)(null),_=(0,J.useRef)(null);(0,J.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,J.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,J.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),vs().then(e=>{let t=_s(e);g.current=t,u(t),n(`granted`)}).catch(e=>{c(ys(e)),e?.code===1&&(n(`denied`),h.current=!1,i(!1))}).finally(()=>o(!1)))},[e]),manual:d,manualLabel:p,setManual:v,capture:(0,J.useCallback)(async()=>{if(_.current)return _.current;if(!h.current||!e)return null;try{return _s(await vs())}catch{return g.current}},[e])}}var xs=`2.1`,Ss=[`pending`,`in-progress`,`completed`,`cancelled`],Cs={pending:`Pending`,"in-progress":`In progress`,completed:`Completed`,cancelled:`Cancelled`};function ws(e){return String(e).padStart(2,`0`)}function Ts(e){return`${e.getFullYear()}-${ws(e.getMonth()+1)}-${ws(e.getDate())}T${ws(e.getHours())}:${ws(e.getMinutes())}`}function Es(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:Ts(t)}function Ds(e){if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function Os(){let e=new Date;return e.setHours(23,59,0,0),Ts(e)}function ks(e){let t=Ds(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 As(){let[e,t]=(0,J.useState)(``),[n,r]=(0,J.useState)(``),[i,a]=(0,J.useState)(`pending`),[o,s]=(0,J.useState)(``),[c,l]=(0,J.useState)(Os()),[u,d]=(0,J.useState)([]),[f,p]=(0,J.useState)(``),[m,h]=(0,J.useState)(!1),g=bs(),_=e.trim().length>0&&!m;async function v(t){h(!0);try{let r=await g.capture(),a=f.trim(),s={schema:Nt,schemaVersion:xs,data:ks({title:e,description:n,status:i,priority:o,due:c}),...a?{comment:a}:{},metadata:{features:Wn(u),...r?{geo:r}:{}}};return await ir(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 js(e){return e.data||{}}var Ms={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 Ns(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 Ps(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 Fs(e,t,n){let r=n===`completed`,i={...t.data||{},status:n,completed:r};r?i.completedAt=new Date().toISOString():delete i.completedAt,await jn(e,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:i}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}function Is({document:e,workspaceId:t,className:n=``}){let r=js(e),i=Yn()!=null,[a,o]=(0,J.useState)(!1),{replicating:s,label:c}=K(e),l=r.status===`completed`,u=r.status??`pending`,d=Ns(r);return(0,X.jsx)(`div`,{className:`space-y-3 ${n}`,children:(0,X.jsxs)(`div`,{className:`relative flex items-start gap-3 rounded-lg border bg-card p-3 transition-opacity ${s?`opacity-60`:``}`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(i||a)){o(!0);try{await Fs(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,X.jsx)(ut,{className:`h-3 w-3 animate-spin`}):l&&(0,X.jsx)(b,{className:`h-3.5 w-3.5`})}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,X.jsx)(`div`,{className:`font-medium leading-tight ${l?`text-muted-foreground line-through`:``}`,children:r.title||`Todo ${e.id}`}),(0,X.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-2 text-xs`,children:[(0,X.jsx)(`span`,{className:`rounded-full px-2 py-0.5 ${Ms[u]}`,children:Cs[u]}),r.dueDate&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,X.jsx)(T,{className:`h-3 w-3`}),Ps(r.dueDate),d?` · overdue`:``]}),typeof r.priority==`number`&&(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,children:[(0,X.jsx)(Oe,{className:`h-3 w-3`}),`P`,r.priority]})]}),r.description&&(0,X.jsx)(cs,{content:String(r.description),className:`mt-2 text-sm text-muted-foreground`}),s&&(0,X.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground`,role:`status`,children:[(0,X.jsx)(ut,{className:`h-3 w-3 animate-spin`}),c]})]})]})})}function Ls(e,t){let{fetchBlob:n}=Jn(e),r=Yn(),i=t.checksumArray?.[0]||t.updatedAt||``,a=JSON.stringify([e,r,t.id,i]),o=typeof t.data?.body==`string`?t.data.body:null,s=typeof t.data?.bodyHtml==`string`?t.data.bodyHtml:null,c=o!==null||s!==null,[l,u]=(0,J.useState)(null);return(0,J.useEffect)(()=>{if(c)return;let e=new AbortController;return n(t.id,{format:`email`,version:i,signal:e.signal}).then(async({blob:t})=>{let n=JSON.parse(await t.text());if(typeof n.body!=`string`||n.bodyHtml!=null&&typeof n.bodyHtml!=`string`)throw Error(`Invalid email content response`);e.signal.aborted||u({key:a,body:n.body,bodyHtml:n.bodyHtml||null,error:null})}).catch(t=>{e.signal.aborted||u({key:a,body:``,bodyHtml:null,error:t instanceof Error?t.message:String(t)})}),()=>e.abort()},[a,c,n,t.id,i]),c?{body:o||``,bodyHtml:s,loading:!1,error:null}:l?.key===a?{...l,loading:!1}:{body:``,bodyHtml:null,loading:!0,error:null}}function Rs(e){return e?typeof e==`string`?e:e.name&&e.address?`${e.name} <${e.address}>`:e.address||e.name||``:``}function zs(e){return e?(Array.isArray(e)?e:[e]).map(e=>Rs(e)).filter(Boolean).join(`, `):``}function Bs(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 Vs(e,t,n){let r=0;sr.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=sr.sanitize(e,{FORBID_TAGS:[`script`,`iframe`,`object`,`embed`,`form`,`base`,`link`,`meta`],FORBID_ATTR:[`srcset`]}),i=`<!doctype html><html><head>
5
+ <meta charset="utf-8">
6
+ <meta name="viewport" content="width=device-width,initial-scale=1">
7
+ <meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; img-src data:${n?` https:`:``}; style-src 'unsafe-inline'`}">
8
+ <style>html{overflow:auto}body{margin:12px;font:14px/1.5 system-ui,sans-serif;color:#1a1a1a;background:#fff}@media(max-width:480px){body{margin:8px}}</style>
9
+ </head><body>${t}</body></html>`;return{url:URL.createObjectURL(new Blob([i],{type:`text/html;charset=utf-8`})),remoteCount:r}}finally{sr.removeHook(`afterSanitizeAttributes`)}}function Hs(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 Us(e){return(0,X.jsx)(Ws,{...e},`${e.workspaceId}:${e.document.id}`)}function Ws({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=Jn(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],{body:s,bodyHtml:c,loading:l,error:u}=Ls(e,t),[d,f]=(0,J.useState)(null),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(!1),[_,v]=(0,J.useState)(0),[y,b]=(0,J.useState)(null);(0,J.useEffect)(()=>{if(!c||p)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 Hs(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}=Vs(c,r,h);n.push(i),f(i),v(a)}).catch(t=>{e||b(String(t instanceof Error?t.message:t))}),()=>{e=!0,n.forEach(e=>URL.revokeObjectURL(e)),f(null)}},[e,t.id,c,p,h]);let x=typeof a.date==`string`?new Date(a.date).toLocaleString():null,S=o.filter(e=>!e.isInline||!e.contentId),C=async e=>{if(e.url)try{await i(t.id,e.filename||`attachment`,{url:e.url})}catch(e){b(e instanceof Error?e.message:String(e))}};return(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 min-w-0 flex-col gap-3 ${n}`,children:[(0,X.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-2 text-sm sm:p-3`,children:(0,X.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2 sm:gap-3`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 basis-64 space-y-1`,children:[(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,X.jsxs)(`details`,{className:`sm:hidden`,children:[(0,X.jsxs)(`summary`,{className:`cursor-pointer text-xs`,children:[(0,X.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,X.jsx)(`span`,{className:`ml-2 text-muted-foreground`,children:`Details`})]}),(0,X.jsxs)(`div`,{className:`mt-2 space-y-1 break-words text-xs`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Rs(a.from)]}),zs(a.to)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,zs(a.to)]}),zs(a.cc)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,zs(a.cc)]}),x&&(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:x})]})]}),(0,X.jsxs)(`div`,{className:`hidden space-y-1 break-words sm:block`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Rs(a.from)]}),zs(a.to)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,zs(a.to)]}),zs(a.cc)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,zs(a.cc)]}),x&&(0,X.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:x})]})]}),c&&(0,X.jsxs)(`div`,{className:`flex max-w-full flex-wrap gap-2`,children:[(0,X.jsxs)(G,{size:`sm`,variant:`outline`,onClick:()=>m(!p),children:[p?(0,X.jsx)(re,{className:`mr-1.5 h-3.5 w-3.5`}):(0,X.jsx)(Le,{className:`mr-1.5 h-3.5 w-3.5`}),p?`HTML`:`Plain text`]}),!p&&_>0&&(0,X.jsxs)(G,{size:`sm`,variant:h?`secondary`:`outline`,onClick:()=>g(!h),title:`Remote images can reveal your IP/read status to the sender`,children:[h?(0,X.jsx)(Re,{className:`mr-1.5 h-3.5 w-3.5`}):(0,X.jsx)(Be,{className:`mr-1.5 h-3.5 w-3.5`}),h?`Hide remote images`:`Show remote images (${_})`]})]})]})}),(y||u)&&(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:y||u}),l?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading message…`}):u?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:String(a.bodyPreview||`Message content could not be loaded.`)}):!p&&c?d?(0,X.jsx)(`iframe`,{src:d,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,X.jsx)(`pre`,{className:`min-h-[12rem] flex-1 overflow-auto whitespace-pre-wrap rounded bg-muted p-3 text-sm`,children:s||`(empty body)`}),S.length>0&&(0,X.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,X.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,S.length,`)`]}),S.map((e,t)=>(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,X.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,X.jsx)(Le,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,X.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:Bs(e.size)})]}),e.url&&(0,X.jsxs)(`button`,{onClick:()=>C(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,X.jsx)(Me,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}function Gs({attachment:e,workspaceId:t,document:n}){let{download:r}=Jn(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}=Vn(t,n.id,{url:e.url,typeHint:i,enabled:!o&&!!e.url}),{src:u,error:d,loading:f}=zn(t,n.id,{url:e.url,enabled:o&&!!e.url}),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(``),_=o?d:c;return(0,X.jsxs)(`div`,{className:`space-y-2 rounded border p-2`,children:[_&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:_}),(o?f:l)&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading attachment…`}),!o&&s&&i.startsWith(`image/`)&&(0,X.jsx)(`img`,{src:s,alt:a,className:`max-h-96 max-w-full rounded object-contain`}),o&&u&&(i.startsWith(`video/`)?(0,X.jsx)(`video`,{controls:!0,playsInline:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`max-h-96 w-full rounded`},u):(0,X.jsx)(`audio`,{controls:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`w-full`},u)),p&&(0,X.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,X.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:h}),e.url&&(0,X.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 Ks(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,X.jsxs)(`article`,{className:`space-y-4 p-3 ${e.className||``}`,children:[(0,X.jsxs)(`header`,{className:`space-y-1 border-b pb-3`,children:[(0,X.jsx)(`p`,{className:`font-medium`,children:n?.name||n?.displayName||n?.username||n?.id||`Unknown sender`}),(0,X.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,X.jsx)(`p`,{className:`whitespace-pre-wrap break-words text-sm`,children:String(t.text||`(No text)`)}),!!t.mediaError&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:String(t.mediaError)}),i.map((t,n)=>(0,X.jsx)(Gs,{...e,attachment:t},t.url||n))]})}var qs={email:Se,phone:S,sms:be,chat:be,slack:be,matrix:be,web:se,url:se},Js={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Ys=e=>Array.isArray(e)?e:[];function Xs(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 Zs({title:e,count:t,children:n}){return t===0?null:(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,X.jsx)(`div`,{className:`space-y-1`,children:n})]})}function Qs({icon:e,primary:t,children:n,title:r}){return(0,X.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,X.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,X.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,X.jsx)(Ye,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function $s({document:e,className:t}){let n=e.data??{},r=Ys(n.identifiers),i=Ys(n.channels),a=Ys(n.organizations),o=Ys(n.links),s=Ys(n.tags),c=String(n.displayName||``).trim(),l=wn(e.schema,Xt),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,X.jsxs)(`div`,{className:H(`space-y-4`,t),children:[(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:Js[l]||l}),f&&f!==c&&(0,X.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,X.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,X.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,X.jsx)(Zs,{title:`Primary email`,count:1,children:(0,X.jsx)(Qs,{icon:Se,primary:!0,children:(0,X.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,X.jsx)(Zs,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=Xs(n,r),a=qs[n]||be;return(0,X.jsxs)(Qs,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,X.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,X.jsx)(Zs,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,X.jsxs)(Qs,{icon:st,primary:e.primary,children:[(0,X.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,X.jsx)(Zs,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,X.jsxs)(Qs,{icon:et,children:[e.name,e.role&&(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,X.jsx)(Zs,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,X.jsxs)(Qs,{icon:We,children:[(0,X.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,X.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,X.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function ec({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,X.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,X.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function tc(e){let t=e.schema;if(t===`data/schema/note`)return us;if(t===`data/schema/drawing`)return rs;if(t===`data/schema/task`)return Is;if(t===`data/schema/message/email`)return Us;if(t===`data/schema/message`)return Ks;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return $s;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return Rt(t)?ds:ps(t)?fs:hs}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(Vt(n,Ft(e))){case`image`:return rs;case`audio`:return is;case`video`:return as;case`pdf`:return os;case`markdown`:return us;case`text`:return ls;default:return ec}}function nc(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}`}var rc=[];function ic(e){if(e.key!==`Escape`||e.isComposing||e.defaultPrevented)return;let t=rc[rc.length-1];t&&(e.preventDefault(),t())}function ac(e,t=!0){let n=(0,J.useRef)(e);(0,J.useEffect)(()=>{n.current=e});let r=t&&!!e;(0,J.useEffect)(()=>{if(!r)return;let e=()=>n.current?.();return rc.push(e),rc.length===1&&window.addEventListener(`keydown`,ic),()=>{let t=rc.indexOf(e);t>=0&&rc.splice(t,1),rc.length===0&&window.removeEventListener(`keydown`,ic)}},[r])}function oc({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,J.useRef)(null),[o,s]=(0,J.useState)({x:e,y:t});return ac(n),(0,J.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,uo.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,X.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:H(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r,`bg-popover text-popover-foreground`),children:i})]}),document.body)}var sc=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),cc={Delete:`Del`,Backspace:`⌫`,Enter:`↵`,ArrowUp:`↑`,ArrowDown:`↓`};function lc(e){let t=e.split(`+`),n=t.pop()||``,r=cc[n]||(n.length===1?n.toUpperCase():n);if(sc){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 uc(e,t){let n=t.split(`+`),r=n.pop()||``;return(sc?e.metaKey:e.ctrlKey)!==n.includes(`Mod`)||e.shiftKey!==n.includes(`Shift`)||e.altKey!==n.includes(`Alt`)||sc&&e.ctrlKey!==n.includes(`Ctrl`)?!1:r.length===1?e.key.toLowerCase()===r.toLowerCase():e.key===r}function dc(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 fc(e,t){if(e.defaultPrevented||e.nativeEvent.isComposing||dc(e.target))return!1;let n=t.find(t=>t.shortcut&&!t.disabled&&uc(e,t.shortcut));return n?(e.preventDefault(),e.stopPropagation(),n.run({shiftKey:e.shiftKey}),!0):!1}function pc(e){return e.key===`ContextMenu`||e.key===`F10`&&e.shiftKey}function mc(){return typeof window<`u`&&window.matchMedia(`(max-width: 767px)`).matches}function hc(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 gc(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 _c(e,t,n){t(),setTimeout(()=>{e.run({shiftKey:n})},0)}function vc({anchor:e,items:t,onClose:n,label:r}){let i=(0,J.useRef)(null);return(0,J.useEffect)(()=>{let e=document.activeElement;return i.current?.querySelector(`[role="menuitem"]:not([aria-disabled="true"])`)?.focus(),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[]),(0,X.jsx)(oc,{x:e.x,y:e.y,onClose:n,className:`min-w-[200px] rounded-lg border bg-popover text-popover-foreground py-1 shadow-elevation-3`,children:(0,X.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:gc(t).map((e,t)=>(0,X.jsxs)(J.Fragment,{children:[t>0&&(0,X.jsx)(`div`,{role:`separator`,className:`my-1 h-px bg-border`}),e[0].groupLabel&&(0,X.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,X.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,"aria-disabled":e.disabled||void 0,title:e.hint,onClick:t=>{e.disabled||_c(e,n,t.shiftKey)},className:H(`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,X.jsx)(t,{className:`h-3.5 w-3.5 shrink-0`}):(0,X.jsx)(`span`,{className:`w-3.5 shrink-0`}),(0,X.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.shortcut&&(0,X.jsx)(`kbd`,{className:`ml-4 shrink-0 font-sans text-[11px] text-muted-foreground`,children:lc(e.shortcut)})]},e.id)})]},`${e[0].group??``}:${t}`))})})}function yc({items:e,onClose:t,header:n}){ac(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,uo.createPortal)((0,X.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,className:`fixed inset-0 z-fullscreen flex flex-col bg-popover text-popover-foreground animate-in slide-in-from-bottom-10 fade-in duration-normal`,onClick:t,onContextMenu:e=>e.preventDefault(),children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,X.jsx)(`div`,{className:`min-w-0 flex-1`,children:n}),(0,X.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,X.jsx)(E,{className:`h-5 w-5`})})]}),(0,X.jsx)(`div`,{className:`min-h-4 flex-1`}),(0,X.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:[gc(e).map((e,n)=>(0,X.jsxs)(`div`,{className:H(`space-y-2`,n>0&&`pt-2`),children:[e[0].groupLabel&&(0,X.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,X.jsxs)(`button`,{type:`button`,disabled:e.disabled,onClick:n=>_c(e,t,n.shiftKey),className:H(r,e.destructive&&`border-destructive/30 text-destructive`,e.disabled&&`opacity-50`),children:[n&&(0,X.jsx)(n,{className:H(`h-5 w-5 shrink-0`,!e.destructive&&`text-muted-foreground`)}),e.label]},e.id)})]},`${e[0].group??``}:${n}`)),(0,X.jsx)(`button`,{type:`button`,onClick:t,className:`${r} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function bc({anchor:e,items:t,onClose:n,label:r,header:i}){return t.length===0?null:mc()?(0,X.jsx)(yc,{items:t,onClose:n,header:i??(r&&(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:r}))}):(0,X.jsx)(vc,{anchor:e,items:t,onClose:n,label:r})}var xc=null;function Sc(){return xc||=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(()=>(xc=null,[])),xc}async function Cc(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 wc=`ph:folder-fill`,Tc=`ph:squares-four-fill`,Ec=`ph:stack-fill`,Dc=[`#ef4444`,`#f97316`,`#f59e0b`,`#eab308`,`#84cc16`,`#22c55e`,`#14b8a6`,`#06b6d4`,`#3b82f6`,`#6366f1`,`#8b5cf6`,`#a855f7`,`#ec4899`,`#f43f5e`,`#64748b`,`#78716c`],Oc={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`}},kc={"workspace:home":{icon:`ph:house-fill`,color:`#3b82f6`},"workspace:data":{icon:`ph:database-fill`,color:`#14b8a6`}},Ac={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`}},jc={icon:`ph:hard-drive-fill`,color:`#64748b`};function Mc(e){let t=e.config?.ui??{},n=e.address&&kc[e.address]||e.driver&&Ac[e.driver]||jc;return{icon:typeof t.icon==`string`?t.icon:n.icon??jc.icon,color:typeof t.color==`string`?t.color:n.color??jc.color}}function Nc(e){let t=e.metadata?.ui??{},n=Oc[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 Pc(e){let t=Oc[(e.split(`/`).filter(Boolean).pop()??``).trim().toLowerCase()];return t?{metadata:Fc(void 0,t)}:null}function Fc(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 Ic=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,Lc=()=>({h:Ic(0,360),s:Ic(42,98),l:Ic(40,90)}),Rc=(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)}`},zc=()=>{let{h:e,s:t,l:n}=Lc();return Rc(e,t,n)},Bc=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)},Vc=(e,t=.82)=>{let n=Bc(e);return n===null||n>t},Hc=e=>e&&!Vc(e)?e:void 0,Uc=e=>{if(!e)return`text-muted-foreground/70`;let t=Bc(e);return t!==null&&t>.5?`text-black/45`:`text-white/80`},Wc=e=>{let t=Bc(e);return t!==null&&(t+.05)/.05>=1.05/(t+.05)?`text-black`:`text-white`},Gc=[{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 Kc(e,t){return{Icon:e,...Gc[t-1]}}var qc={tab:Kc(se,7),link:Kc(se,7),email:Kc(Se,3),note:Kc(ct,3),task:Kc(Ce,5),message:Kc(be,6),identity:Kc(ae,2),contact:Kc(ae,2),device:Kc(tt,10),application:Kc(R,11),dotfile:Kc(V,4),document:Kc(Le,9)},Jc=[{test:/^image\//,spec:Kc(Be,5)},{test:/^video\//,spec:Kc(Je,11)},{test:/^audio\//,spec:Kc(fe,10)},{test:/pdf$/,spec:Kc(Le,1)},{test:/zip|tar|gzip|7z|rar|compressed/,spec:Kc(Ue,12)},{test:/json|javascript|typescript|xml|html|css|x-sh|python/,spec:Kc(Ee,6)},{test:/^text\//,spec:Kc(Le,12)}],Yc=Kc(rt,6),Xc=Kc(rt,9);function Zc(e){let t=(e.schema||``).split(`/`).pop()||``;if(t===`file`){let t=String(e.metadata?.contentType||``).toLowerCase();return Jc.find(({test:e})=>e.test(t))?.spec||Yc}return qc[t]||Xc}var Qc={3.5:`h-3.5 w-3.5`,4:`h-4 w-4`,5:`h-5 w-5`,10:`h-10 w-10`};function $c(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 el({document:e,size:t=4,chip:n=!1,className:r}){let i=Zc(e),a=e.schema===`data/schema/tab`?$c(e.data):[],[o,s]=(0,J.useState)(0),c=a[o]??null,l=c?(0,X.jsx)(`img`,{src:c,alt:``,loading:`lazy`,onError:()=>s(e=>e+1),className:H(Qc[t],`rounded-xs object-contain`,!n&&`shrink-0`,!n&&r)}):(0,X.jsx)(i.Icon,{className:H(Qc[t],i.color,!n&&`shrink-0`,!n&&r)});return n?(0,X.jsx)(`span`,{className:H(`inline-flex shrink-0 items-center justify-center rounded-md`,t>=10?`p-3`:`p-1`,i.chip,r),children:l}):l}function tl({items:e,onNavigate:t,disabled:n,className:r,label:i=`Tree path`}){let a=(0,J.useRef)(null),o=e[e.length-1]?.path;return(0,J.useEffect)(()=>{let e=a.current;e&&(e.scrollLeft=e.scrollWidth)},[o]),(0,X.jsx)(`nav`,{"aria-label":i,className:H(`min-w-0 flex-1`,r),children:(0,X.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=H(`block max-w-56 truncate rounded px-1.5 py-1`,a?`font-medium text-foreground`:`text-muted-foreground`);return(0,X.jsxs)(`li`,{className:`flex shrink-0 items-center gap-1`,children:[i>0&&(0,X.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/60`,children:`/`}),t&&!a?(0,X.jsx)(`button`,{type:`button`,title:r.path===`/`?`${r.label} (root)`:r.path,disabled:n,onClick:()=>t(r.path),className:H(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,X.jsx)(`span`,{title:r.path===`/`?r.label:r.path,"aria-current":a?`location`:void 0,className:o,children:r.label})]},r.path)})})})}function nl(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 rl={context:(0,X.jsx)(y,{className:`h-3.5 w-3.5`}),directory:(0,X.jsx)(g,{className:`h-3.5 w-3.5`}),backends:(0,X.jsx)(F,{className:`h-3.5 w-3.5`}),relations:(0,X.jsx)(Qe,{className:`h-3.5 w-3.5`})},il={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function al(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function ol(e,t){let n=(0,J.useRef)(null),r=(0,J.useRef)(!1),i=()=>{n.current&&=(clearTimeout(n.current),null)},a=e=>t=>{if(r.current){r.current=!1;return}t.detail>1||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 sl(e,t,n){let r=al(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>sl(e,r,n))??!1}var cl=200;function ll({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,J.useState)(``);return(0,X.jsxs)(`div`,{className:`flex min-h-11 items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 text-sm shadow-elevation-1`,children:[(0,X.jsx)(te,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.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,X.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function ul({node:e,parentPath:t,query:n,selected:r,onToggle:a,onActivate:o,onRowMenu:s,createParent:c,onCreateConfirm:l,onCreateCancel:u,creating:d}){let f=al(t,e.name),p=!!e.children?.length,[m,h]=(0,J.useState)(!1),{handlers:g,guardClick:_}=ol(f,s);if(n&&!sl(e,t,n))return null;let v=c===f,y=m||n.length>0||v,b=r.has(f),x=e.type===`canvas`,S=Nc(e);return(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`div`,{className:H(`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:_(()=>a(f)),onDoubleClick:e=>{e.ctrlKey||e.metaKey||e.shiftKey||e.altKey||e.target.closest(`button,input,textarea,select,a,[contenteditable="true"]`)||(e.preventDefault(),e.stopPropagation(),p?h(e=>!e):o?.(f))},title:f,...g,children:[(0,X.jsx)(`button`,{type:`button`,"aria-label":`${y?`Collapse`:`Expand`} ${e.label||e.name}`,"aria-expanded":p?y:void 0,disabled:!p,className:H(`shrink-0 text-muted-foreground hover:text-foreground`,!p&&`invisible`),onClick:e=>{e.stopPropagation(),e.detail<=1&&h(e=>!e)},children:y?(0,X.jsx)(ce,{className:`w-4 h-4`}):(0,X.jsx)(vt,{className:`w-4 h-4`})}),(0,X.jsx)(i,{icon:S.icon||(x?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:Hc(S.color),className:H(`shrink-0`,!Hc(S.color)&&(x?`text-primary`:`text-muted-foreground`))}),(0,X.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),y&&p||v?(0,X.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[v&&l&&u&&(0,X.jsx)(ll,{busy:d,onConfirm:e=>{h(!0),l(f,e)},onCancel:u}),y&&e.children?.map(e=>(0,X.jsx)(ul,{node:e,parentPath:f,query:n,selected:r,onToggle:a,onActivate:o,onRowMenu:s,createParent:c,onCreateConfirm:l,onCreateCancel:u,creating:d},e.id||e.name))]}):null]})}function dl({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,X.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=Hc(e.color);return(0,X.jsxs)(`div`,{onClick:()=>n(e.name),className:`group relative flex cursor-pointer items-center gap-2 rounded-(--card-radius) bg-card px-3 py-2.5 shadow-elevation-1 transition-all hover:bg-accent/50 hover:shadow`,style:{borderRight:`6px solid ${t||`transparent`}`},children:[(0,X.jsx)(i,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:H(`shrink-0`,!t&&`text-muted-foreground`)}),(0,X.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,X.jsx)(vt,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function fl({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:a,excludeDocumentIds:o}){let[s,c]=(0,J.useState)(`folder`),[l,u]=(0,J.useState)(``),d=l.trim().toLowerCase(),[f,p]=(0,J.useState)(`/`),[m,h]=(0,J.useState)(null),[g,_]=(0,J.useState)(!1),[v,y]=(0,J.useState)([]),[b,x]=(0,J.useState)(!1),[S,C]=(0,J.useState)(``),[w,T]=(0,J.useState)(``),[D,O]=(0,J.useState)(t),k=n?t:D,A=e=>{p(`/`),c(`folder`),C(``),T(``),a?.(`/`),n?n(e):O(e)},[j,ee]=(0,J.useState)(k);k!==j&&(ee(k),p(`/`),c(`folder`)),(0,J.useEffect)(()=>{let e=setTimeout(()=>T(S.trim()),300);return()=>clearTimeout(e)},[S]),(0,J.useEffect)(()=>{let t=!1;async function n(){_(!0);try{let n=await Bt(e,k);t||h(n)}catch{t||h(null)}finally{t||_(!1)}}return n(),()=>{t=!0}},[e,k]),(0,J.useEffect)(()=>{if(s!==`documents`)return;let t=!1,n=k===`directory`?`directory`:Dn,r=k===`context`?`context`:`directory`;async function i(){x(!0);try{let i=w?await mn(e,f,[],{treeName:n,treeType:r,q:w,limit:cl}):await Cn(e,f,n,{limit:cl});t||y(i.payload||[])}catch{t||y([])}finally{t||x(!1)}}return i(),()=>{t=!0}},[e,k,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,X.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,X.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,X.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>A(e),className:H(`flex flex-1 items-center justify-center gap-1.5 rounded px-2 py-1 text-xs transition-colors`,k===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),title:`Browse the ${il[e].toLowerCase()}`,children:[rl[e],(0,X.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,X.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,X.jsx)(vt,{className:`h-3.5 w-3.5`})]})]}),(0,X.jsx)(tl,{items:nl(f,e),onNavigate:M,label:`Folder path`}),(0,X.jsxs)(`div`,{className:`relative`,children:[(0,X.jsx)(mt,{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,X.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,X.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:g?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:H(`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,X.jsx)(ce,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,X.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:m?.children?.length?m.children.map(e=>(0,X.jsx)(ul,{node:e,parentPath:`/`,query:d,selected:new Set([f]),onToggle:M,onActivate:e=>{M(e),c(`documents`)}},e.id||e.name)):(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,X.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,X.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.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,X.jsx)(vt,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,X.jsx)(`span`,{children:`Folders`})]}),(0,X.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,X.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,X.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground`,children:[`[`,k,`]`]}),(0,X.jsx)(tl,{items:nl(f,e),onNavigate:M,label:`Document folder path`})]}),(0,X.jsxs)(`div`,{className:`relative`,children:[(0,X.jsx)(mt,{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,X.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,X.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,X.jsx)(E,{className:`h-3.5 w-3.5`})})]})]}),(0,X.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:b?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):N.length===0?(0,X.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=Gt(e),n=r.has(e.id);return(0,X.jsxs)(`div`,{onClick:()=>i(e.id),className:H(`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,X.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,X.jsx)(el,{document:e,size:3.5}),(0,X.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function pl({onClose:e,onConfirm:t,documentCount:n,fixedWorkspaceName:r,excludeWorkspace:i,multiple:a=!0,saving:o=!1,savingContent:s,sizeClassName:c,tabs:l=[`context`,`directory`],initialTab:u,title:d,confirmLabel:f,backendFolderCreation:p,onConfirmRelation:m,relationWorkspaceName:h,relationPredicates:g,relationExcludeIds:_}){let[v,y]=(0,J.useState)(r?`tree`:`workspace`),[b,x]=(0,J.useState)([]),[S,C]=(0,J.useState)(!r),[w,T]=(0,J.useState)(r??null),D=u&&l.includes(u)?u:l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`,[O,k]=(0,J.useState)(D),A=g?.length?g:[...Tn],[j,ee]=(0,J.useState)(A[0]??`references`),[N,P]=(0,J.useState)(`out`),[F,I]=(0,J.useState)(new Set),[L,te]=(0,J.useState)(null),[ne,re]=(0,J.useState)(`context`),[ie,ae]=(0,J.useState)(!1),oe=O===`pins`?ne:O;(0,J.useEffect)(()=>{if(!w)return;let e=!1;return Ut(w).then(t=>{e||te(t)}).catch(()=>{e||ae(!0)}),()=>{e=!0}},[w]);let R=O===`relations`,[se,le]=(0,J.useState)(null),[ue,de]=(0,J.useState)(!1),[z,fe]=(0,J.useState)(new Set),[pe,me]=(0,J.useState)(``),he=pe.trim().toLowerCase(),{showErrorToast:ge}=Tt(),[ve,ye]=(0,J.useState)(null),[be,xe]=(0,J.useState)(null),[B,Se]=(0,J.useState)(!1);ac(e,!o&&!B);let Ce=ol(`/`,e=>ye(e)),we=e=>!o&&(O===`backends`?p?.canCreate(e)===!0:O!==`pins`&&O!==`relations`),Te=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!w||B||!we(e))){Se(!0);try{let t=`${e===`/`?``:e}/${n}`,r=O===`context`?Dn:O;O===`backends`?await p.create(e,n):await pn(w,t,!0,r),un(w,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:w,treeName:r,cacheInvalidated:!0}}));let i=await Bt(w,O);le(i),fe(e=>a?new Set([...e,t]):new Set([t])),me(``),xe(null)}catch(e){ge(e instanceof Error?e.message:`Failed to create folder`)}finally{Se(!1)}}},[Ee,De]=(0,J.useState)(r);r!==Ee&&(De(r),r||C(!0)),(0,J.useEffect)(()=>{r||Kt().then(e=>x(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>x([])).finally(()=>C(!1))},[r,i]),(0,J.useEffect)(()=>{if(!w||O===`relations`||O===`pins`)return;let e=!1,t=0;async function n(n=!1){let r=++t;n||de(!0);try{let n=await Bt(w,O);!e&&r===t&&le(n)}catch{!e&&r===t&&!n&&le(null)}finally{!e&&r===t&&de(!1)}}let r=e=>{let t=e.detail;t?.workspaceName&&t.workspaceName!==w||t?.treeName&&t.treeName!==O||(t?.cacheInvalidated||un(w,O),n(!0))};return window.addEventListener(`workspace:tree:refresh`,r),n(),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,r)}},[w,O]);let Oe=e=>{e!==w&&(te(null),ae(!1)),k(D),T(e),fe(new Set),I(new Set),y(`tree`)},ke=e=>{I(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Ae=e=>{if(!a){fe(new Set([e]));return}fe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},je=R?F.size>0&&!!m:z.size>0,Me=async()=>{if(!(!w||o||!je)){if(R){await m?.({predicate:j,direction:N,targetIds:Array.from(F)},{workspaceName:h??w});return}await t(Array.from(z),{workspaceName:w,treeName:oe===`context`?Dn:oe,treeType:oe===`context`?`context`:`directory`})}},Pe=n??1;return o&&s?(0,X.jsx)(`div`,{className:H(`flex flex-col overflow-hidden rounded-(--panel-radius) 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,X.jsxs)(`div`,{className:H(`flex flex-col overflow-hidden rounded-(--panel-radius) 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,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(Ne,{className:`h-4 w-4`}),d??(v===`workspace`?`Link to…`:R?`Relate ${Pe} document${Pe===1?``:`s`} to…`:`Link ${Pe} document${Pe===1?``:`s`} to…`)]}),(0,X.jsx)(`button`,{type:`button`,onClick:e,disabled:o||B,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,X.jsx)(E,{className:`h-4 w-4`})})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,X.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-normal`,style:{transform:v===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,X.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,X.jsx)(dl,{workspaces:b,loading:S,onPick:Oe})}),(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,X.jsx)(`button`,{type:`button`,disabled:B,onClick:()=>y(`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,X.jsx)(vt,{className:`h-4 w-4 rotate-180`})}),(l.includes(`context`)||l.includes(`directory`))&&(0,X.jsxs)(`button`,{type:`button`,disabled:B,onClick:()=>{k(`pins`),fe(new Set),xe(null)},className:H(`flex shrink-0 items-center gap-1.5 border-b-2 px-3 py-2 text-xs`,O===`pins`?`border-primary`:`border-transparent text-muted-foreground`),children:[(0,X.jsx)(M,{className:`h-3.5 w-3.5`}),`Pins`]}),l.map(e=>(0,X.jsxs)(`button`,{type:`button`,disabled:B,onClick:()=>{k(e),fe(new Set),xe(null)},className:H(`flex shrink-0 items-center gap-1.5 rounded-t-md border-b-2 px-3 py-2 text-xs font-medium transition-colors`,O===e?`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[rl[e],il[e]]},e))]}),!R&&(0,X.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,X.jsxs)(`div`,{className:`relative`,children:[(0,X.jsx)(mt,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,X.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:pe,onChange:e=>me(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`})]})}),R&&(0,X.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,X.jsx)(`select`,{id:`relation-predicate`,value:j,onChange:e=>ee(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:A.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e))})]}),(0,X.jsx)(`div`,{className:`flex items-center gap-1`,children:[{dir:`out`,label:`This → picked`,hint:`the ${Pe===1?`document`:`documents`} you started from ${j} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${j} the ${Pe===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,X.jsx)(`button`,{type:`button`,title:n,onClick:()=>P(e),className:H(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,N===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!R&&a&&(0,X.jsxs)(`div`,{className:`flex h-10 shrink-0 items-center gap-1.5 overflow-x-auto border-b bg-primary/[0.04] px-3`,children:[!z.size&&(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Selected folders appear here`}),Array.from(z).map(e=>(0,X.jsxs)(`span`,{className:`inline-flex max-w-full shrink-0 items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground`,children:[(0,X.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,X.jsx)(`button`,{type:`button`,onClick:()=>Ae(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,X.jsx)(E,{className:`h-3 w-3`})})]},e))]}),R&&(h??w)&&(0,X.jsx)(fl,{workspaceName:h??w,treeTab:`context`,selectedDocIds:F,onToggleDoc:ke,excludeDocumentIds:_}),O===`pins`&&(0,X.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!L&&!ie&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),ie&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!ie&&L?.length===0&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),L?.filter(e=>e.resolvable!==!1&&l.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(he)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,X.jsxs)(`button`,{type:`button`,"aria-pressed":ne===t&&z.has(e.path),className:H(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,ne===t&&z.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{ne===t?Ae(e.path):(re(t),fe(new Set([e.path])))},children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(M,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,X.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,X.jsx)(`div`,{className:H(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(R||O===`pins`)&&`hidden`),children:ue?(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:H(`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`,z.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:Ce.guardClick(()=>Ae(`/`)),title:`/`,...we(`/`)?Ce.handlers:{},children:[(0,X.jsx)(ce,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,X.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[be===`/`&&(0,X.jsx)(ll,{busy:B,onConfirm:e=>Te(`/`,e),onCancel:()=>xe(null)}),se?.children?.length?se.children.map(e=>(0,X.jsx)(ul,{node:e,parentPath:`/`,query:he,selected:z,onToggle:Ae,onRowMenu:e=>{we(e.path)&&ye(e)},createParent:be,onCreateConfirm:Te,onCreateCancel:()=>xe(null),creating:B},e.id||e.name)):be===`/`?null:(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),v===`tree`&&(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:R?`${F.size} document${F.size===1?``:`s`} selected`:`${z.size} path${z.size===1?``:`s`} selected`}),(0,X.jsx)(G,{size:`sm`,onClick:Me,disabled:!je||o||B,children:o?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(go,{className:`mr-1.5 h-3.5 w-3.5`}),R?`Relating…`:`Linking…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Ne,{className:`mr-1 h-3.5 w-3.5`}),R?`Relate`:f??`Link`]})})]}),ve&&(0,X.jsx)(vc,{anchor:{x:ve.clientX,y:ve.clientY},onClose:()=>ye(null),items:[{id:`new-folder`,label:`New folder in ${ve.path}`,icon:_e,run:()=>xe(ve.path)}]})]})}var ml=`workspace:relations:refresh`;function hl(){window.dispatchEvent(new CustomEvent(ml))}function gl({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:f=!1,relationSubjectId:p,frame:m,children:h,maximized:g,onMaximizedChange:_}){let v=Fi(),[y,b]=(0,J.useState)(`portrait`),[x,S]=(0,J.useState)(!1),C=g??x,w=e=>{S(e),_?.(e)},[T,D]=(0,J.useState)(!1),[O,k]=(0,J.useState)(!1),[A,j]=(0,J.useState)(!1),ee=o||A;ac(()=>D(!1),T&&!ee),ac(()=>w(!1),C&&!T);let M=(0,J.useRef)(null),N=Lo(),{showSuccessToast:P,showErrorToast:F}=Tt(),I=N&&!u&&!C,[L,te]=(0,J.useState)(!1),ne=!u&&!C&&!m&&!L;(0,J.useEffect)(()=>{T&&M.current?.scrollIntoView({behavior:`smooth`,inline:`end`,block:`nearest`})},[T]);let re=async(e,t)=>{if(!(!r||ee)){j(!0);try{let a=await r({...t,path:e[0]}),o=e.slice(1);a.length&&o.length&&await Promise.all(o.map(e=>Zt(t.workspaceName,e,a,t.treeName,t.treeType))),P(c),n?.(),i&&v(nc({...t,path:e[0]}),{replace:!0})}catch(e){F(e instanceof Error?e.message:`Failed to save`)}finally{j(!1)}}},ie=async e=>{if(!(!p||!l||e.targetIds.length===0)){k(!0);try{await kn(l,p,e.predicate,e.targetIds,e.direction),P(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),hl(),D(!1)}catch(e){F(e instanceof Error?e.message:`Failed to create relations`)}finally{k(!1)}}},ae=C?T?{flex:`1 1 auto`,minWidth:0,height:`100%`}:{width:`100%`,height:`100%`}:u?{height:`100%`,flexShrink:0}:I?void 0:y===`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},oe=!!(p&&l),R=r&&T&&(0,X.jsx)(pl,{onClose:()=>D(!1),onConfirm:re,fixedWorkspaceName:l,saving:ee||O,savingContent:s,tabs:oe?[`context`,`directory`,`relations`]:[`context`,`directory`],onConfirmRelation:oe?ie:void 0,relationWorkspaceName:l,relationExcludeIds:oe?new Set([p]):void 0,sizeClassName:m?`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}),se=(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>b(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,X.jsx)(d,{className:`h-4 w-4`})}),r&&(typeof h==`function`?(0,X.jsx)(`button`,{type:`button`,onClick:()=>D(!0),disabled:!a||ee,className:`flex h-8 w-8 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,"aria-label":ee?`Saving…`:`Add relations / Link to…`,title:`Add relations / Link to…`,children:(0,X.jsx)(Ne,{className:`h-4 w-4`})}):(0,X.jsx)(G,{size:`sm`,variant:`outline`,onClick:()=>D(!0),disabled:!a||ee,children:ee?`Saving…`:`Save / Link to…`})),(0,X.jsx)(`button`,{type:`button`,onClick:()=>m&&!C?m.onToggleExpanded():w(!C),className:H(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground`,typeof h==`function`&&`flex h-8 w-8 items-center justify-center`,!C&&!m&&`max-md:hidden`),"aria-label":m&&!C?m.expanded?`Card size`:`Expand to full width`:C?`Restore`:`Maximize`,title:m&&!C?m.expanded?`Card size`:`Expand to full width`:C?`Restore`:`Maximize`,children:C||m?.expanded?(0,X.jsx)(ve,{className:`h-4 w-4`}):(0,X.jsx)(qe,{className:`h-4 w-4`})}),n&&(0,X.jsx)(`button`,{type:`button`,onClick:n,disabled:ee,className:H(`rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 touch-target`,typeof h==`function`&&`flex h-8 w-8 items-center justify-center`),"aria-label":`Close`,children:(0,X.jsx)(E,{className:`h-4 w-4`})})]}),ce=(0,X.jsxs)(`div`,{style:{...m&&!C?{width:`100%`,height:`100%`,minWidth:0}:ae,"--document-reading-width":C&&!f?`48rem`:`100%`},onAnimationEnd:e=>{ne&&e.target===e.currentTarget&&te(!0)},className:H(`flex flex-col overflow-hidden`,m&&!C?`strip-document-card`:`rounded-(--card-radius) border bg-card shadow-elevation-4 transition-[width,height]`,u&&!C&&!m&&`w-full`,I&&`fixed inset-2 z-40 shadow-elevation-5`,ne&&`animate-card-in`),children:[typeof h!=`function`&&(0,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,X.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,X.jsx)(`span`,{className:`truncate`,children:e})]}),se]}),(0,X.jsx)(qo.Provider,{value:()=>w(!C),children:(0,X.jsx)(`div`,{className:H(`min-h-0 flex-1 overflow-y-auto`,C&&!f&&typeof h!=`function`&&`mx-auto w-full max-w-3xl`),children:m&&R?R:typeof h==`function`?h(se):h})})]});return C?(0,uo.createPortal)((0,X.jsxs)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center gap-4 bg-scrim p-4 max-md:p-2`,children:[ce,R&&(0,X.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:R})]}),document.body):(0,X.jsxs)(X.Fragment,{children:[ce,!m&&R&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!ee&&D(!1),"aria-hidden":!0}),(0,X.jsx)(`div`,{ref:M,className:`relative shrink-0 md:z-panel md:ml-2 md:pr-2 max-md:fixed max-md:bottom-2 max-md:left-2 max-md:right-2 max-md:top-2 max-md:z-card-overlay max-md:animate-fade-in`,children:R})]})]})}function _l({onSearch:e,onDraftChange:t,inputRef:n,label:r=`Search documents`,clearOnSubmit:i=!0,showSubmitButton:a=!0}){return(0,X.jsxs)(`form`,{className:`canvas-search-input`,role:`search`,onSubmit:n=>{n.preventDefault();let r=n.currentTarget.elements.namedItem(`query`),a=r.value.trim();a&&(e(a),i&&(r.value=``,t?.(``)))},children:[(0,X.jsx)(`input`,{ref:n,name:`query`,type:`search`,"aria-label":r,placeholder:r,autoComplete:`off`,enterKeyHint:`search`,onChange:e=>t?.(e.target.value),onKeyDown:e=>{e.key===`Enter`&&e.nativeEvent.isComposing&&e.preventDefault()}}),a&&(0,X.jsx)(`button`,{type:`submit`,className:`canvas-nav-button`,"aria-label":`Run search`,title:`Run search`,children:(0,X.jsx)(mt,{size:17})})]})}function vl({queries:e,onRemoveQuery:t,scope:n=`path`,onScopeChange:r}){return(0,X.jsxs)(`div`,{className:`canvas-search-options`,children:[r&&(0,X.jsxs)(`div`,{className:`canvas-search-scopes`,"aria-label":`Search scope`,children:[(0,X.jsx)(`span`,{children:`Search in`}),(0,X.jsx)(`button`,{type:`button`,"aria-pressed":n===`path`,onClick:()=>r(`path`),children:`This path`}),(0,X.jsx)(`button`,{type:`button`,"aria-pressed":n===`workspace`,onClick:()=>r(`workspace`),children:`Workspace`})]}),e.length>0&&(0,X.jsxs)(`div`,{className:`canvas-search-queries`,"aria-label":`Active searches`,children:[e.map((e,n)=>(0,X.jsxs)(`span`,{className:`canvas-search-query`,children:[(0,X.jsx)(mt,{size:12,"aria-hidden":`true`}),(0,X.jsx)(`span`,{title:e,children:e}),t&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>t(n),"aria-label":`Remove search: ${e}`,children:(0,X.jsx)(E,{size:14})})]},`${e}-${n}`)),t&&e.length>1&&(0,X.jsx)(`button`,{type:`button`,onClick:()=>t(-1),className:`canvas-search-clear`,children:`Clear all`})]})]})}function yl({children:e,accentColor:t}){return(0,X.jsxs)(`div`,{className:`canvas-navigation-tabs`,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,className:`canvas-tab-divider`,style:t?{backgroundColor:t}:void 0}),e]})}function bl({workspace:e,workspaceIcon:t,tree:n,path:r,document:a,section:o,onBack:s,onBrowseWorkspaces:c,onBrowseTree:l,onNavigatePath:u,onDocument:d,onSection:f,onFilter:p,filtersActive:m,filtersOpen:h,onAdd:g,search:_,onDraftChange:v,tabs:y,accentColor:b,actions:x}){let[S,C]=(0,J.useState)(!1),[w,T]=(0,J.useState)(!1),D=(0,J.useRef)(null),O=(0,J.useRef)(null),k=(0,J.useRef)(null),A=(0,J.useRef)(!1),j=JSON.stringify([e,n,r,a]),[ee,M]=(0,J.useState)(j);ee!==j&&(M(j),C(!1)),(0,J.useEffect)(()=>{S?O.current?.focus():(D.current&&(D.current.scrollLeft=D.current.scrollWidth,T(D.current.scrollLeft>1)),A.current&&=(k.current?.focus(),!1))},[S,j,o]);let N=()=>{A.current=!0,C(!1),v?.(``)},P=S?N:s??l,F=nl(r,e).slice(1),I=(e,t,n,r,i=!1)=>n?(0,X.jsx)(`button`,{type:`button`,className:t,onClick:n,title:r,"aria-current":i?`location`:void 0,children:e}):(0,X.jsx)(`span`,{className:`canvas-address-label ${t}`,title:r,"aria-current":i?`location`:void 0,children:e});return(0,X.jsxs)(`header`,{className:`canvas-navigation${y?` has-tabs`:``}`,style:b?{borderTopColor:b}:void 0,children:[y&&(0,X.jsx)(yl,{accentColor:b,children:y}),(0,X.jsxs)(`div`,{className:`canvas-address-row`,children:[(0,X.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,"aria-label":S?`Back to address`:`Back to previous view`,title:S?`Back to address`:`Back to previous view`,disabled:!S&&!s&&!l,onClick:P,children:(0,X.jsx)(lt,{size:19})}),(0,X.jsxs)(`div`,{className:`canvas-address-field`,onDoubleClick:e=>{_&&!e.target.closest(`button`)&&C(!0)},onKeyDown:e=>{e.key===`Escape`&&S&&(e.preventDefault(),e.stopPropagation(),N())},children:[S&&_?(0,X.jsx)(_l,{inputRef:O,onSearch:_.onSearch,onDraftChange:v,clearOnSubmit:!_.localOnly,showSubmitButton:!1,label:_.queries.length?`Refine search…`:`Search documents…`}):(0,X.jsxs)(X.Fragment,{children:[I((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(i,{icon:t||`ph:stack-fill`,className:`h-4 w-4 shrink-0`,"aria-hidden":`true`}),(0,X.jsx)(`span`,{className:`truncate`,children:e})]}),`canvas-address-workspace`,c,`Browse workspaces`),(0,X.jsxs)(`div`,{ref:D,className:`canvas-address-crumbs${w?` is-scrolled`:``}`,onScroll:e=>T(e.currentTarget.scrollLeft>1),role:`navigation`,"aria-label":`Canvas address`,tabIndex:0,onKeyDown:e=>{e.key===`Enter`&&e.target===e.currentTarget&&_&&C(!0)},children:[n&&I(`[${n}]`,`canvas-address-tree`,l,`Browse tree: ${n}`),I(`:/`,`canvas-address-root`,u?()=>u(`/`):void 0,`Go to tree root`),F.map((e,t)=>(0,X.jsxs)(`span`,{className:`canvas-address-segment`,children:[t>0&&(0,X.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),I(e.label,``,u?()=>u(e.path):void 0,e.path,!a&&t===F.length-1)]},e.path)),a&&(0,X.jsxs)(`span`,{className:`canvas-address-segment`,children:[(0,X.jsx)(`span`,{"aria-hidden":`true`,children:F.length?`/`:``}),I(a,``,d,a)]}),o&&I(`#${o}`,`canvas-address-section`,f,o,!0)]})]}),_&&(0,X.jsxs)(`button`,{ref:k,type:`button`,className:`canvas-nav-button canvas-address-search`,onClick:S?N:()=>C(!0),"aria-label":S?`Close search`:`Search this canvas`,"aria-expanded":S,title:S?`Close search`:`Search this canvas`,children:[(0,X.jsx)(mt,{size:17}),_.queries.length>0&&(0,X.jsx)(`span`,{className:`canvas-nav-dot`})]})]}),p&&(0,X.jsxs)(`button`,{type:`button`,className:`canvas-nav-button canvas-filter-button`,onClick:p,"aria-label":m?`Filters active`:`Filters`,"aria-expanded":!!h,"data-active":!!m,title:m?`Filters active`:`Filters`,children:[(0,X.jsx)(ot,{size:19}),m&&(0,X.jsx)(`span`,{className:`canvas-nav-dot`})]}),g&&(0,X.jsx)(`button`,{type:`button`,className:`canvas-nav-button canvas-add-button`,onClick:g,"aria-label":`Add here`,title:`Add here`,children:(0,X.jsx)(ze,{size:21})}),x]}),S&&_&&(0,X.jsxs)(`div`,{className:`canvas-search-dropdown`,children:[(0,X.jsxs)(`div`,{className:`canvas-search-heading`,children:[(0,X.jsx)(`span`,{children:_.localOnly?`Filter documents on this page`:v?`Type to filter this page · Enter to search all results`:`Search text or an exact ID, e.g. @id:123`}),(0,X.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,onClick:N,"aria-label":`Close search`,children:(0,X.jsx)(E,{size:16})})]}),(0,X.jsx)(vl,{..._})]}),!S&&_&&_.queries.length>0&&(0,X.jsx)(`div`,{className:`px-3 pb-2`,children:(0,X.jsx)(vl,{queries:_.queries,onRemoveQuery:_.onRemoveQuery})})]})}function xl({tabs:e,active:t,onChange:n,className:r=``,iconOnly:i=!1}){return(0,X.jsx)(`div`,{className:`flex gap-1 border-b overflow-x-auto ${r}`,children:e.map(e=>{let r=e.icon;return(0,X.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,X.jsx)(r,{className:`h-3.5 w-3.5`}),(!i||!r)&&e.label]},e.id)})})}function Sl({workspaceId:e,document:t,className:n}){let r=tc(t);return r?(0,X.jsx)(r,{workspaceId:e,document:t,className:n}):(0,X.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var Cl=e=>`${bt.workspaces}/${encodeURIComponent(e)}/messages`,wl=e=>W.get(`${Cl(e)}/accounts`),Tl=(e,t)=>W.get(`${Cl(e)}/reply-target/${t}`),El=(e,t)=>W.post(`${Cl(e)}/send`,t),Dl=(e,t)=>W.get(`${Cl(e)}/whatsapp/${encodeURIComponent(t)}/connection`),Ol=(e,t)=>W.get(`${Cl(e)}/outbox/${encodeURIComponent(t)}`),kl=(e,t)=>W.delete(`${Cl(e)}/whatsapp/${encodeURIComponent(t)}/connection`),Al=(e,t)=>W.get(`${Cl(e)}/thread/${t}`),jl=new cr({html:!1});function Ml(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`
10
+ `;case`paragraph_close`:case`heading_close`:return`
11
+
12
+ `;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(jl.parse(e,{})).trim()}function Nl(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 Pl={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function Fl({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${Nl(e)}:smtp-test:${i?.address}`:Nl(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,J.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,J.useState)(null),[m,h]=(0,J.useState)([]),[g,_]=(0,J.useState)(navigator.onLine);(0,J.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,J.useRef)(!1),[y,b]=(0,J.useState)(!1),[x,S]=(0,J.useState)(!1),[C,w]=(0,J.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,J.useState)(``),[D,O]=(0,J.useState)(null);(0,J.useEffect)(()=>{let n=!0;return Promise.all([wl(e),t?Tl(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,J.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`,ee=!!u.images?.length,M=!!u.text.trim(),N=e=>d(t=>({...t,...e})),P=async()=>{S(!0),E(``),w(!0);let t=A?M?u:{...u,html:void 0}:{...u,text:j?Ml(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await Ol(e,u.requestId).catch(n=>{if(n.statusCode===404)return El(e,t);throw n}):await El(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,te=a?`Send test email`:t?s?Pl.forward:Pl[u.replyAll?`replyAll`:`reply`]:`New message`,ne=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,X.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?`${te} to message`:`New message`,children:[(0,X.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,X.jsx)(`strong`,{className:`text-sm`,children:te}),(0,X.jsx)(G,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,X.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&&N({driver:t.driver,address:t.address,to:[],cc:[],bcc:[],subject:void 0,target:void 0,images:void 0,replyAll:!1})},children:[(0,X.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,X.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,X.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,X.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,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,X.jsx)(U,{"aria-label":`To`,disabled:L,value:u.to?.join(`, `)||``,onChange:e=>N({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&I&&(0,X.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,X.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,X.jsx)(U,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:L,value:u[e]?.join(`, `)||``,onChange:t=>N({[e]:[t.target.value]})})]},e)),(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,X.jsx)(U,{"aria-label":`Subject`,disabled:L,value:u.subject||``,placeholder:ne,onChange:e=>N({subject:e.target.value||void 0})})]}),t&&!s&&(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,X.jsxs)(`label`,{className:`flex gap-2`,children:[(0,X.jsx)(`input`,{type:`checkbox`,disabled:L,checked:u.replyAll||!1,onChange:e=>{let t=e.target.checked?f?.allRecipients:f?.recipients;N({replyAll:e.target.checked,...t?{to:t.to,cc:t.cc}:{}})}}),`Reply all`]}),(0,X.jsxs)(`label`,{className:`flex gap-2`,children:[(0,X.jsx)(`input`,{type:`checkbox`,disabled:L,checked:u.quote||!1,onChange:e=>N({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,X.jsx)(Ln,{format:`html`,editable:!L,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>N({html:e,text:t.slice(0,32e3)})})]}):(0,X.jsxs)(X.Fragment,{children:[!t&&(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,X.jsx)(U,{"aria-label":`Conversation`,disabled:L,value:u.target||``,onChange:e=>N({target:e.target.value})})]}),j?(0,X.jsx)(Ln,{format:`markdown`,editable:!L,value:u.text,placeholder:`Write a message…`,onChange:e=>N({text:e.slice(0,32e3)})}):(0,X.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=>N({text:e.target.value}),placeholder:`Write a message…`})]}),(A||j)&&(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,X.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,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,X.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,X.jsx)(G,{size:`sm`,variant:`ghost`,disabled:L,onClick:()=>N({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),j&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,X.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,X.jsx)(G,{size:`sm`,disabled:x||y||!C&&(!k||!M&&!ee&&!(A&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void P(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,X.jsx)(G,{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,X.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 Il(e){let t=(0,J.useRef)(null),n=(0,J.useRef)(e.onClose);return(0,J.useEffect)(()=>{n.current=e.onClose}),(0,J.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,X.jsx)(`dialog`,{ref:t,"aria-label":e.replyToDocumentId?`${e.mode===`forward`?`Forward`:e.mode===`replyAll`?`Reply all`:`Reply`} message`:`Send test email`,className:`m-auto w-[calc(100%-2rem)] max-w-3xl max-h-[90dvh] overflow-y-auto rounded-(--panel-radius) border bg-card p-0 text-foreground shadow-elevation-4 backdrop:bg-black/40`,onKeyDown:e=>e.stopPropagation(),onCancel:e=>{e.preventDefault(),e.stopPropagation(),n.current()},children:(0,X.jsx)(Fl,{...e})})}function Ll({workspaceId:e,documentId:t}){let[n,r]=(0,J.useState)(null),[i,a]=(0,J.useState)(``),[o,s]=(0,J.useState)({}),[c,l]=(0,J.useState)(null),u=(0,J.useCallback)(async()=>{try{let n=await Al(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,J.useEffect)(()=>{let n=!0;Al(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(ml,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(ml,i)}},[e,t,u]),i?(0,X.jsxs)(`div`,{className:`p-3`,children:[(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,X.jsx)(G,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,X.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,X.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,X.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,X.jsx)(G,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,X.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,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Showing up to 200 linked messages.`}),n.documents.map(r=>{let i=Gt(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?[Gt(t).title]:[]}),p=o[Number(r.id)]??Number(r.id)===t;return(0,X.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,X.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,X.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,X.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,X.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,X.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,X.jsx)(G,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,X.jsx)(Sl,{workspaceId:e,document:r})]},r.id)}),c&&(0,X.jsx)(Il,{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}`)]})}function Rl(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(`
13
+ `)+(e.length>3?`\n…and ${e.length-3} more failed file${e.length===4?``:`s`}.`:``)}var zl=`h-full w-[380px] max-w-[90vw] max-md:w-full`;function Bl({onClose:e,children:t}){return(0,uo.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-stretch justify-end bg-scrim animate-fade-in`,onClick:e,children:(0,X.jsx)(`div`,{className:`h-full p-2 max-md:w-full max-md:p-1`,onClick:e=>e.stopPropagation(),children:t})}),window.document.body)}var Vl=[{mode:`copy`,label:`Copy to`,icon:(0,X.jsx)(u,{className:`h-3.5 w-3.5`})},{mode:`move`,label:`Move to`,icon:(0,X.jsx)(Te,{className:`h-3.5 w-3.5`})},{mode:`delete`,label:`Delete from`,icon:(0,X.jsx)(pe,{className:`h-3.5 w-3.5`})}],Hl=[{value:`rename`,label:`Rename mine (file-1.ext)`},{value:`overwrite`,label:`Overwrite the existing file`},{value:`error`,label:`Skip the document`}],Ul=`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 Wl(e){return e.driver===`cacache`?pt:e.config?.remote===!0?p:F}function Gl({workspaceId:e,documentCount:t,initialMode:n=`copy`,defaultFilename:r=``,onConfirm:i,onClose:a,saving:o=!1,sizeClassName:s,deleteFrom:c,progress:l,stopping:d=!1,onStop:f}){let{showErrorToast:p}=Tt(),[m,h]=(0,J.useState)(!1);ac(a,!o&&!m);let[_,v]=(0,J.useState)(n),[y,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(null),[w,T]=(0,J.useState)(()=>new Set(n===`delete`&&c?[c.backend]:[])),[D,O]=(0,J.useState)(!1),[k,A]=(0,J.useState)(``),[j,ee]=(0,J.useState)(r),[M,N]=(0,J.useState)(`rename`);(0,J.useEffect)(()=>{let t=!1;return an(e).then(e=>{if(t)return;b(e.filter(e=>e.kind===`storage`));let n=new Set(e.filter(e=>e.kind===`storage`&&e.enabled!==!1&&e.config?.readOnly!==!0&&e.config?.supported!==!1).map(e=>e.address));T(e=>new Set([...e].filter(e=>n.has(e))))}).catch(e=>{t||S(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let P=_===`move`,I=e=>e.enabled===!1?`disabled`:e.config?.readOnly===!0?`read-only`:e.config?.supported===!1?`unsupported`:null,L=(0,J.useMemo)(()=>(y||[]).filter(e=>!I(e)).map(e=>e.address),[y,_]),te=e=>{v(e),T(t=>{let n=(y||[]).filter(e=>e.enabled!==!1&&e.config?.readOnly!==!0&&e.config?.supported!==!1).map(e=>e.address),r=[...t].filter(e=>n.includes(e));return new Set(e===`move`?r.slice(0,1):r)})},ne=e=>{T(t=>{if(P)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})},re=(0,J.useMemo)(()=>(y||[]).filter(e=>w.has(e.address)&&yn(e)),[y,w]),ie=_!==`delete`&&re.length>0,ae=e=>{let t=on(e,y||[]),n=t&&y?.find(e=>e.address===t.address);return!!n&&!I(n)&&_!==`delete`&&!o},oe=async(t,n)=>{let r=on(t,y||[]);if(!r||!ae(t))throw Error(`Choose a writable file backend folder`);await nn(e,r.driver,r.address,[[r.key,n].filter(Boolean).join(`/`)])},R=e=>{h(!1);let t=sn(e[0]||``,y||[]),n=t?(y||[]).find(e=>e.address===t.address):null;if(!t||!n){p(`Pick a folder inside a storage backend`);return}if(I(n)){p(`${n.address} is ${I(n)}`);return}if(!yn(n)){p(`${n.address} does not keep folders — objects are stored by content`);return}A(t.key),T(e=>P?new Set([t.address]):new Set([...e,t.address]))},se=async()=>{w.size===0||o||await i([...w],_,{keepDocument:D,folder:ie?k.trim():``,filename:ie&&t===1?j.trim():``,onConflict:M})},ce=t,le=ce===1?``:`s`,ue=_===`delete`?`Delete ${ce} document${le} from…`:`${_===`move`?`Move`:`Copy`} ${ce} document${le} to…`,de=_===`delete`?`Delete from`:_===`move`?`Move to`:`Copy to`,z=w.size===0?de.split(` `)[0]:`${de} ${w.size} backend${w.size===1?``:`s`}`;return(0,X.jsxs)(`div`,{className:H(`flex flex-col overflow-hidden rounded-(--panel-radius) 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,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(F,{className:`h-4 w-4`}),ue]}),(0,X.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,X.jsx)(E,{className:`h-4 w-4`})})]}),(0,X.jsx)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:Vl.map(({mode:e,label:t,icon:n})=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>te(e),disabled:o,className:H(`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`,_===e?e===`delete`?`border-destructive text-destructive`:`border-primary text-foreground`:`border-transparent text-muted-foreground hover:text-foreground`),children:[n,t]},e))}),(0,X.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:[x&&(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-destructive`,children:x}),!y&&!x&&(0,X.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading backends…`}),y?.length===0&&(0,X.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`No storage backends configured.`}),y?.map(e=>{let t=Wl(e),n=I(e),r=w.has(e.address),i=e.config?.remote===!0;return(0,X.jsxs)(`div`,{onClick:()=>!n&&!o&&ne(e.address),className:H(`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?_===`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,X.jsx)(`input`,{type:P?`radio`:`checkbox`,checked:r,disabled:!!n||o,onChange:()=>ne(e.address),onClick:e=>e.stopPropagation(),className:`h-4 w-4 shrink-0 accent-primary`,"aria-label":e.address}),(0,X.jsx)(t,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,X.jsx)(`span`,{className:`block truncate font-medium`,children:e.config?.label||e.address}),(0,X.jsxs)(`span`,{className:`block truncate font-mono text-[10px] text-muted-foreground`,children:[e.driver,` · `,e.address]})]}),i&&(0,X.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,X.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}`)}),_===`delete`&&(0,X.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,X.jsx)(`input`,{type:`checkbox`,checked:D,onChange:e=>O(e.target.checked),disabled:o,className:`mt-0.5 h-3.5 w-3.5 accent-destructive`}),(0,X.jsxs)(`span`,{children:[`Keep the index entry when its `,(0,X.jsx)(`strong`,{children:`last`}),` copy is deleted.`,(0,X.jsx)(`span`,{className:`block text-muted-foreground`,children:`Otherwise the document moves to workspace Trash once no locations remain.`})]})]}),ie&&(0,X.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-md border px-3 py-2`,children:[(0,X.jsxs)(`p`,{className:`text-xs font-medium`,children:[`Destination on `,re.map(e=>e.config?.label||e.address).join(`, `)]}),(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`label`,{htmlFor:`backend-transfer-folder`,className:`text-[11px] text-muted-foreground`,children:`Folder (relative to the backend root)`}),(0,X.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,X.jsx)(U,{id:`backend-transfer-folder`,value:k,onChange:e=>A(e.target.value),placeholder:`/`,disabled:o,className:`h-9 font-mono text-xs`}),(0,X.jsx)(G,{type:`button`,variant:`outline`,size:`icon`,className:`h-9 w-9 shrink-0`,onClick:()=>h(!0),disabled:o,"aria-label":`Browse backend folders`,title:`Browse…`,children:(0,X.jsx)(g,{className:`h-4 w-4`})})]})]}),t===1?(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`label`,{htmlFor:`backend-transfer-filename`,className:`text-[11px] text-muted-foreground`,children:`File name`}),(0,X.jsx)(U,{id:`backend-transfer-filename`,value:j,onChange:e=>ee(e.target.value),placeholder:r||`keeps the document's own name`,disabled:o,className:`h-9 font-mono text-xs`})]}):(0,X.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Each document keeps its own file name and extension.`}),(0,X.jsxs)(`div`,{className:`space-y-1`,children:[(0,X.jsx)(`label`,{htmlFor:`backend-transfer-conflict`,className:`text-[11px] text-muted-foreground`,children:`If a different file already has that name`}),(0,X.jsx)(`select`,{id:`backend-transfer-conflict`,className:Ul,value:M,onChange:e=>N(e.target.value),disabled:o,children:Hl.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),_===`move`&&L.length>0&&(0,X.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.`})]}),o&&l&&(0,X.jsxs)(`div`,{role:`status`,className:`flex items-center justify-between gap-2 border-t px-4 py-2 text-xs`,children:[(0,X.jsxs)(`span`,{children:[d?`Stopping after current file`:`Processing`,` · `,l.completed,`/`,l.total]}),f&&(0,X.jsx)(G,{size:`sm`,variant:`outline`,onClick:f,disabled:d,children:`Stop`})]}),(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-t px-4 py-3`,children:[(0,X.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[w.size,` backend`,w.size===1?``:`s`,` selected`]}),(0,X.jsx)(G,{size:`sm`,variant:_===`delete`?`destructive`:`default`,onClick:se,disabled:w.size===0||o,children:o?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(go,{className:`mr-1.5 h-3.5 w-3.5`}),`Working…`]}):(0,X.jsxs)(X.Fragment,{children:[_===`delete`?(0,X.jsx)(pe,{className:`mr-1 h-3.5 w-3.5`}):_===`move`?(0,X.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}):(0,X.jsx)(u,{className:`mr-1 h-3.5 w-3.5`}),z]})})]}),_===`delete`&&(0,X.jsxs)(`div`,{className:`flex items-start gap-2 border-t bg-destructive/5 px-4 py-2 text-[11px] text-muted-foreground`,children:[(0,X.jsx)(C,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,X.jsx)(`span`,{children:c&&w.has(c.backend)?`Deletes selected files in ${c.backend}/${c.folder}. Copies in other folders are kept.${w.size>1?` Other selected backends are also targeted.`:` Copies on other backends are kept.`}`:`Deletes the file data from the selected backends. Copies on other backends are untouched.`})]}),m&&(0,X.jsx)(Bl,{onClose:()=>h(!1),children:(0,X.jsx)(pl,{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:ae,create:oe},onConfirm:R,onClose:()=>h(!1)})})]})}function Kl({tags:e,onChange:t,placeholder:n=`Add tag, press Enter`,suggestions:r=[]}){let[i,a]=(0,J.useState)(``),[o,s]=(0,J.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,X.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,X.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs`,children:[n,(0,X.jsx)(`button`,{type:`button`,onClick:()=>t(e.filter(e=>e!==n)),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${n}`,children:(0,X.jsx)(E,{className:`h-3 w-3`})})]},n)),(0,X.jsxs)(`div`,{className:`relative flex-1 min-w-[8ch]`,children:[(0,X.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,X.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,X.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))})]})]})}var ql=e(lr(),1),Jl=`#8b5cf6`,Yl=`https://nominatim.openstreetmap.org`,Xl=700,Zl=e=>Math.round(e*1e6)/1e6;function Ql(){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:${Jl};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 ql.default.divIcon({html:e,className:`canvas-map-pick`,iconSize:[28,28],iconAnchor:[14,28]})}function $l({initial:e,onPick:t,onClose:n}){let r=(0,J.useRef)(null),i=(0,J.useRef)(null),a=(0,J.useRef)(null),o=(0,J.useRef)(null);(0,J.useEffect)(()=>()=>o.current?.abort(),[]);let[s,c]=(0,J.useState)(e?{lat:e.lat,lon:e.lon}:null),[l,u]=(0,J.useState)(``),[d,f]=(0,J.useState)([]),[p,m]=(0,J.useState)(!1),[h,g]=(0,J.useState)(null),[_,v]=(0,J.useState)(!1),[y,x]=(0,J.useState)(!1),[S,C]=(0,J.useState)(!1);(0,J.useEffect)(()=>{let e=requestAnimationFrame(()=>C(!0));return()=>cancelAnimationFrame(e)},[]),ac(n);let w=(0,J.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let o=ql.default.latLng(e,t);a.current?a.current.setLatLng(o):(a.current=ql.default.marker(o,{icon:Ql(),draggable:!0,autoPan:!0}).addTo(r),a.current.on(`dragend`,()=>{let e=a.current.getLatLng();c({lat:Zl(e.lat),lon:Zl(e.lng)})})),c({lat:Zl(e),lon:Zl(t),...n?{label:n}:{}})},[]);(0,J.useEffect)(()=>{let t=r.current;if(!t||i.current)return;let n=ql.default.map(t,{center:e?[e.lat,e.lon]:[20,0],zoom:e?13:2,worldCopyJump:!0,zoomControl:!0});ql.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`&copy; OpenStreetMap contributors`,maxZoom:19}).addTo(n),i.current=n,e&&w(e.lat,e.lon),n.on(`click`,e=>w(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,J.useEffect)(()=>{if(!s||s.label)return;let{lat:e,lon:t}=s,n=new AbortController,r=setTimeout(()=>{v(!0),fetch(`${Yl}/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))},Xl);return()=>{clearTimeout(r),n.abort()}},[s]);let T=(0,J.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(`${Yl}/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]),D=(0,J.useCallback)(()=>{if(!navigator.geolocation){g(`This browser has no geolocation`);return}x(!0),g(null),navigator.geolocation.getCurrentPosition(e=>{x(!1),i.current?.setView([e.coords.latitude,e.coords.longitude],16),w(e.coords.latitude,e.coords.longitude)},()=>{x(!1),g(`Could not read your location. Search or click the map instead`)},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})},[w]),O=(0,J.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(ql.default.latLngBounds([a[0],a[2]],[a[1],a[3]]),{maxZoom:16}):t.setView([n,r],15),w(n,r,e.display_name),f([])},[w]);return(0,uo.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:H(`fixed inset-0 z-[60] bg-scrim transition-opacity duration-normal`,S?`opacity-100`:`opacity-0`),onClick:n}),(0,X.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Pick a location on the map`,className:H(`fixed inset-y-0 right-0 z-[61] flex w-[min(560px,100vw)] flex-col overflow-hidden rounded-(--panel-radius) bg-background shadow-elevation-4 transition-transform duration-normal ease-out`,S?`translate-x-0`:`translate-x-full`),children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(Ie,{className:`h-4 w-4 text-info`}),`Custom geotag`]}),(0,X.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,X.jsx)(E,{className:`h-4 w-4`})})]}),(0,X.jsxs)(`div`,{className:`relative z-10 shrink-0 border-b px-3 py-2`,children:[(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsxs)(`div`,{className:`relative flex-1`,children:[(0,X.jsx)(mt,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,X.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(),T())},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,X.jsx)(`button`,{type:`button`,onClick:D,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,X.jsx)(ut,{className:`h-3.5 w-3.5 animate-spin`}):(0,X.jsx)(He,{className:`h-3.5 w-3.5`})}),(0,X.jsxs)(`button`,{type:`button`,onClick:T,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,X.jsx)(ut,{className:`h-3.5 w-3.5 animate-spin`}):(0,X.jsx)(mt,{className:`h-3.5 w-3.5`}),`Search`]})]}),h&&(0,X.jsx)(`p`,{role:`status`,className:`mt-1 text-xs text-warning`,children:h}),d.length>0&&(0,X.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,X.jsx)(`button`,{type:`button`,onClick:()=>O(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,X.jsxs)(`div`,{className:`relative isolate z-0 min-h-0 flex-1`,children:[(0,X.jsx)(`div`,{ref:r,className:`h-full w-full`}),!s&&(0,X.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-3 z-[1000] flex justify-center`,children:(0,X.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,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2`,children:[(0,X.jsx)(`div`,{className:`min-w-0 text-xs`,children:s?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5 tabular-nums text-foreground`,children:[(0,X.jsx)(_t,{className:`h-3 w-3 shrink-0 text-muted-foreground`}),s.lat.toFixed(5),`, `,s.lon.toFixed(5),_&&(0,X.jsx)(ut,{className:`h-3 w-3 animate-spin text-muted-foreground`})]}),s.label&&(0,X.jsx)(`div`,{className:`truncate text-muted-foreground`,children:s.label})]}):(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`No point selected`})}),(0,X.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,X.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,X.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,X.jsx)(b,{className:`h-3.5 w-3.5`}),`Use this point`]})]})]})]})]}),document.body)}var eu={exif:`from the photo's EXIF`,device:`from the device at capture`,manual:`placed by hand`};function tu(e){let t=`${e.lat.toFixed(5)}, ${e.lon.toFixed(5)}`,n=e.source?eu[e.source]:null;return[t,e.accuracy==null?null:`±${e.accuracy} m`,n].filter(Boolean).join(` · `)}function nu({value:e,onChange:t,idPrefix:n=`edit-geo`}){let[r,i]=(0,J.useState)(!1);return(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${n}-action`,children:`Location`}),(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,X.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 text-xs`,children:[(0,X.jsx)(Ie,{className:e?`h-4 w-4 shrink-0 text-info`:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:e?`truncate tabular-nums`:`truncate text-muted-foreground`,children:e?tu(e):`No location on this document`})]}),(0,X.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,X.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,X.jsx)(nt,{className:`h-3.5 w-3.5`}),e?`Move pin`:`Set on map`]}),e&&(0,X.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,X.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]}),r&&(0,X.jsx)($l,{initial:e,onPick:e=>t({lat:e.lat,lon:e.lon,source:`manual`}),onClose:()=>i(!1)})]})}var ru=15,iu=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function au(e){return String(e).padStart(2,`0`)}function ou(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 su(e){return`${e.getFullYear()}-${au(e.getMonth()+1)}-${au(e.getDate())}`}function cu(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function lu(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/ru)*ru),`${au(e.getHours())}:${au(e.getMinutes())}`}function uu(){let e=[];for(let t=0;t<1440;t+=ru)e.push(`${au(Math.floor(t/60))}:${au(t%60)}`);return e}var du=uu();function fu(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 pu(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 mu(e){let t=ou(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 hu({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,J.useState)(!1),u=(0,J.useRef)(null),d=ou(e),f=d?mu(e):``;return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:H(`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,X.jsx)(T,{className:H(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,X.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,X.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,X.jsx)(E,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,X.jsx)(gu,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function gu({anchorRef:e,value:t,onChange:n,onClose:r}){let i=ou(t),a=i?.date??su(new Date),o=i?.time??null,[s,c]=(0,J.useState)(()=>{let e=cu(a);return new Date(e.getFullYear(),e.getMonth(),1)}),u=(0,J.useRef)(null),d=(0,J.useRef)(null),[f,p]=(0,J.useState)(null);(0,J.useLayoutEffect)(()=>{let t=u.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));p({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,J.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),r())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[r]);let m=(0,J.useMemo)(()=>!o||du.includes(o)?du:[...du,o].sort(),[o]);(0,J.useEffect)(()=>{let e=d.current,t=e?.querySelector(`[data-selected="true"]`);e&&t&&(e.scrollTop=t.offsetTop-e.clientHeight/2+t.clientHeight/2)},[]);let h=(e,t)=>n(`${e}T${t}`),g=e=>{let t=o??lu();h(su(e),t),e.getMonth()!==s.getMonth()&&c(new Date(e.getFullYear(),e.getMonth(),1))},_=e=>{h(a,e),r()},v=e=>{let t=new Date;t.setDate(t.getDate()+e);let n=o??lu();h(su(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},y=su(new Date),b=fu(s);return(0,uo.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,X.jsxs)(`div`,{ref:u,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:f?.x??-9999,top:f?.y??-9999,visibility:f?`visible`:`hidden`},children:[(0,X.jsxs)(`div`,{className:`w-[236px]`,children:[(0,X.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,X.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,X.jsx)(l,{className:`h-4 w-4`})}),(0,X.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,X.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,X.jsx)(vt,{className:`h-4 w-4`})})]}),(0,X.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:iu.map(e=>(0,X.jsx)(`span`,{children:e},e))}),(0,X.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:b.map(e=>{let t=su(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,X.jsx)(`button`,{type:`button`,onClick:()=>g(e),"aria-pressed":r,className:H(`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===y&&`font-semibold ring-1 ring-inset ring-border`),children:e.getDate()},t)})}),(0,X.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>v(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,X.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,X.jsx)(`input`,{type:`time`,step:900,value:o??``,onChange:e=>{e.target.value&&h(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,X.jsx)(`div`,{ref:d,className:`max-h-[236px] flex-1 overflow-y-auto pr-0.5`,children:m.map(e=>{let t=e===o;return(0,X.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>_(e),"aria-pressed":t,className:H(`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:pu(e)},e)})})]})]})]}),document.body)}var _u={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},vu=`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`,yu=`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 bu({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,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${u}-title`,children:`Title`}),(0,X.jsx)(U,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${u}-desc`,children:`Description`}),(0,X.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:yu})]}),(0,X.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${u}-due`,children:`Due`}),(0,X.jsx)(hu,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${u}-priority`,children:`Priority`}),(0,X.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:vu,children:[(0,X.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,X.jsx)(`option`,{value:e,children:_u[e]},e))]})]})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${u}-status`,children:`Status`}),(0,X.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:vu,children:Ss.map(e=>(0,X.jsx)(`option`,{value:e,children:Cs[e]},e))})]})]})}var xu=`3.0`,Su=[`person`,`organization`,`service`,`bot`],Cu={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},wu=[`email`,`phone`,`sms`,`chat`,`web`],Tu=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function Eu(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 Du(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=wn(String(e?.schema||``),Xt);return{displayName:String(t.displayName||``),type:Su.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 Ou(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await kn(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function ku(e){let[t,n]=(0,J.useState)(e?.displayName??``),[r,i]=(0,J.useState)(e?.type??`person`),[a,o]=(0,J.useState)(e?.primaryEmail??``),[s,c]=(0,J.useState)(e?.given??``),[l,u]=(0,J.useState)(e?.family??``),[d,f]=(0,J.useState)(e?.channels??[]),[p,m]=(0,J.useState)(e?.identifiers??[]),[h,g]=(0,J.useState)(e?.organizations??[]),[_,v]=(0,J.useState)([]),[y,b]=(0,J.useState)(``),[x,S]=(0,J.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:`${Xt}/${C.type}`,schemaVersion:xu,data:Eu(C),...t?{comment:t}:{},metadata:{features:Wn(_)}},r=await ir(e,[n]);return await Ou(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 Au=`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 ju({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,X.jsx)(fo,{children:e}),(0,X.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,X.jsx)(ze,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,X.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,X.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,X.jsx)(pe,{className:`h-3.5 w-3.5`})})]},i))})]})}function Mu(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 Nu(e){let[t,n]=(0,J.useState)([]);return(0,J.useEffect)(()=>{if(!e)return;let t=!1;async function r(){try{let r=await Jt(e,`organization`);t||n(r.map(e=>({id:e.id,name:Gt(e).title})))}catch{t||n([])}}return r(),()=>{t=!0}},[e]),t}function Pu({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=Nu(t);return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,X.jsx)(U,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${e}-type`,children:`Type`}),(0,X.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:H(Au,`w-full`),children:Su.map(e=>(0,X.jsx)(`option`,{value:e,children:Cu[e]},e))})]}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${e}-email`,children:`Primary email`}),(0,X.jsx)(U,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${e}-given`,children:`Given name`}),(0,X.jsx)(U,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,X.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`${e}-family`,children:`Family name`}),(0,X.jsx)(U,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,X.jsx)(ju,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:H(Au,`w-24`),children:[wu.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e)),!wu.includes(e.kind)&&(0,X.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,X.jsx)(U,{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,X.jsx)(`button`,{type:`button`,onClick:()=>p(Mu(f,f.indexOf(e))),className:H(`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,X.jsx)(Ye,{className:H(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,X.jsx)(ju,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:H(Au,`w-24`),children:[Tu.map(e=>(0,X.jsx)(`option`,{value:e,children:e},e)),!Tu.includes(e.type)&&(0,X.jsx)(`option`,{value:e.type,children:e.type})]}),(0,X.jsx)(U,{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,X.jsx)(ju,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,X.jsxs)(X.Fragment,{children:[y.length>0?(0,X.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:H(Au,`min-w-0 flex-1`),children:[(0,X.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,X.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,X.jsx)(U,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,X.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,X.jsx)(Ne,{className:`h-3.5 w-3.5`})}),(0,X.jsx)(U,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function Fu(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 Iu(e){return Fu(e.schema)||Bn(e)}function Lu(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function Ru(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await $t(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 kn(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await tn(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function zu({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),a=Fu(e.schema),o=e.schema===Yt,s=Bn(e),c=Gn(e)??`markdown`,l=s&&Fn(e),u=e.schema===Nt,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=Lu(e.schema),[m,h]=(0,J.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,J.useState)(String(e.data?.[p]??``)),[v,y]=(0,J.useState)(String(e.data?.content??``)),[b,x]=(0,J.useState)(String(e.data?.description??``)),[S,C]=(0,J.useState)(e.data?.status??`pending`),[w,T]=(0,J.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,J.useState)(e.data?.dueDate?Es(String(e.data.dueDate)):Os()),O=ku(Du(e)),[k,A]=(0,J.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[ee,M]=(0,J.useState)(j),N=e.features??e.metadata?.features,[P,F]=(0,J.useState)(Rn(N).length?Rn(N):e.data?.tags??[]),I=In(e,t,o),{title:L,content:te,comment:ne,tags:re,geo:ie,setTitle:ae,setContent:oe,setComment:R,setTags:se,setGeo:ce}=o?I:{title:g,content:v,comment:k,tags:P,geo:ee,setTitle:_,setContent:y,setComment:A,setTags:F,setGeo:M},le=JSON.stringify(ie??null)!==JSON.stringify(j??null),ue=Vn(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Hn,version:e.checksumArray?.[0]??null}),[de,z]=(0,J.useState)(null),fe=`${e.id}:${e.checksumArray?.[0]??``}`;s&&ue.text!=null&&de!==fe&&(z(fe),oe(ue.text));let[pe,me]=(0,J.useState)([]),[he,ge]=(0,J.useState)(!1),{replicating:_e,mirror:ve}=K(e);(0,J.useEffect)(()=>{let e=!1;return kt(t).then(t=>{e||me(t)}).catch(()=>{}),()=>{e=!0}},[t]);let ye=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),be=!he&&(s?!l&&ue.text!=null&&!ue.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?L.trim().length>0:o?I.canSave:ye:!0),xe=async()=>{ge(!0);let c=[...(N||[]).filter(e=>!e.startsWith(`tag/`)),...Wn(re)];try{if(o){await I.save(),n();return}if(s){let i=await qn(t,e,te,{comment:ne.trim(),metadata:{features:c,...le?{geo:ie}:{}}});r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n(i);return}let i={id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,comment:ne.trim(),metadata:{features:c}};if(d){let{type:t,...n}=e.data??{};i.schema=`${Xt}/${O.values.type}`,i.data={...n,...Eu(O.values)}}else if(u)i.data={...e.data,...ks({title:L,description:b,status:S,priority:w,due:E})};else if(a){let t=re.map(e=>e.trim()).filter(Boolean),n;o?n={...L.trim()?{title:L.trim()}:{},content:te}:(n={...e.data},f&&(n[f]=m.trim()),L.trim()?n[p]=L.trim():delete n[p],n.tags=t),i.data=n}le&&(i.metadata={...i.metadata??{},geo:ie}),await jn(t,i),d&&(await Ru(t,e.id,O.values.organizations),hl()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{ge(!1)}};return(0,X.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`edit-url`,children:`URL`}),(0,X.jsx)(U,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!ye&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,X.jsx)(Pu,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,X.jsx)(bu,{idPrefix:`edit-todo`,title:L,setTitle:ae,description:b,setDescription:x,status:S,setStatus:C,priority:w,setPriority:T,due:E,setDue:D}),a&&!u&&!d&&(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`edit-title`,children:`Title`}),(0,X.jsx)(U,{id:`edit-title`,value:L,onChange:e=>ae(e.target.value),placeholder:o?`Optional; defaults to today's date`:`Optional display title`})]}),(o||s)&&(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{children:`Body`}),l?(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`This file is too large to edit here (`,`>`,1e3,` kB) — download it instead.`]}):s&&ue.error?(0,X.jsx)(`p`,{className:`text-xs text-destructive`,children:ue.error}):s&&ue.text==null?(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,X.jsx)(Un,{kind:o?`markdown`:c,value:te,onChange:oe,placeholder:o?`Write your note…`:void 0})]}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{children:`Tags`}),(0,X.jsx)(Kl,{tags:re,onChange:se,suggestions:pe})]}),(0,X.jsx)(nu,{value:ie,onChange:ce}),(0,X.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,X.jsx)(fo,{htmlFor:`edit-comment`,children:`Comment`}),(0,X.jsx)(`textarea`,{id:`edit-comment`,value:ne,onChange:e=>R(e.target.value),rows:3,placeholder:`Add context you can't infer from the content, e.g. “sofa from the cozmo bar in Košice”`,className:`flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-elevation-1 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50`})]}),o&&(0,X.jsx)(Kn,{...I,onRetry:I.save}),(0,X.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,X.jsx)(G,{variant:`outline`,size:`sm`,onClick:()=>n(),disabled:he,children:o?`Close`:`Cancel`}),(0,X.jsx)(G,{size:`sm`,onClick:xe,disabled:!be,children:he?_e?`Replicating to ${ve.label}…`:`Saving…`:`Save changes`})]})]})}var Bu=(0,J.createContext)(null),Vu={open:()=>{},close:()=>{}};function Hu(){return(0,J.useContext)(Bu)??Vu}var Uu=(0,J.createContext)(null),Wu={entry:null,open:()=>{},close:()=>{}};function Gu(){return(0,J.useContext)(Uu)??Wu}var Ku=`main`,qu=(0,J.createContext)(null);function Ju(){return(0,J.useContext)(qu)}var Yu=50;function Xu({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=Hu(),o=Gu(),s=Ju(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?Gt(l).title:``,[d,f]=(0,J.useState)(!1),{showErrorToast:p}=Tt(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await xn(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,X.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,X.jsx)(Te,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,X.jsx)(lt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,X.jsx)(el,{document:l,size:3.5}):null,l?(0,X.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,X.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,X.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!h&&(0,X.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,X.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,X.jsx)(pe,{className:`h-3.5 w-3.5`})})]})}function Zu({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Tt(),[i,a]=(0,J.useState)(null),[o,s]=(0,J.useState)(null),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(!1),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(0),[g,_]=(0,J.useState)(1),v=(0,J.useRef)(0),y=(0,J.useCallback)(()=>{v.current++},[]),b=(0,J.useCallback)(async()=>{let n=++v.current;try{let r=await $t(t,e.id,{offset:m*Yu,limit:Yu,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)/Yu)-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,J.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,J.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(ml,e),()=>{y(),window.removeEventListener(ml,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 tn(t,e.id,i.p,o,a),n(`Relation removed`),hl()}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,X.jsxs)(`div`,{children:[(0,X.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,X.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,X.jsx)(ze,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,X.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,X.jsxs)(`div`,{children:[(0,X.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,X.jsxs)(`div`,{className:`mb-2`,children:[(0,X.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,X.jsx)(Xu,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,X.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,X.jsx)(G,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,X.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,X.jsx)(G,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,X.jsx)(Bl,{onClose:()=>{u||l(!1)},children:(0,X.jsx)(pl,{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 kn(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),hl()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var Qu=(0,J.lazy)(()=>s(()=>import(`./SketchEditor-CRJF-Jp4.js`),__vite__mapDeps([9,3,4,10,1,11,12,13,14,15,16,17,18,19,20,21,22,23,24]))),$u=(0,J.lazy)(()=>s(()=>import(`./TextDocumentEditor-BKueFXia.js`),__vite__mapDeps([25,3,4,11,10,13,12,14,15,16,26,1,23]))),ed={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},td={reply:ie,replyAll:m,forward:oe};function nd({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Yn()!=null,{showErrorToast:a}=Tt(),[o,s]=(0,J.useState)(!1),c=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[l,u]=(0,J.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,J.useState)(n&&!i),v=e.schema===qt,[y,b]=(0,J.useState)(!1),x=e.schema===`data/schema/note`||Bn(e),[S,C]=(0,J.useState)(!1),T=`${t}:${e.id}:${n}:${i}`,[E,D]=(0,J.useState)(T);T!==E&&(D(T),_(n&&!i),u(null),s(!1),b(!1),C(!1));let O=t=>{if(!h||!Iu(e)||t.defaultPrevented)return!1;let n=t.target;return n instanceof Element&&t.currentTarget.contains(n)&&!n.closest(`a, button, input, textarea, select, label, summary, audio, video, [role="button"], [role="checkbox"], [contenteditable]:not([contenteditable="false"])`)};return g&&h?(0,X.jsx)(zu,{document:e,workspaceId:t,onClose:e=>{_(!1),r?.(e)}}):(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[h&&(0,X.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[c&&(0,X.jsx)(G,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=td[e];return(0,X.jsxs)(G,{size:`sm`,variant:l===e?`secondary`:`outline`,onClick:()=>m(e),children:[(0,X.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),ed[e]]},e)}),e.schema===`data/schema/file`&&(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>Wt(t,e.id,Ft(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,X.jsx)(Me,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,X.jsx)(w,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>C(!0),children:[(0,X.jsx)(yt,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,X.jsx)(k,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),y&&h&&(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,X.jsx)(Qu,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),_(!0)}})}),S&&h&&(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,X.jsx)($u,{doc:e,workspaceName:t,onSaved:e=>{C(!1),r?.(e)},onClose:()=>C(!1),onDetails:()=>{C(!1),_(!0)}})}),(0,X.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,onMouseDownCapture:e=>{e.button===0&&e.detail>1&&O(e)&&e.preventDefault()},onDoubleClickCapture:e=>{O(e)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.ownerDocument.getSelection()?.removeAllRanges(),_(!0))},children:[o&&!i?(0,X.jsx)(Ll,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,X.jsx)(Sl,{workspaceId:t,document:e}),l&&f&&(0,X.jsx)(Il,{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,X.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,X.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,X.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var rd=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,id=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function ad({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,X.jsxs)(`div`,{children:[(0,X.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,X.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,X.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`,id(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`,rd(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,X.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 od({document:e}){let t=e.metadata;return(0,X.jsxs)(`div`,{className:`space-y-6`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,X.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,X.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,X.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:rd(e.createdAt)})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:rd(e.updatedAt)})]})]})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,X.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,X.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,X.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,X.jsx)(ad,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,X.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=ud(e.url);return(0,X.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,X.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),e.status&&e.status!==`available`&&(0,X.jsx)(`span`,{className:`shrink-0 rounded border px-1 text-xs`,title:e.statusChangedAt,children:e.status===`deleted`?`Deleted`:`Not found`}),r&&(0,X.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,X.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,X.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,X.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,X.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,X.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,X.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,X.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,X.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,X.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function sd({document:e}){let{showSuccessToast:t,showErrorToast:n}=Tt(),r=JSON.stringify(e,null,2);return(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)(`div`,{className:`flex justify-end`,children:(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,X.jsx)(u,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,X.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function cd({document:e,workspaceId:t}){let[n,r]=(0,J.useState)(null),[i,a]=(0,J.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,J.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,J.useEffect)(()=>{let n=!1;return en(t,e.id).then(e=>{n||r(e)}).catch(e=>{n||a(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[o]),i?(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,X.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,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,X.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,X.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,X.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,X.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,X.jsx)(Zu,{document:e,workspaceId:t})]}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function ld(e){return e===`stored`?pt:e===`workspace-file`?F:e===`imap`?Se:e===`readonly`?se:at}function ud(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 dd({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(null),[l,d]=(0,J.useState)(null),[f,p]=(0,J.useState)(null),[m,h]=(0,J.useState)(null),[g,_]=(0,J.useState)(!1),v=`${t}:${e.id}`,[y,b]=(0,J.useState)(v);v!==y&&(b(v),o(null),c(null),p(null));let x=()=>{Lt(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,J.useEffect)(()=>{let n=!1;return Lt(t,e.id).then(e=>{n||o(e)}).catch(e=>{n||c(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[v]);let S=async(a,o)=>{d(a),p(null);try{let i=await _n(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?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{d(null)}},C=async(a,o,s)=>{_(!0);try{let i=await An(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(Rl(i.failed,new Map([[e.id,Ft(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`)),h(null),n?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{_(!1)}},w=e=>{if((a?.length??0)<=1){p(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&S(e.url)};if(s)return(0,X.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let T=a.length===0,E=Ft(e);return(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,X.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,X.jsx)(pt,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,X.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,X.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),T?(0,X.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,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>h(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,X.jsx)(u,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>h(`move`),title:`Move the file data to another storage backend (source released once the copy is durable)`,children:[(0,X.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=ld(n.kind),{backend:a,key:o}=ud(n.url),s=l===n.url;return(0,X.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,X.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,X.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,X.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,X.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,X.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,X.jsx)(`button`,{onClick:()=>Wt(t,e.id,E||`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,X.jsx)(Me,{className:`h-3.5 w-3.5`})}),(0,X.jsx)(`button`,{onClick:()=>w(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,X.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]}),f===n.url&&(0,X.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,X.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,X.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,X.jsx)(G,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!1),children:`Also remove index entry`}),(0,X.jsx)(G,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!0),children:`Keep index entry (no bytes)`}),(0,X.jsx)(G,{variant:`ghost`,size:`sm`,onClick:()=>p(null),children:`Cancel`})]})]})]},n.url)}),m&&(0,uo.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,X.jsx)(Gl,{workspaceId:t,documentCount:1,initialMode:m,defaultFilename:E,saving:g,onConfirm:C,onClose:()=>{g||h(null)}})}),window.document.body)]})}function fd(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 pd(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 md(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&&pd(e,t,n.points)}function hd(e,t,n=!1){let r=fd(e);return r?md(r.lat,r.lon,t):n}var gd=(0,J.lazy)(()=>s(()=>import(`./LocationTab-BONJQfYM.js`),__vite__mapDeps([27,3,4,28,29]))),_d=[{id:`view`,label:`View`,icon:dt},{id:`location`,label:`Location`,icon:Ie},{id:`metadata`,label:`Metadata`,icon:f},{id:`json`,label:`JSON`,icon:he},{id:`synapses`,label:`Synapses`,icon:Qe},{id:`backends`,label:`Backends`,icon:pt}];function vd({document:e,workspaceId:t,initialTab:n=`view`,initialEdit:r=!1,onChanged:i,className:a=``,compact:o=!1,navigation:s,tabActions:c,onTabChange:l}){let u=Yn()!=null,d=fd(e),f=_d.filter(e=>(e.id!==`location`||d!==null)&&(!u||![`synapses`,`backends`].includes(e.id))),[p,m]=(0,J.useState)(n),h=`${e.id}:${n}`,[g,_]=(0,J.useState)(h);h!==g&&(_(h),m(n));let v=f.some(e=>e.id===p)?p:`view`,y=e=>{m(e),l?.(e)},b=o&&!!c&&!s,x=(0,X.jsx)(`div`,{className:H(b&&`document-detail-header shrink-0 border-b-[3px] bg-muted`),children:(0,X.jsxs)(`div`,{className:H(`flex min-w-0 items-center`,b&&`mx-auto h-[calc(3rem-4px)] w-full max-w-[var(--document-reading-width,100%)] gap-1 pl-2 pr-2 sm:pl-4`),children:[(0,X.jsx)(xl,{tabs:f,active:v,onChange:y,className:H(`min-w-0 flex-1 px-1`,b&&`h-full border-b-0 px-0 max-sm:gap-0 max-sm:[&>button]:px-2.5`),iconOnly:o}),c]})});return(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[s?(0,X.jsx)(bl,{...s,tabs:x,section:v,onDocument:()=>y(`view`),onSection:()=>y(`view`),onBack:v===`view`?s.onBack:()=>y(`view`)}):x,(0,X.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,X.jsxs)(`div`,{className:`mx-auto h-full w-full max-w-[var(--document-reading-width,100%)] p-4`,children:[v===`view`&&(0,X.jsx)(nd,{document:e,workspaceId:t,initialEdit:r&&!u,onChanged:i}),v===`location`&&d&&(0,X.jsx)(J.Suspense,{fallback:(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,X.jsx)(gd,{lat:d.lat,lon:d.lon})}),v===`metadata`&&(0,X.jsx)(od,{document:e,workspaceId:t}),v===`json`&&(0,X.jsx)(sd,{document:e,workspaceId:t}),v===`synapses`&&!u&&(0,X.jsx)(cd,{document:e,workspaceId:t}),v===`backends`&&!u&&(0,X.jsx)(dd,{document:e,workspaceId:t,onChanged:i})]})})]})}function yd(e,t){let[n,r]=(0,J.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,J.useState)(a);a!==o&&(s(a),r(null));let c=(0,J.useRef)(a),l=(0,J.useRef)(0);(0,J.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,J.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}xn(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}function bd(e){return e.schema===`data/schema/note`?ct:e.schema===`data/schema/tab`?We:e.schema===`data/schema/file`?rt:e.schema===`data/schema/message/email`?Se:at}function xd({entry:e,onClose:t,frame:n}={}){let r=Gu(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=yd(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,X.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,X.jsxs)(`div`,{className:`flex h-[calc(3rem-1px)] shrink-0 items-center justify-between border-b-[3px] bg-muted pl-4 pr-2`,children:[(0,X.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,X.jsx)(`button`,{type:`button`,onClick:a,className:`flex h-8 w-8 items-center justify-center rounded hover:bg-accent`,"aria-label":`Close`,children:(0,X.jsx)(E,{className:`h-4 w-4`})})]}),(0,X.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,X.jsx)(`button`,{type:`button`,className:`ml-2 underline`,onClick:r.retry,children:`Retry`})]})]}):null;let{workspaceId:c}=i,l=t=>{s(t),t&&t.id!==i.document.id&&!e&&r.replace?.(t,c)};return(0,X.jsx)(gl,{title:Gt(o).title,icon:bd(o),onClose:r.alwaysOn?void 0:a,onSave:async e=>(await Zt(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:tc(o)===rs,maximized:e?void 0:r.location?.maximized,onMaximizedChange:e?void 0:e=>r.update?.({maximized:e}),children:t=>(0,X.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,X.jsx)(vd,{document:o,workspaceId:c,onChanged:l,compact:!0,tabActions:t,initialTab:e?void 0:r.location?.section,onTabChange:e?void 0:e=>r.update?.({section:e})},`${c}:${o.id}`)})})}var Sd=320,Cd=1600;function wd({edge:e}){let t=No(),n=(0,J.useRef)(null),r=e===`left`?-1:1;return(0,X.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":Sd,"aria-valuemax":Cd,"aria-valuenow":t??420,tabIndex:0,title:`Drag to resize; arrow keys adjust width; double-click to reset`,className:`absolute inset-y-0 ${e===`left`?`left-0`:`right-0`} z-20 hidden w-2 touch-none cursor-col-resize select-none hover:bg-primary/20 focus-visible:bg-primary/20 focus-visible:outline-none md:block`,onPointerDown:t=>{if(t.button!==0)return;t.preventDefault(),t.stopPropagation();let r=t.currentTarget.closest(`[data-reader-pane]`),i=e===`left`?(r.parentElement?.clientWidth??window.innerWidth)-248:window.innerWidth;n.current={x:t.clientX,width:r.getBoundingClientRect().width,max:Math.max(Sd,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&Mo(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:()=>Mo(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`?Mo(null):Mo(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function Td(e){let t=wo(),n=Lo(),r=Gu();return!e.enabled||!e.workspaceId||!t||n||r.location?e.children:(0,X.jsx)(Ed,{...e,workspaceId:e.workspaceId},e.scope)}function Ed({workspaceId:e,scope:t,documents:n,loading:r,children:i}){let a=No(),o=`canvas:readerSelection:${t}`,[s,c]=(0,J.useState)(()=>{try{return Number(sessionStorage.getItem(o))||null}catch{return null}}),l=r?null:n.find(e=>e.id===s)??n[0]??null,u=(0,J.useCallback)((t,n)=>{if(n===e){c(t.id);try{sessionStorage.setItem(o,String(t.id))}catch{}}},[e,o]),d=(0,J.useMemo)(()=>({entry:l?{document:l,workspaceId:e}:null,alwaysOn:!0,open:u,preview:u,replace:u,close:()=>{}}),[l,e,u]);return(0,X.jsx)(Uu.Provider,{value:d,children:(0,X.jsxs)(`div`,{"data-always-reader":!0,className:`flex h-full min-h-0 min-w-0 flex-1 gap-shell`,children:[(0,X.jsx)(`div`,{className:`min-h-0 min-w-0 flex-1 overflow-auto`,children:i}),(0,X.jsxs)(`aside`,{"data-reader-pane":!0,"aria-label":`Document reading pane`,style:{width:a?`${a}px`:`50vw`,maxWidth:`calc(100% - 240px)`},className:`relative flex min-h-0 min-w-0 shrink-0 overflow-hidden border-l bg-card`,children:[(0,X.jsx)(wd,{edge:`left`}),l?(0,X.jsx)(xd,{},`${e}:${l.id}`):(0,X.jsx)(`div`,{className:`flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground`,role:`status`,children:r?`Loading documents…`:`No documents in this list`})]})]})})}async function Dd(e,t,n){let r={successful:[],failed:[],pending:[]},i=[...new Set(e)],a=0;n.onProgress(0,i.length);for(let e of i){if(n.shouldStop())break;try{let n=await t([e]);r.successful.push(...n.successful),r.failed.push(...n.failed)}catch(t){r.failed.push({id:e,reason:t instanceof Error?t.message:String(t)}),a++,n.onProgress(a,i.length);break}a++,n.onProgress(a,i.length)}return r.pending=i.slice(a),r}function Od(e){return`/workspaces/${e}/hooks`}async function kd(e){return await W.get(Od(e))||[]}async function Ad(e,t){return(await W.get(`${Od(e)}/${t}`))?.content??``}async function jd(e,t,n){await W.put(`${Od(e)}/${t}`,{content:n})}async function Md(e,t){await W.delete(`${Od(e)}/${t}`)}var Nd=[`example-`,`disabled-`,`_`];function Pd(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function Fd(e){return Nd.find(t=>e.startsWith(t))??null}function Id(e){return Fd(Pd(e).base)===null}function Ld(e){return Pd(e).base.startsWith(`example-`)}function Rd(e){let{dir:t,base:n}=Pd(e),r=Fd(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function zd(e,t,n){if(Id(t)===n)return t;let r=Rd(t);return await jd(e,r,await Ad(e,t)),await Md(e,t),r}function Bd(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 Vd(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function Hd(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function Ud(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 Wd(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 Gd(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var Kd=`rules.json`;async function qd(e){try{let t=await Ad(e,Kd),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Jd(e,t){await jd(e,Kd,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
14
+ `)}async function Yd(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 W.get(`${Od(e)}/pending${r?`?${r}`:``}`)||[]}async function Xd(e,t){return await W.post(`${Od(e)}/pending/decisions`,t)}async function Zd(e,t){return await W.get(`${Od(e)}/runs/${encodeURIComponent(t)}`)}async function Qd(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 W.get(`${Od(e)}/runs${r?`?${r}`:``}`)||[]}var $d=1e4,ef=`canvas.hooks.backfillLimit`;function tf(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?100:Math.min(t,$d)}function nf(){try{let e=localStorage.getItem(ef);return e?tf(e):100}catch{return 100}}function rf(e){let t=tf(e);try{localStorage.setItem(ef,String(t))}catch{}return t}function af(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 of(e,t){return await W.post(`${Od(e)}/backfill`,t)}async function sf(e,t){return await W.post(`${Od(e)}/run`,t)}async function cf(e,t){return await W.post(`${Od(e)}/runs/${t}/replay`,{})}async function lf(e){return await W.get(`${Od(e)}/meta`)}async function uf(e,t){return await W.post(`${Od(e)}/generate`,t)}async function df(e,t){let n=await Ad(e,Kd),r=JSON.parse(n),i=Array.isArray(r)?r:r?.rules;if(!Array.isArray(i))throw Error(`The workspace rules file is invalid. Fix it in Rules before adding a rule.`);let a=(Array.isArray(t)?t:[t]).filter(e=>!i.some(t=>t.id===e.id));if(!a.length)return;let o=Array.isArray(r)?[...i,...a]:{...r,rules:[...i,...a]};await jd(e,Kd,JSON.stringify(o,null,2)+`
15
+ `)}var ff=df;function pf(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 mf(){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 hf(){let[e]=(0,J.useState)(mf);return(0,J.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 gf(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}function _f(e){return e?e.remote?e.remote.permissions.includes(`admin`):e.access?e.access.isOwner||e.access.permissions.includes(`admin`):e.isShared||e.type===`shared`?typeof e.sharedVia==`object`&&e.sharedVia?.permissions?.includes(`admin`)===!0:!0:!1}var vf=e=>typeof e==`string`?e:``,yf=e=>e&&typeof e==`object`?e:{},bf=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);function xf(e){let t=e.data||{},n=e.schema===`data/schema/message/email`,r=!n&&e.schema.startsWith(`data/schema/message`),i=vf(t.platform),a=vf(yf(t.channel).id)||vf(t.channel),o=[],s=(t,n,r)=>o.push({id:t,label:n,rule:{id:``,description:n,enabled:!0,when:{event:`document.inserted`,schema:e.schema,...r},then:[{action:`link`,paths:[]}]}}),c=i?{platform:{equals:i}}:{};if(n){let e=vf(yf(t.from).address)||vf(t.from);e&&s(`sender`,`Mail from ${e}`,{from:{equals:e}}),t.subject&&s(`subject`,`Subject matches regex`,{subject:{regex:bf(t.subject)}})}else if(r){let e=vf(yf(t.sender).id)||vf(yf(t.sender).username)||vf(yf(t.sender).name)||vf(t.sender),n=vf(yf(t.sender).name)||vf(yf(t.sender).username)||e;e&&s(`sender`,`Messages from ${n}`,{...c,sender:{equals:e}})}let l=vf(t.body)||vf(t.text)||vf(t.content)||vf(t.bodyHtml)||vf(t.bodyPreview);if((n||r||l)&&s(`body`,n?`Email body matches regex`:`Text matches regex`,{...c,body:{regex:bf(l.slice(0,160))}}),r){let n=vf(t.threadId)||([`slack`,`teams`].includes(i)?vf(yf(e.metadata).remoteId):``);n&&a&&s(`thread`,`Messages in this thread`,{...c,channel:{equals:a},thread:{equals:n}}),a&&s(`channel`,i===`whatsapp`?`Messages in this conversation`:`Messages in this channel`,{...c,channel:{equals:a}})}return t.url&&s(`url`,`URL matches regex`,{url:{regex:bf(t.url)}}),s(`schema`,`All items of this type`,{}),o}function Sf({label:e,onClose:t,children:n}){return ac(t),(0,uo.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-dialog flex items-center justify-center bg-scrim p-4`,onClick:t,children:(0,X.jsx)(`section`,{"data-dialog-surface":!0,role:`dialog`,"aria-modal":`true`,"aria-label":e,className:`h-[86dvh] max-h-full min-h-0 w-full max-w-3xl overflow-y-auto rounded-(--panel-radius) border bg-popover text-popover-foreground shadow-elevation-4`,onClick:e=>e.stopPropagation(),children:n})}),window.document.body)}function Cf(e,t,n,r=new Date){let i=e=>String(e).padStart(2,`0`),a={YYYY:String(r.getFullYear()),YY:i(r.getFullYear()%100),MM:i(r.getMonth()+1),DD:i(r.getDate()),HH:i(r.getHours()),mm:i(r.getMinutes()),ss:i(r.getSeconds())},o=e=>e.replace(/\{\{\s*([A-Za-z]+)\s*\}\}/g,(e,t)=>a[t]??e),s=e=>e.split(/[\\/]+/).filter(e=>e&&e!==`.`&&e!==`..`).join(`/`),c=[e,s(o(t.trim()))].filter(Boolean).join(`/`),l=s(o(n.trim()));return{root:c,added:l,result:[c,l,`<attachment filename>`].filter(Boolean).join(`/`),date:`${a.YYYY}-${a.MM}-${a.DD}`}}function wf(e){return`/workspaces/${e}/scripts`}async function Tf(e){return await W.get(wf(e))||[]}async function Ef(e,t){return(await W.get(`${wf(e)}/${t}`))?.content??``}async function Df(e,t,n){await W.put(`${wf(e)}/${t}`,{content:n})}async function Of(e,t){await W.delete(`${wf(e)}/${t}`)}function kf({value:e,onChange:t,onPickTarget:n,fixedWorkspaceName:r,format:i=`url`,tabs:a=[`context`,`directory`],pickerTitle:o=`Pick a path…`,placeholder:s,id:c,disabled:l,className:u,inputClassName:d,presentation:f=`input`}){let[p,m]=(0,J.useState)(!1),h=e.match(/^(.*?):\/\//)?.[0]||``,_=h?e.slice(h.length):e;return(0,X.jsxs)(`div`,{className:H(`flex gap-2`,u),children:[f===`breadcrumbs`?(0,X.jsx)(tl,{items:nl(_,h.replace(`://`,``)||r||`Workspace`),onNavigate:e=>t(h?`${h}${e.replace(/^\/+/,``)}`:e),disabled:l,className:H(`rounded border px-1`,d)}):(0,X.jsx)(U,{id:c,value:e,onChange:e=>t(e.target.value),placeholder:s,disabled:l,className:H(`font-mono`,d)}),(0,X.jsx)(G,{type:`button`,variant:`outline`,size:`icon`,onClick:()=>m(!0),disabled:l,"aria-label":`Browse tree paths`,title:`Browse…`,className:`shrink-0`,children:(0,X.jsx)(g,{className:`h-4 w-4`})}),p&&(0,X.jsx)(Bl,{onClose:()=>m(!1),children:(0,X.jsx)(pl,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,multiple:!1,tabs:a,fixedWorkspaceName:r,title:o,confirmLabel:`Use path`,onConfirm:(e,r)=>{m(!1);let a=e[0];if(a){if(n){n(a,r);return}t(i===`url`?`${r.workspaceName}://${a.replace(/^\/+/,``)}`:a)}},onClose:()=>m(!1)})})]})}var Af=[{value:``,label:`any item`},{value:`email`,label:`an email`},{value:`message`,label:`a message`},{value:`tab`,label:`a browser tab / link`},{value:`note`,label:`a note`},{value:`file`,label:`a file`},{value:`todo`,label:`a todo / task`}],jf=[{value:`document.inserted`,label:`is added`,hint:`Fires when the item is created or uploaded.`},{value:`document.updated`,label:`is updated`,hint:`Fires on every edit of the item.`},{value:`document.linked`,label:`is filed into a folder`,hint:`Fires when the item is (re)filed into a tree path — the usual pair with "is added" for folder rules.`},{value:`document.unlinked`,label:`is removed from a folder`,hint:`Fires when the item leaves a tree path.`}],Mf=[{key:`toExact`,label:`recipient (To/Cc) is`,hint:`accounting@example.com`},{key:`fromExact`,label:`email sender is`,hint:`person@example.com`},{key:`senderExact`,label:`message sender is`,hint:`Sender ID`},{key:`sender`,label:`message sender contains`,hint:`Sender ID or name`},{key:`senderRegex`,label:`message sender matches regex`,hint:`Sender ID or name pattern`},{key:`body`,label:`body / text contains`,hint:`Words in the email preview or message text`},{key:`bodyRegex`,label:`body / text matches regex`,hint:`invoice\\s+\\d+`},{key:`threadExact`,label:`thread is`,hint:`Thread ID`},{key:`channelExact`,label:`channel / conversation is`,hint:`Channel or conversation ID`},{key:`platformExact`,label:`platform is`,hint:`slack, whatsapp, teams`},{key:`pathExact`,label:`is directly in the folder`,hint:`Current folder membership`},{key:`eventPathExact`,label:`is inserted / linked directly into`,hint:`Exact event destination, e.g. ctx:/foo/bar/baz. Descendant inserts do not match.`},{key:`path`,label:`is under the folder`,hint:`/projects/canvas/UI or backends:/workspace/home/foo`},{key:`mime`,label:`file type is`,hint:`image/*, application/pdf`},{key:`from`,label:`sender contains`,hint:`boss@company.tld`},{key:`to`,label:`recipient (To/Cc) contains`,hint:`invoice@my-company.tld`},{key:`subject`,label:`subject contains`,hint:`invoice`},{key:`fromRegex`,label:`sender matches regex`,hint:`@(acme|example)\\.com$`},{key:`toRegex`,label:`recipient (To/Cc) matches regex`,hint:`^(billing|accounts)@`},{key:`subjectRegex`,label:`subject matches regex`,hint:`^invoice\\s+\\d+`},{key:`urlRegex`,label:`URL matches regex`,hint:`/(invoice|receipt)/`},{key:`urlHost`,label:`website is`,hint:`youtube.com`},{key:`urlContains`,label:`URL contains`,hint:`/watch?v=`},{key:`attachment`,label:`has an attachment of type`,hint:`application/pdf, or * for any`}],Nf=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),Pf=e=>Nf.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),Ff=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:Se,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:Se,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:Se,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:F,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:Me,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:$e,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:$e,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`tag`,label:`add tags`,icon:N,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`},{key:`unstore`,label:`delete the file from a storage backend`,icon:ge,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`notify`,label:`Send me a notification`,icon:Ke,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:P,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`},{key:`script`,label:`run a script`,icon:ye,tone:`text-slate-600 dark:text-slate-300 bg-slate-500/10`},{key:`delete`,label:`delete it from Canvas`,icon:pe,tone:`text-destructive bg-destructive/10`},{key:`destroy`,label:`delete it everywhere`,icon:pe,tone:`text-destructive bg-destructive/10`}],If=e=>Ff.find(t=>t.key===e)||Ff[1],Lf=`{{title}}{{ext}}`,Rf=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,zf=[{value:`auto`,label:`whatever it is (auto)`,hint:`arXiv → the PDF · YouTube, Vimeo, TikTok… → the video · image / video / PDF links → the file · anything else → the page.`},{value:`image`,label:`the file itself (image, PDF, …)`,hint:`Fetches the bytes the URL serves.`},{value:`video`,label:`the video (yt-dlp)`,hint:`Best video + audio, merged. Needs yt-dlp on the server.`},{value:`arxiv`,label:`the arXiv paper (PDF)`,hint:`Works for abs/ and pdf/ links.`},{value:`page`,label:`the page with its images & styles`,hint:`One page, offline-readable (wget --page-requisites).`},{value:`website`,label:`the whole website (mirror)`,hint:`Follows links on the same site up to the chosen depth.`}],Bf=[{value:`keep`,label:`keep the original file name`},{value:`title`,label:`use the item title as file name`},{value:`dated`,label:`photo style: 2024/07/20240714_183012.jpg`},{value:`custom`,label:`custom template…`}],Z=e=>({sendDriver:`imap`,sendSource:`document`,sendSubject:`{{file.name}}`,sendMessage:``,kind:e,a:``,b:``,recursive:!1,storeFrom:``,storeFolder:``,storeName:`keep`,storeMode:`copy`,storeConflict:`rename`,attachmentMime:`application/pdf`,attachmentName:``,attachmentPath:`{{YYYY}}/{{MM}}`,includeInline:!1,dlKind:`auto`,dlDepth:`2`,dlTags:``,keepLast:!0,notePath:``,noteTitle:``,filePath:``,fileBackend:`home`,fileInsert:``,notifyReply:!1}),Vf={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[Z(`link`)]},Hf=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function Uf(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var Wf=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),Gf=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:Se,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`,blurb:`Send matching PDF attachments to your accounting firm’s ingestion email, or to a Slack / WhatsApp conversation. Keep the original email and files.`,build:()=>({...Vf,description:`Send invoice PDFs to accounting`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...Z(`sendFile`),sendSource:`attachments`,sendSubject:`Invoice: {{file.name}}`}]})},{id:`attachments`,title:`File PDF email attachments by month`,icon:Se,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Choose a recipient and extract PDF attachments into Accounting / year / month, using the email date. Add a subject or filename filter to narrow it to invoices.`,build:()=>({...Vf,description:`File accounting PDF attachments by month`,schema:`email`,conditions:[{field:`toExact`,value:``}],actions:[{...Z(`extractAttachments`),a:`workspace:home`,storeFolder:`Accounting`}]})},{id:`store`,title:`Copy/Move file(s) to a storage backend`,icon:F,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`,blurb:`Uploads land in the managed blob store. Pick a folder in Canvas and a folder on a storage backend — copy or move matching files and optionally recreate their sub-folder paths.`,build:({backend:e})=>({...Vf,description:`Copy/Move file(s) to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...Z(`store`),a:e,recursive:!0}]})},{id:`photos`,title:`Sort photos by date`,icon:Be,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`,blurb:`Images filed into a folder are stored as Photos / 2024 / 07 / 20240714_183012.jpg — by the time the photo was taken (EXIF), not uploaded.`,build:({backend:e})=>({...Vf,description:`Sort photos by date`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``},{field:`mime`,value:`image/*`}],actions:[{...Z(`store`),a:e,storeFolder:`Photos`,storeName:`dated`}]})},{id:`mirror`,title:`Mirror a storage folder`,icon:$e,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`,blurb:`Everything that appears under a folder of a storage backend shows up 1:1 in the Directory tree.`,build:()=>({...Vf,description:`Mirror a storage folder`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:`backends:/workspace/home/`}],actions:[{...Z(`link`),a:`dir:/`,recursive:!0}]})},{id:`mail`,title:`File mail from a sender`,icon:Se,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`,blurb:`Emails from a person or domain are filed into a folder and you get a notification.`,build:()=>({...Vf,description:`Mail from …`,schema:`email`,conditions:[{field:`from`,value:``}],actions:[{...Z(`link`),a:`/work/urgent`},{...Z(`notify`),a:`New mail from {{doc.data.from}}: {{doc.data.subject}}`}]})},{id:`download`,title:`Download what links point at`,icon:Me,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`,blurb:`Bookmarks filed into a folder are fetched for real — images, videos (yt-dlp), arXiv papers, a page or a whole website — saved to a folder and filed next to the link.`,build:({backend:e})=>({...Vf,description:`Download what links point at`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...Z(`download`),a:e,storeFolder:`Downloads`,recursive:!0}]})},{id:`agent`,title:`Ask an agent`,icon:P,tone:`text-indigo-600 dark:text-indigo-400 bg-indigo-500/10`,blurb:`Hand new items to an agent with a prompt; save its reply as a note or get it as a notification.`,build:()=>({...Vf,description:`Summarize new items`,actions:[{...Z(`agent`),b:`Read document #{{doc.id}} in full with canvas_get, then summarize it in three bullet points.`,notifyReply:!0}]})},{id:`blank`,title:`Start from scratch`,icon:Ze,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...Vf})}];function Kf(e){let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field));if(t.length!==1||t[0].field!==`eventPathExact`)return null;let n=Hf(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function qf(e){if(Kf(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>Hf(e.value));return t.length>0&&t.every(e=>/^(dir|directory|backends):\//.test(e))}function Jf(e,t,n){let r=e=>e.replace(/\\/g,`/`).split(`/`).filter(e=>e&&e!==`.`&&e!==`..`).join(`/`),i=`${n?.treePath?`backends:${n.treePath}`:e.a}/${r(e.storeFolder.trim())}`.replace(/\/+$/,``),a=Kf(t),o=e.recursive?a===null?`<sub-folders>`:r(a):``;return{root:i,recreated:o,result:[i,o,e.storeName===`keep`?`<original filename>`:e.storeName===`title`?`<title>.<ext>`:e.storeName===`dated`?Rf:e.b||`<filename>`].filter(Boolean).join(`/`)}}function Yf(e,t=[]){let n={event:e.events.length===1?e.events[0]:e.events};e.schema&&(n.schema=e.schema);let r={},i={};for(let t of e.conditions){let e=t.field.endsWith(`Regex`),n=Nf.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:Hf(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${Mf.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${Mf.find(e=>e.key===t.field)?.label||t.field}, or remove that condition.`);if(t.field===`urlHost`||t.field===`urlContains`||t.field===`urlRegex`){let e=t.field===`urlHost`?`host`:t.field===`urlRegex`?`regex`:`contains`,n=i[e],r=[...Array.isArray(n)?n:n==null?[]:[n],...a];i[e]=r.length===1?r[0]:r}else(r[Pf(t.field)]||=[]).push(...e?a.map(e=>({regex:e})):n?a.map(e=>({equals:e})):a)}for(let[e,t]of Object.entries(r))t?.length&&(n[e]=t.length===1?t[0]:t);Object.keys(i).length&&(n.url=i);let a=e=>{let t={};return e.notePath.trim()&&(t.note={path:e.notePath.trim(),...e.noteTitle.trim()?{title:e.noteTitle.trim()}:{}}),e.filePath.trim()&&(t.file={path:e.filePath.trim(),...e.fileBackend===`data`?{backend:`data`}:{},...e.fileInsert.trim()?{insert:e.fileInsert.trim()}:{}}),e.notifyReply&&(t.notify=!0),Object.keys(t).length?t:null},o=[];for(let n of e.actions){let r=n.a.trim(),i=n.b.trim(),s=n.recursive?{recursive:!0}:{};if(n.kind===`sendFile`){if(!r)throw Error(`Choose a sending account for the file.`);if(!i)throw Error(n.sendDriver===`imap`?`Enter the destination email address.`:`Enter a configured destination conversation.`);if(![`imap`,`slack`,`whatsapp`].includes(n.sendDriver))throw Error(`Choose email, Slack or WhatsApp.`);if(![`document`,`attachments`,`download`].includes(n.sendSource))throw Error(`Choose which files to send.`);if(n.sendSource===`download`&&!o.some(e=>e.action===`download`))throw Error(`Add a Download action before sending its files.`);let e=Wf(n.attachmentMime);if(n.sendSource===`attachments`&&(!e.length||e.some(e=>!/^(\*|[a-z0-9!#$&^_.+-]+\/(\*|[a-z0-9!#$&^_.+-]+)|\*\/\*)$/i.test(e))))throw Error(`Enter attachment MIME types, such as application/pdf.`);if(n.sendDriver===`whatsapp`&&n.sendMessage.length>1024)throw Error(`WhatsApp file captions must be at most 1,024 characters.`);o.push({action:`sendFile`,source:n.sendSource,driver:n.sendDriver,address:r,...n.sendDriver===`imap`?{to:Wf(i),subject:n.sendSubject}:{target:i},...n.sendMessage?{message:n.sendMessage}:{},...n.sendSource===`attachments`?{mime:e.length===1?e[0]:e,...n.attachmentName.trim()?{filename:n.attachmentName.trim()}:{},...n.includeInline?{includeInline:!0}:{}}:{}})}if(n.kind===`link`&&r&&o.push({action:`link`,paths:Wf(r),...s,...i?{tags:Wf(i)}:{}}),n.kind===`unlink`&&r&&o.push({action:`unlink`,paths:Wf(r),...s}),n.kind===`tag`&&r&&o.push({action:`tag`,tags:Wf(r)}),n.kind===`moveMessage`){if(!r)throw Error(`Enter the mail folder to move the email to, such as INBOX/Accounting/{{YYYY}}/Expenses.`);o.push({action:`moveMessage`,folder:r})}if(n.kind===`store`&&r){if(n.storeMode===`move`&&!n.storeFrom.trim())throw Error(`Choose the source backend whose copy should be moved.`);if(n.recursive&&!qf(e.conditions))throw Error(`Choose a Directory/Backends source path, or one exact Context insertion path, to recreate the path.`);if(n.recursive&&t.find(e=>e.address===r)?.capabilities?.paths!==!0)throw Error(`This destination has not reported support for folder paths. Choose a supported backend or turn off path recreation.`);let a=n.storeFolder.trim().replace(/^\/+|\/+$/g,``),c=n.storeName===`title`?Lf:n.storeName===`dated`?Rf:n.storeName===`custom`?i:``;o.push({action:`store`,to:r,...n.storeFrom.trim()?{from:n.storeFrom.trim()}:{},mode:n.storeMode,...a?{folder:a}:{},...s,...n.recursive&&Kf(e.conditions)!==null?{pathMode:`full`}:{},...c?{key:c}:{},onConflict:n.storeConflict})}if(n.kind===`extractAttachments`){if(!r)throw Error(`Choose a destination backend for the attachments.`);if(t.find(e=>e.address===r)?.capabilities?.paths!==!0)throw Error(`Choose an attachment destination with support for folder paths.`);let e=Wf(n.attachmentMime);if(!e.length||e.some(e=>!/^(\*|[a-z0-9!#$&^_.+-]+\/(\*|[a-z0-9!#$&^_.+-]+)|\*\/\*)$/i.test(e)))throw Error(`Enter attachment MIME types, such as application/pdf or image/*. Use * for all attachments.`);if(![`rename`,`error`].includes(n.storeConflict))throw Error(`Choose rename or skip for attachment filename conflicts.`);o.push({action:`extractAttachments`,to:r,mime:e.length===1?e[0]:e,...n.storeFolder.trim()?{folder:n.storeFolder.trim()}:{},...n.attachmentPath.trim()?{subfolder:n.attachmentPath.trim()}:{},...n.attachmentName.trim()?{filename:n.attachmentName.trim()}:{},...n.includeInline?{includeInline:!0}:{},onConflict:n.storeConflict})}if(n.kind===`download`){let e=n.storeFolder.trim().replace(/^\/+|\/+$/g,``),t=Number(n.dlDepth);o.push({action:`download`,to:r||`workspace:home`,...e?{folder:e}:{},...s,...n.dlKind===`auto`?{}:{kind:n.dlKind},...i?{insert:Wf(i)}:{},...n.dlTags.trim()?{tags:Wf(n.dlTags)}:{},...n.dlKind===`website`&&Number.isFinite(t)&&t>0&&t!==2?{depth:t}:{}})}if(n.kind===`unstore`&&r&&o.push({action:`unstore`,from:r,...i?{ifOn:i}:{},...n.keepLast?{}:{keepLast:!1}}),n.kind===`notify`&&r&&o.push({action:`notify`,message:r}),n.kind===`delete`&&o.push({action:`delete`}),n.kind===`destroy`&&o.push({action:`destroy`}),n.kind===`agent`&&r&&i){let e=a(n);o.push({action:`agent`,slug:r,prompt:i,...e?{output:e}:{}})}if(n.kind===`script`&&r){let e=a(n);o.push({action:`script`,path:r,...e?{output:e}:{}})}}return{id:e.id||Uf(e.description),enabled:!0,...e.description?{description:e.description}:{},...e.cascade?{cascade:!0}:{},...e.approval?{approval:!0}:{},...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},when:n,then:o}}function Xf(e){let{event:t,schema:n,from:r,to:i,subject:a,body:o,sender:s,thread:c,channel:l,platform:u,path:d,pathExact:f,eventPathExact:p,mime:m,url:h,attachment:g,..._}=e.when;if(Object.keys(_).length>0)return null;let v=Array.isArray(t)?t:[t];if(!v.length||!v.every(e=>typeof e==`string`&&jf.some(t=>t.value===e))||n!==void 0&&typeof n!=`string`)return null;let y=[],b=(e,t)=>{let n=Array.isArray(t)?t:[t];if(e.endsWith(`Regex`)){if(!n.every(e=>typeof e==`string`))return!1;for(let t of n)y.push({field:e,value:t})}else if(Nf.has(e))for(let t of n){if(!t||typeof t!=`object`||Object.keys(t).length!==1||typeof t.equals!=`string`)return!1;y.push({field:e,value:t.equals})}else if([`from`,`to`,`subject`,`body`,`sender`].includes(e))for(let t of n)if(typeof t==`string`)y.push({field:e,value:t});else if([`from`,`to`,`sender`].includes(e)&&t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.equals==`string`)y.push({field:`${e}Exact`,value:t.equals});else if(t&&typeof t==`object`&&Object.keys(t).length===1&&typeof t.regex==`string`)y.push({field:`${e}Regex`,value:t.regex});else return!1;else{if(!n.every(e=>typeof e==`string`))return!1;y.push({field:e,value:n.join(` | `)})}return!0};if(d!==void 0&&!b(`path`,d)||f!==void 0&&!b(`pathExact`,f)||p!==void 0&&!b(`eventPathExact`,p)||m!==void 0&&!b(`mime`,m)||r!==void 0&&!b(`from`,r)||i!==void 0&&!b(`to`,i)||a!==void 0&&!b(`subject`,a)||o!==void 0&&!b(`body`,o)||s!==void 0&&!b(`sender`,s)||c!==void 0&&!b(`threadExact`,c)||l!==void 0&&!b(`channelExact`,l)||u!==void 0&&!b(`platformExact`,u)||g!==void 0&&!b(`attachment`,g))return null;if(h!==void 0){if(typeof h==`string`)y.push({field:`urlContains`,value:h});else if(h&&typeof h==`object`){let e=h;if(Object.keys(e).filter(e=>e!==`host`&&e!==`contains`&&e!==`regex`).length||e.host!==void 0&&!b(`urlHost`,e.host)||e.contains!==void 0&&!b(`urlContains`,e.contains)||e.regex!==void 0&&!b(`urlRegex`,e.regex))return null}else return null}let x=e=>{let t=e.output&&typeof e.output==`object`?e.output:{};if(Object.keys(t).filter(e=>e!==`note`&&e!==`file`&&e!==`notify`).length)return null;let n=t.note&&typeof t.note==`object`?t.note:{},r=t.file&&typeof t.file==`object`?t.file:{};return Object.keys(r).filter(e=>e!==`path`&&e!==`backend`&&e!==`insert`).length?null:{notePath:typeof n.path==`string`?n.path:``,noteTitle:typeof n.title==`string`?n.title:``,filePath:typeof r.path==`string`?r.path:``,fileBackend:r.backend===`data`?`data`:`home`,fileInsert:typeof r.insert==`string`?r.insert:``,notifyReply:t.notify===!0}},S=[];for(let t of e.then||[]){if(t.approval!==void 0)return null;if(t.action===`link`&&Array.isArray(t.paths))S.push({...Z(`link`),a:t.paths.join(`, `),b:Array.isArray(t.tags)?t.tags.join(`, `):``,recursive:t.recursive===!0});else if(t.action===`unlink`&&Array.isArray(t.paths))S.push({...Z(`unlink`),a:t.paths.join(`, `),recursive:t.recursive===!0});else if(t.action===`tag`&&Array.isArray(t.tags))S.push({...Z(`tag`),a:t.tags.join(`, `)});else if(t.action===`moveMessage`){if(Object.keys(t).some(e=>e!==`action`&&e!==`folder`)||typeof t.folder!=`string`)return null;S.push({...Z(`moveMessage`),a:t.folder})}else if(t.action===`notify`&&typeof t.message==`string`)S.push({...Z(`notify`),a:t.message});else if(t.action===`store`&&typeof t.to==`string`){if(t.pathMode!==void 0&&(t.pathMode!==`full`||t.recursive!==!0||Kf(y)===null)||t.recursive===!0&&Kf(y)!==null&&t.pathMode!==`full`||t.folder!==void 0&&typeof t.folder!=`string`||t.key!==void 0&&typeof t.key!=`string`)return null;let e=typeof t.key==`string`?t.key:``;S.push({...Z(`store`),a:t.to,b:e===Lf||e===Rf?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===Lf?`title`:e===Rf?`dated`:`custom`:`keep`,storeFrom:typeof t.from==`string`?t.from:Array.isArray(t.from)?String(t.from[0]??``):``,storeMode:t.mode===`move`?`move`:`copy`,storeConflict:t.onConflict===`error`||t.onConflict===`overwrite`?t.onConflict:`rename`})}else if(t.action===`sendFile`){let e=new Set([`action`,`source`,`driver`,`address`,`to`,`target`,`subject`,`message`,`mime`,`filename`,`includeInline`]);if(Object.keys(t).some(t=>!e.has(t))||![`imap`,`slack`,`whatsapp`].includes(String(t.driver))||typeof t.address!=`string`||t.source!==void 0&&![`document`,`attachments`,`download`].includes(String(t.source))||[`target`,`subject`,`message`,`filename`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.includeInline!==void 0&&typeof t.includeInline!=`boolean`)return null;let n=Array.isArray(t.to)?t.to:t.to===void 0?[]:[t.to],r=Array.isArray(t.mime)?t.mime:[t.mime??`*`];if(!n.every(e=>typeof e==`string`)||!r.every(e=>typeof e==`string`)||(t.driver===`imap`?t.target!==void 0:t.to!==void 0||t.subject!==void 0))return null;S.push({...Z(`sendFile`),a:t.address,b:t.driver===`imap`?n.join(`, `):String(t.target||``),sendDriver:t.driver,sendSource:t.source||`document`,sendSubject:String(t.subject??`{{file.name}}`),sendMessage:String(t.message||``),attachmentMime:r.join(`, `),attachmentName:String(t.filename||``),includeInline:t.includeInline===!0})}else if(t.action===`extractAttachments`){let e=new Set([`action`,`to`,`folder`,`subfolder`,`mime`,`filename`,`includeInline`,`onConflict`]);if(Object.keys(t).some(t=>!e.has(t))||typeof t.to!=`string`||[`folder`,`subfolder`,`filename`].some(e=>t[e]!==void 0&&typeof t[e]!=`string`)||t.includeInline!==void 0&&typeof t.includeInline!=`boolean`||t.onConflict!==void 0&&t.onConflict!==`rename`&&t.onConflict!==`error`)return null;let n=Array.isArray(t.mime)?t.mime:[t.mime??`*`];if(!n.every(e=>typeof e==`string`))return null;S.push({...Z(`extractAttachments`),a:t.to,storeFolder:typeof t.folder==`string`?t.folder:``,attachmentPath:typeof t.subfolder==`string`?t.subfolder:``,attachmentMime:n.join(`, `),attachmentName:typeof t.filename==`string`?t.filename:``,includeInline:t.includeInline===!0,storeConflict:t.onConflict===`error`?`error`:`rename`})}else if(t.action===`download`){let e=new Set([`action`,`to`,`folder`,`recursive`,`kind`,`insert`,`tags`,`depth`]);if(Object.keys(t).some(t=>!e.has(t)))return null;let n=typeof t.kind==`string`?t.kind:`auto`;if(!zf.some(e=>e.value===n))return null;let r=Array.isArray(t.insert)?t.insert:typeof t.insert==`string`?[t.insert]:[];if(!r.every(e=>typeof e==`string`))return null;S.push({...Z(`download`),a:typeof t.to==`string`?t.to:`workspace:home`,b:r.join(`, `),storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,dlKind:n,dlDepth:typeof t.depth==`number`?String(t.depth):`2`,dlTags:Array.isArray(t.tags)?t.tags.join(`, `):``})}else if(t.action===`unstore`&&(typeof t.from==`string`||Array.isArray(t.from))){let e=e=>Array.isArray(e)?String(e[0]??``):typeof e==`string`?e:``;S.push({...Z(`unstore`),a:e(t.from),b:e(t.ifOn),keepLast:t.keepLast!==!1})}else if(t.action===`delete`)S.push(Z(`delete`));else if(t.action===`destroy`)S.push(Z(`destroy`));else if(t.action===`agent`&&typeof t.slug==`string`&&typeof t.prompt==`string`){let e=x(t);if(!e)return null;S.push({...Z(`agent`),a:t.slug,b:t.prompt,...e})}else if(t.action===`script`&&typeof t.path==`string`){let e=x(t);if(!e)return null;S.push({...Z(`script`),a:t.path,...e})}else return null}return{id:e.id,description:e.description||``,events:v,schema:typeof n==`string`?n:``,cascade:e.cascade===!0,approval:e.approval===!0,...e.editable?.length?{editable:e.editable}:{},...e.ttl===void 0?{}:{ttl:e.ttl},conditions:y,actions:S.length?S:[Z(`link`)]}}var Zf=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function Qf(e,t=Af){let n=e.when,r=Vd(e).map(e=>jf.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${Zf(n.schema,t)} ${r}`],a=e=>Array.isArray(e)?e.join(` or `):typeof e==`object`&&e?JSON.stringify(e):String(e),o={path:`under`,pathExact:`directly in`,eventPathExact:`inserted / linked directly into`,mime:`type`,from:`from`,to:`to`,subject:`subject`,body:`body / text`,sender:`sender`,thread:`thread`,channel:`conversation`,platform:`platform`,url:`url`,attachment:`attachment`};for(let e of Object.keys(o))n[e]!==void 0&&i.push(`${o[e]} ${a(n[e])}`);return i.join(` · `)}function $f(e){let t=e.output||{},n=t.note||{},r=t.file||{};return[n.path?`reply → note ${n.path}`:``,r.path?`reply → file ${r.backend===`data`?`data:`:`home/`}${r.path}${r.insert?` (indexed at ${r.insert})`:``}`:``,t.notify?`reply → notify`:``].filter(Boolean).join(`, `)}function ep(e){if(e.action===`link`)return`file into ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`unlink`)return`remove from ${e.paths?.join(`, `)}${e.recursive===!0?` (sub-folders kept)`:``}`;if(e.action===`tag`)return`tag ${e.tags?.join(`, `)}`;if(e.action===`store`){let t=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,n=e.key===Lf?`, named by title`:e.key===Rf?`, by date`:typeof e.key==`string`&&e.key?`, as ${e.key}`:``;return`${e.mode===`move`?`move`:`copy`} the file to ${e.to}${t}${e.recursive===!0?e.pathMode===`full`?` (full directory path recreated)`:` (sub-folder path recreated)`:``}${n}`}if(e.action===`extractAttachments`){let t=[e.to,e.folder,e.subfolder].filter(Boolean).join(`/`);return`extract ${Array.isArray(e.mime)?e.mime.join(`, `):e.mime||`all`} attachments to ${t}${e.filename?` (filename contains ${e.filename})`:``}`}if(e.action===`moveMessage`)return`move the email to mail folder ${e.folder}`;if(e.action===`download`){let t=zf.find(t=>t.value===(e.kind||`auto`)),n=typeof e.folder==`string`&&e.folder?`/${e.folder}`:``,r=Array.isArray(e.insert)&&e.insert.length?`, filed at ${e.insert.join(`, `)}`:`, filed next to the link`;return`download ${t?.value===`auto`?`the link (auto-detected)`:t?.label||e.kind} to ${e.to||`workspace:home`}${n}${e.recursive===!0?` (sub-folders kept)`:``}${r}`}if(e.action===`unstore`)return`delete the file from ${Array.isArray(e.from)?e.from.join(`, `):e.from}${e.ifOn?` once it is on ${Array.isArray(e.ifOn)?e.ifOn.join(`, `):e.ifOn}`:``}`;if(e.action===`sendFile`)return`send ${e.source===`attachments`?`matching attachments`:e.source===`download`?`downloaded files`:`the file`} via ${e.driver===`imap`?`email`:e.driver} to ${Array.isArray(e.to)?e.to.join(`, `):e.to||e.target||`…`}`;if(e.action===`notify`)return`send me a notification`;if(e.action===`delete`)return`delete from Canvas (keeps stored files/mail)`;if(e.action===`destroy`)return`⚠ delete everywhere (index + storage)`;if(e.action===`agent`){let t=$f(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=$f(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function tp(e){return(e.then||[]).map(ep).join(` · `)||`(no actions)`}function np(e){return Hd(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function rp(e){let t={};for(let n of e){if(n.handlerType!==`rule`)continue;let e=t[n.handler]||={count:0,errors:0,last:n};e.count++,n.status===`error`&&e.errors++,n.ts>e.last.ts&&(e.last=n)}return t}function ip(e){let t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return``;let n=Math.floor(t/6e4);if(n<1)return`just now`;if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function ap(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function op(e){if(e.kind===`document`&&e.rule)return{...Xf(e.rule)||Vf,id:null};if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...Vf,description:`Download links${t}`,schema:`tab`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...Z(`download`),a:e.storeTo||``,storeFolder:e.storeFolder||`Downloads`,recursive:!0}]}}if(e.kind===`store`){let t=e.path||``,n=/^(?:(?:ctx|context):)?\//.test(t),r=[{field:n?`eventPathExact`:`path`,value:n&&t.startsWith(`/`)?`ctx:${t}`:t}],i=e.path?`${n?` inserted / linked directly into`:` filed under`} ${e.path.replace(/^(ctx|context|dir|directory):/,``)}`:``;return{...Vf,description:e.storeTo?`Copy files${i} to ${e.storeTo}${e.storeFolder?`/${e.storeFolder}`:``}`:`Copy files${i} to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:r,actions:[{...Z(`store`),a:e.storeTo||``,storeFolder:e.storeFolder||``,recursive:qf(r)}]}}return{...Vf,description:`Mirror ${e.path} into ${e.target}`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:e.path||``}],actions:[{...Z(`link`),a:e.target||`dir:/`,recursive:!0}]}}var sp=`h-10 w-full rounded-md border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring disabled:opacity-50`,Q=`h-10 text-sm`;function $({label:e,hint:t,children:n,className:r}){return(0,X.jsxs)(`label`,{className:H(`flex min-w-0 flex-col gap-1.5`,r),children:[(0,X.jsx)(`span`,{className:`text-sm font-medium`,children:e}),n,t&&(0,X.jsx)(`span`,{className:`text-xs leading-relaxed text-muted-foreground`,children:t})]})}function cp({checked:e,onChange:t,label:n,hint:r,disabled:i}){return(0,X.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:i,onClick:()=>t(!e),className:H(`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-accent/40 disabled:cursor-not-allowed disabled:opacity-50`,e&&`border-primary/40 bg-primary/5`),children:[(0,X.jsx)(`span`,{className:H(`mt-0.5 inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5 transition-colors`,e?`bg-primary`:`bg-muted-foreground/30`),children:(0,X.jsx)(`span`,{className:H(`h-4 w-4 rounded-full bg-background shadow transition-transform`,e&&`translate-x-4`)})}),(0,X.jsxs)(`span`,{className:`min-w-0`,children:[(0,X.jsx)(`span`,{className:`block text-sm font-medium`,children:n}),r&&(0,X.jsx)(`span`,{className:`block text-xs leading-relaxed text-muted-foreground`,children:r})]})]})}function lp({value:e,options:t,onChange:n}){return(0,X.jsx)(`div`,{className:`inline-flex h-10 rounded-md border bg-background p-1`,children:t.map(t=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>n(t.value),className:H(`rounded px-3 text-sm transition-colors`,e===t.value?`bg-primary text-primary-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:t.label},t.value))})}function up({active:e,onClick:t,children:n,title:r}){return(0,X.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:H(`h-9 rounded-full border px-3.5 text-sm transition-colors`,e?`border-primary bg-primary/10 font-medium text-foreground`:`text-muted-foreground hover:bg-accent hover:text-foreground`),children:n})}function dp({step:e,title:t,hint:n}){return(0,X.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,X.jsx)(`span`,{className:`mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary`,children:e}),(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h3`,{className:`text-base font-semibold leading-7`,children:t}),n&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]})]})}function fp({icon:e,tone:t,size:n=`md`}){return(0,X.jsx)(`span`,{className:H(`inline-flex shrink-0 items-center justify-center rounded-xl`,n===`lg`?`h-12 w-12`:`h-10 w-10`,t),children:(0,X.jsx)(e,{className:n===`lg`?`h-6 w-6`:`h-5 w-5`})})}function pp({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:i,onPrefillConsumed:a,createOnly:o=!1,onCreated:s,onCancel:c}){let{showToast:l}=wt(),[u,d]=(0,J.useState)([]),[f,p]=(0,J.useState)({}),m=e=>{Qd(e,{limit:500}).then(e=>p(rp(e))).catch(()=>p({}))},[h,_]=(0,J.useState)(!0),[v,y]=(0,J.useState)(null),[b,x]=(0,J.useState)(!1),[S,C]=(0,J.useState)(!1),[w,T]=(0,J.useState)([]),[D,O]=(0,J.useState)([]),[j,ee]=(0,J.useState)([]),[M,N]=(0,J.useState)(``),P=(0,J.useRef)(null),[F,I]=(0,J.useState)(e);e!==F&&(I(e),_(!0)),(0,J.useEffect)(()=>{qd(e).then(e=>d(e)).finally(()=>_(!1)),m(e)},[e]);let[L,te]=(0,J.useState)(null);i!==L&&(te(i),i&&(y(op(i)),x(!1))),(0,J.useEffect)(()=>{i&&a?.()},[i,a]),(0,J.useEffect)(()=>{Tf(e).then(e=>T(e.map(e=>e.path))).catch(()=>T([]))},[e]),(0,J.useEffect)(()=>{let t=!1;return wl(e).then(e=>{t||(ee([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),N(``))}).catch(()=>{t||(ee([]),N(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,J.useEffect)(()=>{an(e).then(e=>{let t=e.filter(e=>e.kind===`storage`&&e.enabled!==!1&&e.config?.supported!==!1&&e.config?.readOnly!==!0&&e.capabilities?.write!==!1);O(t);let n=ap(t);n&&y(e=>e&&e.actions.some(e=>(e.kind===`store`||e.kind===`download`)&&!e.a)?{...e,actions:e.actions.map(e=>(e.kind===`store`||e.kind===`download`)&&!e.a?{...e,a:n}:e)}:e)}).catch(()=>O([]))},[e]);let[re,ie]=(0,J.useState)(Af);(0,J.useEffect)(()=>{lf(e).then(e=>{e.schemas?.length&&ie([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let ae=async(t,n)=>{C(!0);try{return await Jd(e,t),d(t),l({title:n,description:`rules.json updated (committed to workspace git)`}),!0}catch(e){return l({title:`Error`,description:e instanceof Error?e.message:`Failed to save rules`,variant:`destructive`}),!1}finally{C(!1)}},oe=async()=>{if(!v||h||S)return;let t;try{t=Yf(v,D)}catch(e){l({title:`Invalid rule`,description:e instanceof Error?e.message:`Check the rule conditions and actions`,variant:`destructive`});return}if(!t.then.length){l({title:`Add an action`,description:`Pick at least one "then" action and fill in its fields.`,variant:`destructive`});return}if(o){t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`,C(!0);try{await df(e,t),l({title:`Rule created`,description:`The rule will run for matching new items.`}),s?.()}catch(e){l({title:`Could not create rule`,description:e instanceof Error?e.message:`Failed to save rule`,variant:`destructive`})}finally{C(!1)}return}!v.id&&u.some(e=>e.id===t.id)&&(t.id=`${t.id}-${Math.random().toString(36).slice(2,10)}`);let n=v.id?u.map(e=>e.id===v.id?{...t,enabled:e.enabled!==!1}:e):[...u,t];await ae(n,v.id?`Rule updated`:`Rule created`)&&(y(null),s?.())},R=e=>ae(u.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),se=e=>{confirm(`Delete rule "${e}"?`)&&ae(u.filter(t=>t.id!==e),`Rule deleted`)},[le,ue]=(0,J.useState)(null),de=async t=>{ue(t);try{let n=await of(e,{ruleId:t,dryRun:!0,limit:r}),i=n.results.filter(e=>e.matched).length;if(!i){l({title:`Apply to existing items`,description:`No matches among ${n.processed} existing documents (conditions evaluate against each document's current tree placements). Raise the batch size in the toolbar to cover more.`});return}if(!confirm(`Rule "${t}" matches ${i} of ${n.processed} existing documents. Run its actions on them now?`))return;let a=await of(e,{ruleId:t,limit:r});l({title:`Done`,description:`${a.matched} documents processed, ${a.failed} failed. Details in the Runs tab`,...a.failed?{variant:`destructive`}:{}})}catch(e){l({title:`Backfill failed`,description:e instanceof Error?e.message:`Unknown error`,variant:`destructive`})}finally{ue(null),m(e)}},z=(e,t)=>y(n=>n&&{...n,[e]:t}),fe=e=>{y(e.build({backend:ap(D)})),x(!1),requestAnimationFrame(()=>P.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},me=e=>{let n=Xf(e);n?(y(n),x(!1),requestAnimationFrame(()=>P.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[ge,_e]=(0,J.useState)(null),ve=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,ye=(e,t)=>{if(!ge||!v||!e.length){_e(null);return}if(ge.target===`storeFolder`){let t=Ud(e[0]);z(`actions`,v.actions.map((e,n)=>n===ge.index?{...e,storeFolder:t?.rel||``,...t?.backend&&D.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(ge.target===`condition`){let n=e.map(e=>ve(e,t)),r=t.treeType===`context`&&v.actions.some(e=>e.kind===`store`);z(`conditions`,v.conditions.map((e,t)=>t===ge.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>ve(e,t));z(`actions`,v.actions.map((e,t)=>t===ge.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}_e(null)},be=(e,t,n=`Browse…`)=>(0,X.jsxs)(G,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>_e({target:e,index:t}),children:[(0,X.jsx)(g,{className:`h-4 w-4 sm:mr-1.5`}),(0,X.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),xe=qf(v?.conditions||[]),B=!!v?.conditions.some(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&e.value.trim()),Se=e=>`${e.address}${e.address===`workspace:data`?` — managed blob store (default)`:e.address===`workspace:home`?` — workspace home folder`:e.driver?` — ${e.driver}`:``}`,Ce=(e,t,n,r=`workspace:home`)=>D.length?(0,X.jsxs)(`select`,{className:sp,value:e,onChange:e=>t(e.target.value),children:[(0,X.jsx)(`option`,{value:``,children:n}),D.map(e=>(0,X.jsx)(`option`,{value:e.address,children:Se(e)},e.address)),e&&!D.some(t=>t.address===e)&&(0,X.jsx)(`option`,{value:e,children:e})]}):(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),we=u.filter(np),Ee=u.filter(e=>!np(e)),De=({rule:e})=>{let t=e.enabled!==!1,r=Xf(e)!==null,i=f[e.id],a=If(e.then?.[0]?.action||`link`),o=Hd(e);return(0,X.jsxs)(`div`,{className:H(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,X.jsx)(fp,{icon:a.icon,tone:a.tone}),(0,X.jsxs)(`div`,{className:`rule-card-content min-w-0 space-y-1.5`,children:[(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,X.jsx)(`h3`,{className:`text-base font-semibold leading-6`,children:e.description||e.id}),e.approval===!0&&(0,X.jsx)(`span`,{className:`rounded-full bg-warning/15 px-2 py-0.5 text-xs font-medium text-warning`,children:`needs approval`}),e.cascade===!0&&(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:`incl. automation-created`}),!r&&(0,X.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,title:`This rule uses matchers the builder cannot show; edit it as JSON.`,children:`JSON only`})]}),(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:Qf(e,re)}),(0,X.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,X.jsx)(Te,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,X.jsx)(`span`,{children:tp(e)})]}),o.length>0&&(0,X.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:o.join(` | `),children:o.join(` | `)}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?(0,X.jsxs)(`button`,{type:`button`,className:H(`text-left underline-offset-2 hover:underline`,i.last.status===`error`&&`text-destructive`,!n&&`cursor-default hover:no-underline`),title:n?`Show this rule's run log`:i.last.error||i.last.skipReason||``,onClick:()=>n?.(e.id),children:[`ran `,i.count,`×`,i.errors?` (${i.errors} failed)`:``,` · last `,i.last.status,` `,ip(i.last.ts)]}):`not run yet`})]}),(0,X.jsxs)(`div`,{className:`rule-card-actions`,children:[(0,X.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":t,disabled:S,title:t?`Enabled — click to pause`:`Paused — click to enable`,onClick:()=>R(e.id),className:H(`mr-1 inline-flex h-6 w-11 items-center rounded-full p-0.5 transition-colors`,t?`bg-primary`:`bg-muted-foreground/30`),children:(0,X.jsx)(`span`,{className:H(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,X.jsxs)(G,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:e.when.eventPathExact===void 0?`Apply this rule to existing items (dry-run first)`:`Requires an original insert/link event. Current folder membership cannot reconstruct its destination.`,disabled:le!==null||e.when.eventPathExact!==void 0,onClick:()=>de(e.id),children:[le===e.id?(0,X.jsx)(ut,{className:`h-4 w-4 animate-spin`}):(0,X.jsx)(A,{className:`h-4 w-4`}),(0,X.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Apply`})]}),(0,X.jsxs)(G,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>me(e),children:[r?(0,X.jsx)(k,{className:`h-4 w-4`}):(0,X.jsx)(he,{className:`h-4 w-4`}),(0,X.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,X.jsx)(G,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>se(e.id),children:(0,X.jsx)(pe,{className:`h-4 w-4`})})]})]})},Oe=(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,X.jsx)(`h3`,{className:`text-base font-semibold`,children:`What should happen automatically?`}),b&&(0,X.jsxs)(G,{size:`sm`,variant:`ghost`,onClick:()=>x(!1),children:[(0,X.jsx)(E,{className:`mr-1 h-4 w-4`}),` Close`]})]}),(0,X.jsx)(`div`,{className:`grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,17rem),1fr))] gap-3`,children:Gf.map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>fe(e),className:`flex min-w-0 items-start gap-3 rounded-xl border bg-card p-4 text-left transition-colors hover:border-primary/50 hover:bg-accent/40`,children:[(0,X.jsx)(fp,{icon:e.icon,tone:e.tone,size:`lg`}),(0,X.jsxs)(`span`,{className:`min-w-0`,children:[(0,X.jsx)(`span`,{className:`block text-base font-semibold leading-6`,children:e.title}),(0,X.jsx)(`span`,{className:`mt-1 block break-words text-sm leading-relaxed text-muted-foreground`,children:e.blurb})]})]},e.id))})]});return(0,X.jsxs)(`div`,{className:`rule-builder min-w-0 space-y-5`,children:[!o&&(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 flex-[1_1_20rem]`,children:[(0,X.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Rules`}),(0,X.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Rules run automatically as items arrive or get filed — no code needed. Stored in`,` `,(0,X.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` in the workspace git.`]})]}),(0,X.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[t&&(0,X.jsxs)(G,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,X.jsx)(he,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,X.jsxs)(G,{onClick:()=>{y(null),x(!0)},disabled:b,children:[(0,X.jsx)(ze,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),b&&!v&&Oe,v&&(0,X.jsxs)(`div`,{ref:P,className:`scroll-mt-4 space-y-6 rounded-xl border bg-card p-4 sm:p-6`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,X.jsx)(`h3`,{className:`text-lg font-semibold`,children:v.id?`Edit rule`:`New rule`}),(0,X.jsxs)(G,{variant:`ghost`,size:`sm`,onClick:()=>y(null),children:[(0,X.jsx)(E,{className:`mr-1 h-4 w-4`}),` Cancel`]})]}),(0,X.jsx)($,{label:`Name`,hint:`Shown in the list and the run log.`,children:(0,X.jsx)(U,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:v.description,onChange:e=>z(`description`,e.target.value)})}),(0,X.jsxs)(`section`,{className:`space-y-4`,children:[(0,X.jsx)(dp,{step:1,title:`When…`,hint:`What the rule reacts to. All conditions must match; repeat a condition for either/or.`}),(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-[minmax(0,220px)_1fr]`,children:[(0,X.jsx)($,{label:`Item`,children:(0,X.jsxs)(`select`,{className:sp,value:v.schema,onChange:e=>z(`schema`,e.target.value),children:[re.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value)),v.schema&&!re.some(e=>e.value===v.schema)&&(0,X.jsx)(`option`,{value:v.schema,children:v.schema.replace(/^data\/schema\//,``)})]})}),(0,X.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,X.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Event `,(0,X.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(any of)`})]}),(0,X.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:jf.map(e=>{let t=v.events.includes(e.value);return(0,X.jsx)(up,{active:t,title:e.hint,onClick:()=>{let n=t?v.events.filter(t=>t!==e.value):[...v.events,e.value];n.length&&z(`events`,n)},children:e.label},e.value)})})]})]}),v.conditions.length>0&&(0,X.jsx)(`div`,{className:`space-y-2`,children:v.conditions.map((e,t)=>{let n=Mf.find(t=>t.key===e.field);return(0,X.jsxs)(`div`,{className:`grid grid-cols-[2.25rem_1fr_auto] items-center gap-2 sm:grid-cols-[2.25rem_minmax(0,240px)_1fr_auto]`,children:[(0,X.jsx)(`span`,{className:`text-xs font-medium uppercase tracking-wide text-muted-foreground`,title:`Same condition again = either may match (OR); different conditions must all match (AND)`,children:v.conditions.slice(0,t).some(t=>Pf(t.field)===Pf(e.field))?`or`:`and`}),(0,X.jsx)(`select`,{className:sp,value:e.field,onChange:e=>z(`conditions`,v.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:Mf.map(e=>(0,X.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,X.jsxs)(`div`,{className:`order-4 col-span-3 flex gap-2 sm:order-3 sm:col-span-1`,children:[(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>z(`conditions`,v.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&be(`condition`,t,`Browse the workspace trees`)]}),(0,X.jsx)(G,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>z(`conditions`,v.conditions.filter((e,n)=>n!==t)),children:(0,X.jsx)(E,{className:`h-4 w-4`})})]},t)})}),(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,X.jsxs)(G,{size:`sm`,variant:`outline`,onClick:()=>z(`conditions`,[...v.conditions,{field:v.schema===`email`?`from`:`path`,value:``}]),children:[(0,X.jsx)(ze,{className:`mr-1 h-4 w-4`}),` Add condition`]}),(0,X.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Contains matches literal text. Regex is case-insensitive: enter the pattern without /…/ delimiters; | stays part of the expression. For other filters, separate alternatives with `,(0,X.jsx)(`span`,{className:`font-mono`,children:`|`}),`, e.g. `,(0,X.jsx)(`span`,{className:`font-mono`,children:`image/* | video/*`}),`.`]})]})]}),(0,X.jsxs)(`section`,{className:`space-y-4`,children:[(0,X.jsx)(dp,{step:2,title:`Then…`,hint:`Actions run in order. The item keeps its id, tags and folders unless an action says otherwise.`}),v.actions.map((t,n)=>{let r=e=>z(`actions`,v.actions.map((t,r)=>r===n?{...t,...e}:t)),i=D.find(e=>e.address===t.a),a=i?.capabilities?.paths===!0,o=xe&&a,s=If(t.kind),c=n=>(0,X.jsxs)(`div`,{className:`space-y-3 rounded-lg border border-dashed p-3`,children:[(0,X.jsxs)(`p`,{className:`text-sm font-medium`,children:[`What to do with the `,n]}),(0,X.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Save as a note at`,hint:`Context path by default, dir:/path for the directory tree.`,children:(0,X.jsx)(kf,{inputClassName:Q,placeholder:`/notes/summaries (optional)`,value:t.notePath,onChange:e=>r({notePath:e}),fixedWorkspaceName:e,pickerTitle:`Save note under…`,onPickTarget:(e,t)=>r({notePath:t.treeType===`directory`?`dir:${e}`:e})})}),t.notePath.trim()&&(0,X.jsx)($,{label:`Note title`,children:(0,X.jsx)(U,{className:Q,placeholder:`Summary: {{doc.data.subject}}`,value:t.noteTitle,onChange:e=>r({noteTitle:e.target.value})})}),(0,X.jsx)($,{label:`Save as a file at`,hint:`Relative path under the workspace home folder or in the data blob store.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`logs/agent.log (optional)`,value:t.filePath,onChange:e=>r({filePath:e.target.value})})}),t.filePath.trim()&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{label:`File lives in`,children:(0,X.jsxs)(`select`,{className:sp,value:t.fileBackend,onChange:e=>r({fileBackend:e.target.value}),children:[(0,X.jsx)(`option`,{value:`home`,children:`the workspace home folder`}),(0,X.jsx)(`option`,{value:`data`,children:`the data blob store`})]})}),(0,X.jsx)($,{label:`Also file the saved file under`,hint:`Index it as a document at this tree path.`,children:(0,X.jsx)(kf,{inputClassName:Q,placeholder:`/path (optional)`,value:t.fileInsert,onChange:e=>r({fileInsert:e}),fixedWorkspaceName:e,tabs:[`context`],pickerTitle:`File under…`,onPickTarget:e=>r({fileInsert:e})})})]})]}),(0,X.jsx)(cp,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send me a notification with the result`})]}),l=Kf(v.conditions),u=t.kind===`store`&&t.a&&(!t.recursive||o)?Jf(t,v.conditions,i):null,d=t.kind===`extractAttachments`&&t.a?Cf(t.a,t.storeFolder,t.attachmentPath):null;return(0,X.jsxs)(`div`,{className:`space-y-4 rounded-xl border bg-background p-4`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,X.jsx)(fp,{icon:s.icon,tone:s.tone}),(0,X.jsx)(`select`,{className:H(sp,`flex-1 font-medium`),value:t.kind,onChange:e=>r(Z(e.target.value)),children:Ff.map(e=>(0,X.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,X.jsx)(G,{size:`sm`,variant:`ghost`,className:`h-10 w-10 shrink-0 p-0 text-muted-foreground`,title:`Remove action`,disabled:v.actions.length===1,onClick:()=>z(`actions`,v.actions.filter((e,t)=>t!==n)),children:(0,X.jsx)(E,{className:`h-4 w-4`})})]}),(t.kind===`link`||t.kind===`unlink`)&&(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsx)($,{label:t.kind===`link`?`Folder(s)`:`Remove from folder(s)`,hint:`Context-tree path by default; dir:/path for the directory tree. Comma-separate several.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:t.kind===`link`?`/work/urgent or dir:/projects/x`:`/inbox or dir:/staging`,value:t.a,onChange:e=>r({a:e.target.value})}),be(`action`,n)]})}),t.kind===`link`&&(0,X.jsx)($,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,X.jsx)(cp,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:B?`The part of the item's path below the "is under the folder" prefix is appended to the target: …/foo/a/b → target/a/b.`:`Needs an "is under the folder" condition to know where sub-folders start.`,disabled:!B})]}),t.kind===`moveMessage`&&(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)($,{label:`Mail folder`,hint:`The folder on the email's own IMAP account, with / between levels (works for servers that use . too). {{YYYY}}, {{MM}}, {{DD}} = the email's date.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`INBOX/Accounting/{{YYYY}}/Expenses`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Moves the message on the mail server, like dragging it in a mail client. Put this after Extract attachments so the files are copied first. The folder must already exist on the server; subscribe to it in the mailbox settings to see the moved mail in Canvas.`})]}),t.kind===`tag`&&(0,X.jsx)($,{label:`Tags`,hint:`Comma-separated.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`urgent, follow-up`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`store`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Storage backend`,hint:`Where the file's bytes should live. Only writable backends are listed.`,children:Ce(t.a,e=>r({a:e}),`pick a backend…`)}),(0,X.jsx)($,{label:`Destination root folder`,hint:`Choose the folder beneath which the path will be recreated. Leave empty to use the backend root.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),be(`storeFolder`,n,`Browse storage backends`)]})}),(0,X.jsx)($,{label:`File name`,children:(0,X.jsx)(`select`,{className:sp,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:Bf.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,X.jsx)($,{label:`Move or copy`,hint:t.storeMode===`move`?`Remove only the selected source copy after the destination is safely stored.`:`Preserve every existing copy.`,children:(0,X.jsx)(lp,{value:t.storeMode,onChange:e=>r({storeMode:e}),options:[{value:`copy`,label:`Copy`},{value:`move`,label:`Move`}]})}),t.storeMode===`move`&&(0,X.jsx)($,{className:`sm:col-span-2`,label:`Move bytes from (required)`,hint:`Context membership does not identify a source copy. If the file is absent here, nothing is moved. Multiple locations on this backend make the move ambiguous; use copy.`,children:Ce(t.storeFrom,e=>r({storeFrom:e}),`choose a source backend…`,`workspace:data`)}),t.storeName===`custom`&&(0,X.jsx)($,{className:`sm:col-span-2`,label:`Name template`,hint:`Tokens: {{YYYY}} {{MM}} {{DD}} {{HH}} {{mm}} {{ss}} (photo capture time when present), {{ext}} {{basename}} {{filename}} {{title}} {{id}}, plus {{doc.…}} fields. Slashes create sub-folders.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,X.jsx)(cp,{checked:t.recursive,onChange:e=>r({recursive:e}),label:l===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:a?xe?l===null?`The path below the source folder is appended beneath the destination root: …/UI/mobile → Root/mobile. Missing destination folders are created.`:`Only inserts or links directly into ctx:${l} trigger this rule. Its full path is appended beneath the destination root; descendant inserts do not match.`:`For Context, choose one folder with “is inserted / linked directly into”. Directory and Backends sources can include sub-folders.`:`Choose a destination that reports support for folder paths. Content-addressed blob stores cannot recreate sub-folder paths.`,disabled:!o&&!t.recursive}),u&&(0,X.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,X.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,X.jsxs)(`span`,{className:`break-all font-mono`,children:[u.root,`/`]})]}),t.recursive&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,X.jsxs)(`span`,{className:`break-all font-mono`,children:[u.recreated||`(root)`,`/`]})]}),(0,X.jsx)(`p`,{className:`break-all font-mono`,children:u.result})]}),(0,X.jsxs)(`details`,{className:`group rounded-lg border`,children:[(0,X.jsxs)(`summary`,{className:`flex cursor-pointer select-none items-center gap-2 px-3 py-2 text-sm font-medium`,children:[(0,X.jsx)(ce,{className:`h-4 w-4 transition-transform group-open:rotate-180`}),` More options`]}),(0,X.jsxs)(`div`,{className:`grid gap-4 border-t p-3 sm:grid-cols-2`,children:[t.storeMode===`copy`&&(0,X.jsx)($,{label:`Copy bytes from`,hint:`Optional source restriction. Default: any readable copy outside the destination backend.`,children:Ce(t.storeFrom,e=>r({storeFrom:e}),`any readable source`,`workspace:data (optional)`)}),(0,X.jsx)($,{label:`If the name is already taken`,children:(0,X.jsxs)(`select`,{className:sp,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,X.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,X.jsx)(`option`,{value:`error`,children:`skip the file`}),(0,X.jsx)(`option`,{value:`overwrite`,children:`overwrite the existing file`})]})})]})]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The item keeps its id and virtual tree memberships. A move removes the chosen physical source location from the backend tree.`})]}),t.kind===`extractAttachments`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Attachment types`,hint:`MIME types, comma-separated. application/pdf for PDFs, image/* for images, or * for all.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`application/pdf`,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,X.jsx)($,{label:`Attachment filename contains`,hint:`Optional: invoice, faktura, or another literal filename fragment. Every selected attachment must also match its type.`,children:(0,X.jsx)(U,{className:Q,placeholder:`Any matching filename`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})}),(0,X.jsx)($,{label:`Storage backend`,hint:`Choose a writable backend that supports folder paths.`,children:Ce(t.a,e=>r({a:e}),`pick a backend…`)}),(0,X.jsx)($,{label:`Destination root folder`,hint:`Choose the folder beneath which date subfolders will be created. Leave empty to use the backend root.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),be(`storeFolder`,n,`Browse storage backends`)]})}),(0,X.jsx)($,{label:`Sub-folder path template`,hint:`Appended beneath the root folder. {{YYYY}} = year, {{MM}} = month, {{DD}} = day of the email. Leave empty to file directly in the root folder.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`No subfolders`,value:t.attachmentPath,onChange:e=>r({attachmentPath:e.target.value})})}),(0,X.jsx)($,{label:`If the attachment name is already taken`,children:(0,X.jsxs)(`select`,{className:sp,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,X.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,X.jsx)(`option`,{value:`error`,children:`skip the file and report the conflict`})]})})]}),!a&&(0,X.jsx)(`p`,{className:`text-sm text-amber-700 dark:text-amber-400`,children:`This destination has not reported support for folder paths. Select a supported backend before saving.`}),d&&(0,X.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,X.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Example email dated `,d.date,`. Each email supplies its own date.`]}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,X.jsxs)(`span`,{className:`break-all font-mono`,children:[d.root,`/`]})]}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,X.jsx)(`span`,{className:`break-all font-mono`,children:d.added?`${d.added}/`:`(none)`})]}),(0,X.jsx)(`p`,{className:`break-all font-mono`,children:d.result})]}),(0,X.jsx)(cp,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Off by default, so signature images and embedded resources are excluded.`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Copies matching attachments and keeps the email and its original files. Missing folders are created on the backend. Dates use the email's sent date (received/content date, then creation date if absent), in the server's timezone. This does not read the invoice date from the PDF.`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Use Apply on the saved rule to process existing mail within the selected batch size. Add a subject or attachment filename condition if you need to distinguish invoices from other PDFs.`})]}),t.kind===`download`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Download`,hint:zf.find(e=>e.value===t.dlKind)?.hint,children:(0,X.jsx)(`select`,{className:sp,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:zf.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),t.dlKind===`website`?(0,X.jsx)($,{label:`Mirror depth`,hint:`How many link hops to follow on the same site (1–5).`,children:(0,X.jsx)(U,{type:`number`,min:1,max:5,className:H(Q,`sm:max-w-32`),value:t.dlDepth,onChange:e=>r({dlDepth:e.target.value})})}):(0,X.jsx)(`div`,{className:`hidden sm:block`}),(0,X.jsx)($,{label:`Storage backend`,hint:`Where the downloaded file's bytes should live.`,children:Ce(t.a,e=>r({a:e}),`workspace:home (default)`)}),(0,X.jsx)($,{label:`Folder on that backend`,hint:`Relative to the backend root.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),be(`storeFolder`,n,`Browse storage backends`)]})}),(0,X.jsx)($,{label:`File the download under`,hint:`Leave empty to file it in the same folder(s) as the link. Comma-separate several.`,children:(0,X.jsxs)(`div`,{className:`flex gap-2`,children:[(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),be(`action`,n)]})}),(0,X.jsx)($,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,X.jsx)(cp,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:B?`A link filed under …/folder/a/b is downloaded into Folder/a/b.`:`Add an "is under the folder" condition to mirror sub-folders.`,disabled:!B}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The link stays as it is; the download becomes a new file item next to it. Each link is downloaded once per rule. Videos need `,(0,X.jsx)(`span`,{className:`font-mono`,children:`yt-dlp`}),`, pages and websites `,(0,X.jsx)(`span`,{className:`font-mono`,children:`wget`}),` on the server.`]})]}),t.kind===`unstore`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Delete the file from`,children:Ce(t.a,e=>r({a:e}),`pick a backend…`,`workspace:data`)}),(0,X.jsx)($,{label:`…but only once it is also on`,hint:`Safety: the copy is dropped only after another backend holds the file.`,children:Ce(t.b,e=>r({b:e}),`anywhere else`,`workspace:home (optional)`)})]}),(0,X.jsx)(cp,{checked:t.keepLast,onChange:e=>r({keepLast:e}),label:`Never delete the last copy`,hint:`Off means the rule may delete the only remaining copy of a file. Leave it on unless you mean exactly that.`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Deletes the stored bytes on that backend only — copies elsewhere and the item itself are kept.`})]}),t.kind===`sendFile`&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsx)($,{label:`Files to send`,children:(0,X.jsxs)(`select`,{className:sp,value:t.sendSource,onChange:e=>r({sendSource:e.target.value}),children:[(0,X.jsx)(`option`,{value:`document`,children:`The file that triggered this rule`}),(0,X.jsx)(`option`,{value:`attachments`,children:`Matching attachments from the email`}),(0,X.jsx)(`option`,{value:`download`,children:`Files from an earlier Download action`})]})}),t.sendSource===`attachments`&&(0,X.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,X.jsx)($,{label:`Attachment types`,hint:`application/pdf for invoices; * for all files.`,children:(0,X.jsx)(U,{className:Q,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,X.jsx)($,{label:`Attachment filename contains`,hint:`Optional literal filename fragment.`,children:(0,X.jsx)(U,{className:Q,placeholder:`invoice`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})})]}),t.sendSource===`attachments`&&(0,X.jsx)(cp,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Signature images are excluded by default.`}),(0,X.jsx)($,{label:`Sending account`,hint:`Enable sending for the account in Connected services.`,children:(0,X.jsxs)(`select`,{className:sp,value:t.a?`${t.sendDriver}:${t.a}`:``,onChange:e=>{let t=j.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&r({a:t.address,sendDriver:t.driver,b:``})},children:[(0,X.jsx)(`option`,{value:``,disabled:!0,children:`Choose email, WhatsApp or Slack…`}),t.a&&!j.some(e=>e.driver===t.sendDriver&&e.address===t.a)&&(0,X.jsxs)(`option`,{value:`${t.sendDriver}:${t.a}`,disabled:!0,children:[t.sendDriver,`: `,t.a,` (unavailable)`]}),j.map(e=>(0,X.jsxs)(`option`,{value:`${e.driver}:${e.address}`,disabled:!e.canSend,children:[e.driver===`imap`?`Email (SMTP)`:e.driver===`whatsapp`?`WhatsApp`:`Slack`,` · `,e.from||e.address,e.canSend?``:` — sending disabled`]},`${e.driver}:${e.address}`))]})}),M&&(0,X.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:M}),(0,X.jsx)($,{label:t.sendDriver===`imap`?`Destination email address`:`Destination conversation`,hint:t.sendDriver===`imap`?`The accounting ingestion address; separate multiple recipients with commas.`:t.sendDriver===`slack`?`A configured Slack channel ID or name. The account needs files:write permission.`:`A configured WhatsApp chat ID, e.g. 421…@s.whatsapp.net or …@g.us.`,children:(0,X.jsx)(U,{className:Q,value:t.b,placeholder:t.sendDriver===`imap`?`invoices@accounting-firm.example`:t.sendDriver===`slack`?`C0123456789`:`421…@s.whatsapp.net`,onChange:e=>r({b:e.target.value})})}),t.sendDriver===`imap`&&(0,X.jsx)($,{label:`Email subject`,hint:`{{file.name}} inserts the attachment filename.`,children:(0,X.jsx)(U,{className:Q,value:t.sendSubject,onChange:e=>r({sendSubject:e.target.value})})}),(0,X.jsx)($,{label:t.sendDriver===`imap`?`Email body (optional)`:`Message / caption (optional)`,hint:`Templates: {{file.name}}, {{doc.data.subject}}, {{doc.data.title}}.`,children:(0,X.jsx)(`textarea`,{className:`min-h-20 w-full rounded-md border bg-background p-3 text-sm`,value:t.sendMessage,onChange:e=>r({sendMessage:e.target.value})})}),(0,X.jsxs)(`div`,{className:`rounded-lg border bg-muted/30 p-3 text-sm`,"aria-label":`File delivery preview`,children:[t.sendSource===`attachments`?`Each matching email attachment`:t.sendSource===`download`?`Each downloaded file`:`The triggering file`,` → `,t.sendDriver===`imap`?`email attachment`:t.sendDriver===`slack`?`Slack file upload`:`WhatsApp document`,` → `,t.b||`choose a destination`]}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Sends each file in a separate message and keeps the original. Maximum 18 MB per file. Replaying this rule does not resend the same file version to the same destination. Unconfirmed deliveries are recorded for review, not retried automatically.`}),t.sendSource===`document`&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`For files created by another automation, enable this rule’s option to also run on automation events.`})]}),t.kind===`notify`&&(0,X.jsx)($,{label:`Notification`,hint:`Notifies you through your bound channel, or in Canvas. Templates: {{doc.data.subject}}, {{doc.data.from}}, {{doc.data.title}}…`,children:(0,X.jsx)(U,{className:Q,placeholder:`New mail from {{doc.data.from}}: {{doc.data.subject}}`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`delete`&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Removes the item from the Canvas index. Files, blobs and mail on storage backends stay untouched.`}),t.kind===`destroy`&&(0,X.jsx)(`p`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive`,children:`⚠ Irreversible: deletes the stored bytes too (blobs, workspace files, mail on the server), then removes the item from the index.`}),t.kind===`agent`&&(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsx)($,{label:`Agent`,hint:`The agent's slug.`,children:(0,X.jsx)(U,{className:H(Q,`font-mono sm:max-w-xs`),placeholder:`assistant`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,X.jsx)($,{label:`Prompt`,hint:`Templates use indexed fields: {{doc.id}}, {{doc.data.subject}}, {{doc.data.bodyPreview}} (emails), {{doc.data.url}}… Ask the agent to use canvas_get for full email content. Objects are inserted as JSON.`,children:(0,X.jsx)(`textarea`,{className:`min-h-28 w-full rounded-md border bg-background p-3 text-sm outline-none focus:ring-2 focus:ring-ring`,placeholder:`Read email #{{doc.id}} in full with canvas_get and summarize it in plain markdown.
16
+
17
+ Subject: {{doc.data.subject}}
18
+ Preview: {{doc.data.bodyPreview}}`,value:t.b,onChange:e=>r({b:e.target.value})})}),c(`reply`)]}),t.kind===`script`&&(0,X.jsxs)(`div`,{className:`space-y-3`,children:[(0,X.jsx)($,{label:`Script`,hint:`From the Scripts section of this workspace.`,children:w.length?(0,X.jsxs)(`select`,{className:H(sp,`font-mono sm:max-w-md`),value:t.a,onChange:e=>r({a:e.target.value}),children:[(0,X.jsx)(`option`,{value:``,children:`pick a script…`}),w.map(e=>(0,X.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,X.jsx)(U,{className:H(Q,`font-mono sm:max-w-md`),placeholder:`scripts/my-script.sh`,value:t.a,onChange:e=>r({a:e.target.value})})}),c(`output`)]})]},n)}),(0,X.jsxs)(G,{size:`sm`,variant:`outline`,onClick:()=>z(`actions`,[...v.actions,Z(`tag`)]),children:[(0,X.jsx)(ze,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,X.jsxs)(`section`,{className:`space-y-3`,children:[(0,X.jsx)(dp,{step:3,title:`Options`}),(0,X.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,X.jsx)(cp,{checked:v.approval,onChange:e=>z(`approval`,e),label:`Ask me before running`,hint:`Actions are held in the Pending queue for review — approve (optionally amended) or decline — instead of running automatically.`}),(0,X.jsx)(cp,{checked:v.cascade,onChange:e=>z(`cascade`,e),label:`Also react to items created by automation`,hint:`Off by default so rules, hooks and agents cannot trigger each other in a loop. A server-side depth limit still stops runaway chains.`})]})]}),(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,X.jsxs)(G,{className:`h-10 px-5`,onClick:oe,disabled:S||h,children:[S?(0,X.jsx)(ut,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,X.jsx)(ne,{className:`mr-1.5 h-4 w-4`}),` `,v.id?`Save changes`:`Create rule`]}),(0,X.jsx)(G,{className:`h-10`,variant:`outline`,onClick:()=>{y(null),c?.()},children:`Cancel`})]})]}),ge&&(0,X.jsx)(Bl,{onClose:()=>_e(null),children:(0,X.jsx)(pl,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:ge.target!==`storeFolder`&&!(ge.target===`condition`&&v?.actions.some(e=>e.kind===`store`)),tabs:ge.target===`condition`?[`context`,`directory`,`backends`]:ge.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:ge.target===`condition`?`Choose source folder…`:ge.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:ge.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:ye,onClose:()=>_e(null)})}),!o&&(h?(0,X.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):u.length===0?!b&&!v&&(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`rounded-xl border border-dashed p-6 text-center`,children:[(0,X.jsx)(`p`,{className:`text-base font-medium`,children:`No rules yet`}),(0,X.jsx)(`p`,{className:`mt-1 text-sm text-muted-foreground`,children:`Pick a starting point below, or right-click a folder in the tree and choose “Create rule…”.`})]}),Oe]}):(0,X.jsxs)(`div`,{className:`space-y-6`,children:[we.length>0&&(0,X.jsxs)(`section`,{className:`space-y-3`,children:[(0,X.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-sm text-muted-foreground`,children:[(0,X.jsxs)(`h3`,{className:`flex items-center gap-2 font-semibold uppercase tracking-wide`,children:[(0,X.jsx)($e,{className:`h-4 w-4 shrink-0`}),` Folder & storage rules`]}),(0,X.jsx)(`p`,{children:`Right-click a folder in the tree to add one`})]}),(0,X.jsx)(`div`,{className:`space-y-3`,children:we.map(e=>(0,X.jsx)(De,{rule:e},e.id))})]}),Ee.length>0&&(0,X.jsxs)(`section`,{className:`space-y-3`,children:[we.length>0&&(0,X.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,X.jsx)(Ze,{className:`h-4 w-4`}),` Other rules`]}),(0,X.jsx)(`div`,{className:`space-y-3`,children:Ee.map(e=>(0,X.jsx)(De,{rule:e},e.id))})]})]}))]})}function mp({workspaceId:e,document:t,onClose:n}){let[r,i]=(0,J.useState)(null),[a,o]=(0,J.useState)(``),[s,c]=(0,J.useState)(``);ac(n),(0,J.useEffect)(()=>{let n=!1;return(async()=>{if(!_f(await Et(e)))throw Error(`Only workspace administrators can create rules.`);let r=await xn(e,t.id);n||i(r)})().catch(e=>{n||o(e instanceof Error?e.message:`Could not load document`)}),()=>{n=!0}},[e,t.id]);let l=(0,J.useMemo)(()=>r?xf(r):[],[r]),u=l.find(e=>e.id===s)||l[0],d=(0,J.useMemo)(()=>u?{kind:`document`,rule:u.rule}:null,[u]);return(0,X.jsx)(Sf,{label:`Create rule`,onClose:n,children:(0,X.jsxs)(`div`,{className:`p-5`,children:[(0,X.jsxs)(`div`,{className:`mb-4 flex items-start justify-between gap-3`,children:[(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsx)(`h2`,{id:`document-rule-title`,className:`text-lg font-semibold`,children:`Create rule`}),(0,X.jsx)(`p`,{className:`truncate text-sm text-muted-foreground`,children:Gt(t).title})]}),(0,X.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`rounded-md p-2 hover:bg-accent`,children:(0,X.jsx)(E,{className:`h-4 w-4`})})]}),a?(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}):r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`label`,{className:`mb-4 block space-y-2 text-sm font-medium`,children:[(0,X.jsx)(`span`,{children:`Start with`}),(0,X.jsx)(`select`,{className:`h-10 w-full rounded-md border bg-background px-3`,value:u?.id,onChange:e=>c(e.target.value),children:l.map(e=>(0,X.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,X.jsx)(pp,{workspaceId:e,prefill:d,createOnly:!0,onCreated:n,onCancel:n})]}):(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading document…`})]})})}function hp(e,t){return{left:Math.min(e.x,t.x),top:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}}function gp(e,t){return e.left<t.left+t.width&&e.left+e.width>t.left&&e.top<t.top+t.height&&e.top+e.height>t.top}function _p(e,t,n,r){let i=new Set(r?n:[]);for(let n of t)gp(e,n.bounds)&&i.add(n.id);return i}var vp=`[data-document-id], button, a, input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="dialog"], [role="menu"], [draggable="true"], thead, [data-selection-ignore]`;function yp(e,t){let n=e.ownerDocument.defaultView,r=null,i=null,a=0,o=0,s=!1,c=!1,l=``,u=()=>{let t=e.getBoundingClientRect();return{left:t.left+e.clientLeft,top:t.top+e.clientTop,width:e.clientWidth,height:e.clientHeight}},d=t=>{let n=u();return{x:Math.max(0,Math.min(n.width,t.x-n.left))+e.scrollLeft,y:Math.max(0,Math.min(n.height,t.y-n.top))+e.scrollTop}},f=()=>{if(!r?.active||!i)return;let n=hp(r.start,d(r.client));Object.assign(i.style,{left:`${n.left}px`,top:`${n.top}px`,width:`${n.width}px`,height:`${n.height}px`});let a=u(),o=Array.from(e.querySelectorAll(`[data-document-id]`)).filter(e=>e.getClientRects().length>0).map(t=>{let n=t.getBoundingClientRect();return{id:Number(t.dataset.documentId),bounds:{left:n.left-a.left+e.scrollLeft,top:n.top-a.top+e.scrollTop,width:n.width,height:n.height}}});t.onSelectionChange(_p(n,o,r.initial,r.additive))},p=(e,t,n)=>{let r=Math.min(40,n/4);return e<t+r?-18*Math.min(1,(t+r-e)/r):e>t+n-r?18*Math.min(1,(e-t-n+r)/r):0},m=t=>{if(!r?.active)return;let i=u(),c=o?Math.min(2,(t-o)/(1e3/60)):1;o=t;let{scrollTop:l,scrollLeft:d}=e;e.scrollTop+=p(r.client.y,i.top,i.height)*c,e.scrollLeft+=p(r.client.x,i.left,i.width)*c,(s||e.scrollTop!==l||e.scrollLeft!==d)&&(f(),s=!1),a=n.requestAnimationFrame(m)},h=(s=!1)=>{if(!r)return;let u=r;r=null,n.cancelAnimationFrame(a),a=0,o=0,i?.remove(),i=null,u.active&&(e.style.userSelect=l,c=!0,s&&t.onSelectionChange(u.initial)),e.hasPointerCapture(u.pointerId)&&e.releasePointerCapture(u.pointerId)},g=n=>{if(c=!1,r||n.button!==0||!n.isPrimary||n.pointerType===`touch`)return;let i=n.target;if(!e.contains(i)||i.closest(vp))return;let a=u();if(n.clientX<a.left||n.clientX>=a.left+a.width||n.clientY<a.top||n.clientY>=a.top+a.height)return;let o={x:n.clientX,y:n.clientY};r={pointerId:n.pointerId,start:d(o),clientStart:o,client:o,initial:new Set(t.getSelection()),additive:n.ctrlKey||n.metaKey||n.shiftKey,active:!1},n.preventDefault(),e.focus({preventScroll:!0}),e.setPointerCapture(n.pointerId)},_=t=>{if(!(!r||t.pointerId!==r.pointerId)){if(!(t.buttons&1)){h();return}if(r.client={x:t.clientX,y:t.clientY},!r.active){if(Math.hypot(t.clientX-r.clientStart.x,t.clientY-r.clientStart.y)<4)return;r.active=!0,l=e.style.userSelect,e.style.userSelect=`none`,n.getSelection()?.removeAllRanges(),i=e.ownerDocument.createElement(`div`),i.setAttribute(`aria-hidden`,`true`),i.dataset.selectionRectangle=``,i.className=`pointer-events-none absolute z-20 border border-info bg-info/15`,e.append(i),a=n.requestAnimationFrame(m)}s=!0,t.preventDefault()}},v=e=>{!r||e.pointerId!==r.pointerId||(r.client={x:e.clientX,y:e.clientY},r.active?f():r.additive||t.onSelectionChange(new Set),h())},y=()=>h(!0),b=e=>{e.pointerId===r?.pointerId&&y()},x=e=>{r&&e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),y())},S=e=>{c&&(c=!1,e.preventDefault(),e.stopImmediatePropagation())},C=()=>{s=!0};return e.addEventListener(`pointerdown`,g),e.addEventListener(`pointermove`,_),e.addEventListener(`pointerup`,v),e.addEventListener(`pointercancel`,b),e.addEventListener(`lostpointercapture`,b),e.addEventListener(`click`,S,!0),e.addEventListener(`scroll`,C,!0),n.addEventListener(`keydown`,x,!0),n.addEventListener(`blur`,y),()=>{h(),e.removeEventListener(`pointerdown`,g),e.removeEventListener(`pointermove`,_),e.removeEventListener(`pointerup`,v),e.removeEventListener(`pointercancel`,b),e.removeEventListener(`lostpointercapture`,b),e.removeEventListener(`click`,S,!0),e.removeEventListener(`scroll`,C,!0),n.removeEventListener(`keydown`,x,!0),n.removeEventListener(`blur`,y)}}function bp({scope:e,selected:t,onSelectionChange:n,onContextMenu:r,children:i}){let a=(0,J.useRef)(null),o=(0,J.useRef)({selected:t,onSelectionChange:n});return(0,J.useLayoutEffect)(()=>{o.current={selected:t,onSelectionChange:n}},[t,n]),(0,J.useLayoutEffect)(()=>{if(a.current)return yp(a.current,{getSelection:()=>o.current.selected,onSelectionChange:e=>o.current.onSelectionChange(e)})},[e]),(0,X.jsx)(`div`,{ref:a,tabIndex:-1,"data-document-selection-area":``,onContextMenu:r,className:`relative isolate min-h-0 min-w-0 flex-1 overflow-auto p-2 outline-none`,children:i})}function xp(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 Sp({workspaceId:e,ids:t,onClose:n,modal:r=!1}){let{showProgress:i}=wt();ac(n,r);let[a]=(0,J.useState)(()=>{try{return xp(e)}catch{return``}}),[o,s]=(0,J.useState)(()=>{try{let e=JSON.parse(localStorage.getItem(a)||`null`);return e&&Array.isArray(e.ids)&&e.target&&e.index<e.ids.length?e:null}catch{return null}}),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(``),f=(0,J.useRef)(!1),p=(0,J.useRef)(!1);(0,J.useEffect)(()=>(f.current=!1,()=>{f.current=!0}),[]);let m=e=>{try{e.index>=e.ids.length?localStorage.removeItem(a):localStorage.setItem(a,JSON.stringify(e))}catch{}f.current||s(e)},h=async t=>{if(p.current)return;p.current=!0,l(!0),d(``);let n=t,r=()=>`${n.index} / ${n.ids.length} document(s) → ${n.target.workspaceName}`,a=i({title:`Copying to workspace…`,description:r()});m(n);try{for(;n.index<n.ids.length&&!f.current;){if(!navigator.onLine)throw Error(`Offline. Your copy is saved; resume when connected.`);await dn(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},m(n),a.update({title:`Copying to workspace…`,description:r()})}a.done({title:n.index>=n.ids.length?`Copy complete`:`Copy paused`,description:r()}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`))}catch(e){a.fail({title:`Copy incomplete`,description:`${r()}. ${e instanceof Error?e.message:`Copy failed`}`,variant:`destructive`}),f.current||d(`Document ${n.ids[n.index]}: ${e instanceof Error?e.message:`Copy failed`}. Resume to retry.`)}finally{p.current=!1,f.current||l(!1)}},g=()=>{f.current=!0,n()},_=o!=null&&o.index>=o.ids.length,v=r?`h-full min-h-0 w-full`:zl,y=(0,X.jsx)(X.Fragment,{children:o?(0,X.jsxs)(`section`,{role:`dialog`,"aria-label":`Copy to workspace`,className:`${v} flex flex-col rounded-(--panel-radius) border bg-card p-4 shadow-elevation-4`,children:[(0,X.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,X.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[o.target.workspaceName,`: `,o.paths.join(`, `)]}),(0,X.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[o.index,` of `,o.ids.length,` copied`,_?`.`:c?`…`:` — paused.`]}),u&&(0,X.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:u}),(0,X.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.`}),!_&&(0,X.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,X.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!_&&!c&&(0,X.jsx)(G,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(a)}catch{}s(null),d(``)},children:`Discard remaining`}),!_&&!c&&(0,X.jsx)(G,{onClick:()=>void h(o),children:`Resume copy`}),(0,X.jsx)(G,{variant:_?`default`:`outline`,onClick:g,children:_?`Done`:c?`Pause & close`:`Close`})]})]}):(0,X.jsx)(pl,{title:`Copy to workspace…`,confirmLabel:`Copy documents`,excludeWorkspace:e,documentCount:t.length,sizeClassName:v,onClose:g,onConfirm:(e,n)=>h({ids:t,target:n,paths:e,index:0,id:crypto.randomUUID()})})});return r?(0,X.jsx)(Sf,{label:`Copy to workspace`,onClose:g,children:y}):(0,X.jsx)(Bl,{onClose:g,children:y})}function Cp(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...Wn(e.data?.tags??[]),...Wn(t)])]}:{},...n?{geo:n}:{}}}function wp(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:Cp(e,t,n),...r===void 0?{}:{comment:r.trim()}}}function Tp({workspaceId:e,documentIds:t,onClose:n}){let[r,i]=(0,J.useState)([]),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(`keep`),[l,u]=(0,J.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,J.useState)(t),[m,h]=(0,J.useState)(!1),[g,_]=(0,J.useState)(``);return ac(n,!m),(0,uo.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-scrim p-4`,children:(0,X.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-(--panel-radius) border bg-background p-5 shadow-elevation-4`,children:[(0,X.jsxs)(`h2`,{id:`bulk-edit-title`,className:`font-semibold`,children:[`Bulk Edit · `,f.length,` documents`]}),(0,X.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,X.jsxs)(`fieldset`,{disabled:m,className:`space-y-4`,children:[(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)(`span`,{className:`text-sm font-medium`,children:`Add tags`}),(0,X.jsx)(Kl,{tags:r,onChange:i,suggestions:[]})]}),(0,X.jsx)(nu,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,X.jsxs)(`div`,{className:`space-y-2`,children:[(0,X.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,X.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,X.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,X.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,X.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,X.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,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,X.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,X.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,X.jsx)(G,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,X.jsx)(G,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await xn(e,n);await jn(e,wp(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 Ep=e=>`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`;function Dp(e,t,n,r){return typeof e.sourcePath==`string`&&!!t&&e.sourceWorkspaceId===t&&!!n&&e.sourceTreeName===n&&Ep(e.sourcePath)===Ep(r)}function Op({onClose:e,onConfirm:t,fixedWorkspaceName:n,saving:r=!1,sizeClassName:i}){let[a,o]=(0,J.useState)(n?`browse`:`workspace`),[s,c]=(0,J.useState)([]),[l,u]=(0,J.useState)(!n),[d,f]=(0,J.useState)(n??null),[p,m]=(0,J.useState)(`context`),[h,g]=(0,J.useState)(new Set),[_,v]=(0,J.useState)(n);return n!==_&&(v(n),n||u(!0)),(0,J.useEffect)(()=>{n||Kt().then(c).catch(()=>c([])).finally(()=>u(!1))},[n]),(0,X.jsxs)(`div`,{className:H(`flex flex-col overflow-hidden rounded-(--panel-radius) 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,X.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,X.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,X.jsx)(Xe,{className:`h-4 w-4`}),a===`workspace`?`Add existing documents…`:`Pick documents…`]}),(0,X.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,X.jsx)(E,{className:`h-4 w-4`})})]}),(0,X.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,X.jsxs)(`div`,{className:`grid h-full w-[200%] grid-cols-2 transition-transform duration-normal`,style:{transform:a===`workspace`?`translateX(0)`:`translateX(-50%)`},children:[(0,X.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,X.jsx)(dl,{workspaces:s,loading:l,onPick:e=>{f(e),g(new Set),o(`browse`)}})}),(0,X.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:[!n&&(0,X.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,X.jsx)(vt,{className:`h-4 w-4 rotate-180`})}),[`context`,`directory`].map(e=>(0,X.jsxs)(`button`,{type:`button`,onClick:()=>{m(e),g(new Set)},className:H(`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:[rl[e],il[e]]},e))]}),d&&(0,X.jsx)(fl,{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,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,X.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[h.size,` document`,h.size===1?``:`s`,` selected`]}),(0,X.jsx)(G,{size:`sm`,onClick:async()=>{!d||h.size===0||r||await t(Array.from(h),{workspaceName:d,treeName:p===`directory`?`directory`:Dn,treeType:p})},disabled:h.size===0||r,children:r?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(go,{className:`mr-1.5 h-3.5 w-3.5`}),`Adding…`]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(Xe,{className:`mr-1 h-3.5 w-3.5`}),`Add`]})})]})]})}function kp(e){let{id:t,...n}=e;return n}var Ap=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`div`,{className:`relative w-full overflow-auto`,children:(0,X.jsx)(`table`,{ref:n,className:H(`w-full caption-bottom text-sm`,e),...t})}));Ap.displayName=`Table`;var jp=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`thead`,{ref:n,className:H(`[&_tr]:border-b`,e),...t}));jp.displayName=`TableHeader`;var Mp=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`tbody`,{ref:n,className:H(`[&_tr:last-child]:border-0`,e),...t}));Mp.displayName=`TableBody`;var Np=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`tfoot`,{ref:n,className:H(`border-t bg-muted/50 font-medium [&>tr]:last:border-b-0`,e),...t}));Np.displayName=`TableFooter`;var Pp=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`tr`,{ref:n,className:H(`border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted`,e),...t}));Pp.displayName=`TableRow`;var Fp=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`th`,{ref:n,className:H(`h-12 px-2 md:px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0`,e),...t}));Fp.displayName=`TableHead`;var Ip=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`td`,{ref:n,className:H(`p-2 md:p-4 align-middle [&:has([role=checkbox])]:pr-0`,e),...t}));Ip.displayName=`TableCell`;var Lp=J.forwardRef(({className:e,...t},n)=>(0,X.jsx)(`caption`,{ref:n,className:H(`mt-4 text-sm text-muted-foreground`,e),...t}));Lp.displayName=`TableCaption`;var Rp=({label:e,sortKey:t,sort:n,onSort:r,className:i})=>{let a=n.key===t;return(0,X.jsx)(Fp,{"aria-sort":a?n.dir===`asc`?`ascending`:`descending`:`none`,className:H(`cursor-pointer select-none hover:text-foreground transition-colors`,i),onClick:()=>r(t),children:(0,X.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,a?n.dir===`asc`?(0,X.jsx)(Fe,{className:`h-3.5 w-3.5`}):(0,X.jsx)(De,{className:`h-3.5 w-3.5`}):(0,X.jsx)(x,{className:`h-3.5 w-3.5 opacity-40`})]})})};Rp.displayName=`SortableTableHead`;function zp(e,t,n={key:null,dir:`asc`}){let[r,i]=J.useState(n);return{sorted:J.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:J.useCallback(e=>{i(t=>t.key===e?{key:e,dir:t.dir===`asc`?`desc`:`asc`}:{key:e,dir:`asc`})},[])}}var Bp=`canvas:documentOpenMode`;function Vp(){try{return localStorage.getItem(Bp)===`modal`?`modal`:`side`}catch{return`side`}}var Hp=Vp(),Up=new Set;function Wp(){return Hp}function Gp(e){try{localStorage.setItem(Bp,e)}catch{}Hp=e;for(let e of Up)e()}function Kp(e){Up.add(e);let t=t=>{(t.key===Bp||t.key===null)&&(Hp=Vp(),e())};return window.addEventListener(`storage`,t),()=>{Up.delete(e),window.removeEventListener(`storage`,t)}}function qp(){return(0,J.useSyncExternalStore)(Kp,Wp,()=>`side`)}function Jp(e){let t=qp(),n=(0,J.useContext)(Uu),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=(t===`side`||n?.alwaysOn===!0)&&!!n&&!!i&&!s&&!c;return(0,J.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,X.jsx)(Yp,{...e})}function Yp({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,J.useState)(!1),c=er(),{document:l,refresh:u}=yd(r,e);if(ac(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,uo.createPortal)((0,X.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:H(`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,X.jsxs)(`div`,{className:H(`flex w-full flex-col border bg-background max-md:h-full max-md:max-w-none`,o?`h-full max-w-none rounded-none md:rounded-(--panel-radius) md:m-2 md:h-[calc(var(--viewport-h)-1rem)]`:`h-viewport-card max-w-3xl rounded-(--panel-radius)`),onClick:e=>e.stopPropagation(),children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:Gt(l).title}),(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=jt(l);return e?(0,X.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,X.jsx)(Ae,{className:`h-4 w-4`})}):null})(),(0,X.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,X.jsx)(ve,{className:`h-4 w-4`}):(0,X.jsx)(qe,{className:`h-4 w-4`})}),(0,X.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,X.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,X.jsx)(qo.Provider,{value:()=>s(e=>!e),children:(0,X.jsx)(vd,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Xp={sortBy:`content`,order:`desc`};function Zp(e){return e?.sortBy===`crud:deleted`?{...Xp}:{sortBy:e?.sortBy??Xp.sortBy,order:e?.order??Xp.order}}var Qp={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:{...Xp}};function $p(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function em(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 tm(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function nm(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=tm(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 rm(e,t,n=[]){return{features:e.features,filters:[...nm(e.timeline),...$p(e.geo),...em(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 im=Xp,am={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function om(e){return am[e]??e}function sm(e){let[t,n]=(0,J.useState)([]);return(0,J.useEffect)(()=>{let t=!1;return gn(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,J.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:om(e)})),[t])}function cm({workspaceId:e,value:t,onChange:n}){let r=sm(e);return(0,X.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,X.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,X.jsx)(`option`,{value:t.sortBy,children:om(t.sortBy)}),r.map(e=>(0,X.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,X.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,X.jsx)(B,{className:`h-3.5 w-3.5`}):(0,X.jsx)(ke,{className:`h-3.5 w-3.5`})})]})}function lm(e,t){let n=t?.replace(/^t:/,``)||`crud:created`,r=(n===`crud:created`?[e.createdAt]:n===`crud:updated`?[e.updatedAt]:(e.timelines??[]).filter(e=>(e.timeline||e.name)===n).map(e=>e.start)).map(e=>Date.parse(e??``)).filter(Number.isFinite);if(r.length)return Math.min(...r);let i=n===`content`?Date.parse(e.createdAt??``):NaN;return Number.isFinite(i)?i:null}var um={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},dm=e=>e*1e6;function fm(){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 pm(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function mm(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=pm(e);return r.setDate(r.getDate()-n),r}var hm=864e5;function gm(e){let t=fm(),n=pm(e),r=mm(e,t);return{today:n.getTime(),yesterday:n.getTime()-hm,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*hm,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function _m(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:dm(um.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:dm(um.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:dm(um.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:dm(um.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:dm(um.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:dm(um.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:dm(um.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:dm(um.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:dm(um.year)+i}}function vm(e,t,n=`desc`,r=new Date){let i=gm(r),a=new Map;for(let n of e){let e=_m(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 ym(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 bm(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function xm(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 Sm=(e,t)=>`${bt.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Cm(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await W.get(`${Sm(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 wm(e,t,n){return Em(e,t,n,`restore`)}function Tm(e,t,n){return Em(e,t,n,`discard`)}async function Em(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await W.post(`${Sm(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{un(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 Dm(e,t){let n=ym(`backends`,t);if(!n?.backend)return;let{items:r}=await Cm(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 wm(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 Om(e,t){if(!t.length)return!1;let n=[...new Set(t.map(e=>e.key))],r=n.slice(0,5).join(`
19
+ `)+(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 km(e,t){let n=ym(`backends`,t);if(!n?.backend)return;let{items:r}=await Cm(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Om(n.backend,i))return;let a=await Tm(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 Am(){let{showProgress:e}=wt();return(0,J.useCallback)(async(t,n,r,i)=>{let a=e({title:t,description:n});try{let e=await i();if(e===!1)throw Error(`The operation could not be completed.`);return a.done({title:r,description:n}),e}catch(e){throw a.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}},[e])}var jm=new Map;function Mm(e,t,n,r,i){let a=JSON.stringify([t,n,r]),o=jm.get(a);if(o)return o;let s=(async()=>{let a=e({title:`Resyncing…`,description:r});try{for(await fn(t,n,r);;){let e=await Qt(t,n,r);if(i?.(e),!e.resyncing&&e.status!==`syncing`){if(e.lastError)throw Error(e.lastError);a.done({title:e.resyncCancelledAt?`Resync stopped`:`Resync complete`,description:`${r}${e.progress?` · ${e.progress.scanned} files scanned`:``}`}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:t,treeName:`backends`}}));return}let o=e.progress;a.update({title:`Resyncing…`,description:`${r}${o?` · ${o.scanned}${o.total==null?``:` / ${o.total}`} files scanned`:``}`}),await new Promise(e=>setTimeout(e,2e3))}}catch(e){throw a.fail({title:`Resync needs attention`,description:`${r}: ${e instanceof Error?e.message:String(e)}`,variant:`destructive`}),e}})();return jm.set(a,s),s.finally(()=>{jm.get(a)===s&&jm.delete(a)}).catch(()=>{}),s}var Nm=[`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`],Pm=new Map;function Fm(e,t,n){un(e,t),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:t,cacheInvalidated:!0}})),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`,{detail:{workspaceName:e,treeName:t,path:n}}))}function Im(e,t){let n=Pm.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=Nm.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)un(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return ho.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)un(e,t);a.forEach(([e,t])=>ho.off(e,t))}},Pm.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),Pm.delete(e))}}function Lm({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=Am(),{showProgress:a}=wt(),o=n||`context`,c=o===`directory`,l=(0,J.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),u=(0,J.useCallback)(async(n,r=!0)=>{let i;if(e)i=await ar(e,n,r);else if(t)i=await pn(t,n,r,o);else return!1;let a=Pc(n);if(i&&a)try{e?await $n(e,n,a):t&&await At(t,n,a,o)}catch{}return l(),i},[e,t,o,l]),d=(0,J.useCallback)(async(n,r=!1,a=!1,s=!1)=>i(s?`Destroying…`:a?`Purging…`:`Removing…`,n,s?`Destroyed`:a?`Purged`:`Removed`,async()=>{try{return e?await Qn(e,n,r):t?await Dt(t,n,r,o,a,s):!1}finally{l()}}),[e,t,o,l,i]),f=(0,J.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await Zn(e,n,t.join(`/`),!1)}else if(t)i=await At(t,n,{name:r},o);else return!1;return l(),i},[e,t,o,l]),p=(0,J.useCallback)(async(n,r,a=!1,s=o,c=o,u={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await Zn(e,n,r,a,u);else if(t)i=await Pn(t,n,r,a,s,c,u);else return!1;return l(),i}),[e,t,o,l,i]),m=(0,J.useCallback)(async n=>{let r;if(e)r=await tr(e,n);else if(t)r=await It(t,n,o);else return null;return l(),r},[e,t,o,l]),h=(0,J.useCallback)(async n=>{let r;if(e)r=await Xn(e,n);else if(t)r=await Sn(t,n,o);else return null;return l(),r},[e,t,o,l]),g=(0,J.useCallback)(async(n,r,a=!1,s=o,c=o)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await rr(e,n,r,a);else if(t)i=await ln(t,n,r,a,s,c);else return!1;return l(),i}),[e,t,o,l,i]),_=(0,J.useCallback)(async(n,r)=>e?await $n(e,n,r):t?await At(t,n,r,o):!1,[e,t,o]),v=(0,J.useCallback)(async(n,r)=>{let i;if(e)i=await or(e,n,r);else if(t)i=await Ht(t,n,r,o);else return null;return l(),i},[e,t,o,l]),y=(0,J.useCallback)(async(n,r)=>{let i;if(e)i=await nr(e,n,r);else if(t)i=await bn(t,n,r,o);else return null;return l(),i},[e,t,o,l]),b=(0,J.useCallback)(async e=>{if(!t)return!1;let n=await Mt(t,e,t,o);return l(300),n},[t,o,l]),x=(0,J.useCallback)(async(e,n)=>{if(!t)return!1;try{await rn(t,e,n??t,o)}catch(e){if(!(e instanceof Error)||!/still locked by/i.test(e.message))throw e}return l(300),!0},[t,o,l]),S=(0,J.useCallback)(async e=>{if(!t)return!1;let n=await Ot(t,e,o);return l(),n},[t,o,l]),C=(0,J.useCallback)(async e=>{if(!t)return!1;let n=await an(t).catch(()=>[]),r=En(e,n);return r?(await Mm(a,t,r.driver,r.address),l(300),!0):!1},[t,l,a]),w=(0,J.useCallback)(async(e,n)=>{if(!t)return!1;let r=await an(t).catch(()=>[]),i=on(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await nn(t,i.driver,i.address,[a]),l(200),!0},[t,l]),T=(0,J.useCallback)(async(e,n)=>{if(!t)return!1;let r=await an(t).catch(()=>[]),i=on(e,r);return!i||!i.key?!1:(await q(t,i.driver,i.address,i.key,n),l(200),!0)},[t,l]),E=(0,J.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await an(t),r=On(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await zt(t,r.driver,r.address,r.key),!0}finally{l(200)}}):!1,[t,l,i]),D=(0,J.useCallback)(async(e,n)=>{if(!t)return;let{showSubtreeTransfer:r}=await s(async()=>{let{showSubtreeTransfer:e}=await import(`./subtree-transfer-dialog-CSjPDp4d.js`);return{showSubtreeTransfer:e}},__vite__mapDeps([30,3,4,10,11,13,12,14]));r({mode:e,path:n,workspaceId:t,treeName:o,onImported:()=>{Fm(t,o),l()}})},[t,o,l]),O=(0,J.useCallback)(async(e,n)=>{if(!t)return;let r=await s(()=>Promise.resolve().then(()=>zm),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await cn(t,n,e,o,Nn(o))).length!==e.length)throw Error(`Some documents could not be imported`);return Fm(t,o),l(),!0});else{let e=[];for(let r=0;;){let i=await mn(t,n,[],{treeName:o,treeType:Nn(o),limit:500,offset:r,order:`asc`}),a=i.payload||[];if(e.push(...a),r+=a.length,!a.length||r>=(i.totalCount??i.count??1/0))break}r.showDocumentExport(e)}},[t,o,l]);return{onImportDocuments:t&&o!==`backends`?e=>O(`import`,e):void 0,onExportDocuments:t?e=>O(`export`,e):void 0,onInsertPath:u,onRemovePath:d,onRenamePath:f,onMovePath:p,onCopyPath:g,onExportSubtree:t?e=>D(`export`,e):void 0,onImportSubtree:t&&o!==`backends`?e=>D(`import`,e):void 0,onUpdateNode:_,onMergeLayer:v,onSubtractLayer:y,onMergeDown:c?void 0:m,onSubtractDown:c?void 0:h,onLockLayer:t?b:void 0,onUnlockLayer:t?x:void 0,onDestroyLayer:t&&!c?S:void 0,onResyncBackend:t?C:void 0,onCreateBackendFolder:t?w:void 0,onRenameBackendFolder:t?T:void 0,onDeleteBackendFolder:t?E:void 0}}function Rm({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let d=Fi(),f=Lm({workspaceId:n,treeName:r}),p=r===`backends`,m=p?on(i):null,[g,_]=(0,J.useState)([]);(0,J.useEffect)(()=>{if(!p)return;let e=!1;return an(n).then(t=>{e||_(t)}).catch(()=>{}),()=>{e=!0}},[n,p]);let v=p?On(i,g):null,y=i.split(`/`).filter(Boolean).pop()||i,[b,x]=(0,J.useState)(void 0);(0,J.useEffect)(()=>{let e=!1;return Ut(n).then(t=>{e||x(t.find(e=>e.tree===r&&e.path===i)??null)}).catch(()=>{e||x(null)}),()=>{e=!0}},[n,r,i]);let S=async e=>{a();try{await e()}catch(e){alert(e instanceof Error?e.message:String(e))}},C=(e,t,n,r=!1)=>(0,X.jsxs)(`button`,{type:`button`,className:H(`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:()=>S(n),children:[e,t]}),w=(0,X.jsx)(`div`,{className:`my-1 h-px bg-border`}),T=e=>{let t=p?(()=>{let t=Ud(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:Gd(i)};d(`/workspaces/${n}/settings/hooks?${Wd(t).toString()}`)},E=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},D=ym(r,i);return D?(0,X.jsxs)(oc,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,X.jsx)(pe,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),D.backend&&C((0,X.jsx)(ht,{className:`h-3 w-3`}),`Restore original paths`,()=>Dm(n,i)),D.backend&&C((0,X.jsx)(pe,{className:`h-3 w-3`}),`Empty Trash`,()=>km(n,i),!0)]}):(0,X.jsxs)(oc,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,X.jsx)(me,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&C((0,X.jsx)(dt,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),w,p?m&&(0,X.jsxs)(X.Fragment,{children:[C((0,X.jsx)(ze,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=E(`New folder name:`);e&&await f.onCreateBackendFolder?.(i,e)}),m.key&&C((0,X.jsx)(L,{className:`w-3 h-3`}),`Rename folder`,async()=>{let e=E(`New folder name:`,y);e&&await f.onRenameBackendFolder?.(i,e)}),C((0,X.jsx)(F,{className:`w-3 h-3`}),`Create storage rule…`,()=>T(`store`))]}):(0,X.jsxs)(X.Fragment,{children:[C((0,X.jsx)(ze,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=E(`New folder name:`);e&&await f.onInsertPath(`${i===`/`?``:i}/${e}`)}),C((0,X.jsx)(L,{className:`w-3 h-3`}),`Rename`,async()=>{let e=E(`New name:`,y);e&&await f.onRenamePath(i,e)}),C((0,X.jsx)(F,{className:`w-3 h-3`}),`Create rule…`,()=>T(`store`)),C((0,X.jsx)(Me,{className:`w-3 h-3`}),`Create download rule…`,()=>T(`download`))]}),b!==void 0&&C(b?(0,X.jsx)(h,{className:`w-3 h-3`}):(0,X.jsx)(M,{className:`w-3 h-3`}),b?`Unpin`:`Pin`,async()=>{b?await Mn(n,b.id):await Pt(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),w,f.onImportDocuments&&C((0,X.jsx)(ze,{className:`w-3 h-3`}),`Import documents…`,()=>f.onImportDocuments(i)),f.onExportDocuments&&C((0,X.jsx)(Me,{className:`w-3 h-3`}),`Export documents…`,()=>f.onExportDocuments(i)),C((0,X.jsx)(u,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!p&&l&&c&&c.length>0&&C((0,X.jsx)(ee,{className:`w-3 h-3`}),`Paste ${c.length} document(s)`,()=>l(i,c)),p?v&&(0,X.jsxs)(X.Fragment,{children:[w,C((0,X.jsx)(pe,{className:`w-3 h-3`}),`Delete from backend`,async()=>{confirm(`Delete folder "${y}" and its contents from the backend?`)&&await f.onDeleteBackendFolder?.(i)},!0)]}):(0,X.jsxs)(X.Fragment,{children:[w,C((0,X.jsx)(pe,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await f.onRemovePath(i,!0)},!0)]})]})}var zm=t({DocumentList:()=>uh,default:()=>uh,showDocumentExport:()=>fh,showDocumentImport:()=>dh});function Bm({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,J.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(kp),l=JSON.stringify(c,null,2),d=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,X.jsx)(Sf,{label:`Export Documents`,onClose:o,children:(0,X.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,X.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,X.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,X.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,X.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,X.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,X.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,X.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,X.jsxs)(G,{onClick:d,size:`sm`,className:`flex items-center gap-2`,children:[(0,X.jsx)(u,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,X.jsx)(`textarea`,{className:`w-full min-h-24 flex-1 p-4 bg-muted border rounded-lg text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-primary`,value:l,readOnly:!0,autoFocus:!0,onKeyDown:e=>{if(e.ctrlKey||e.metaKey){if(e.key===`a`){e.preventDefault();let t=window.getSelection(),n=document.createRange();n.selectNodeContents(e.currentTarget),t?.removeAllRanges(),t?.addRange(n)}else e.key===`c`&&d()}},onFocus:e=>e.target.select()})]})}),(0,X.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-end gap-2`,children:[(0,X.jsx)(G,{variant:`outline`,onClick:()=>{let e=URL.createObjectURL(new Blob([l],{type:`application/json`})),t=window.document.createElement(`a`);t.href=e,t.download=`canvas-documents.json`,t.click(),setTimeout(()=>URL.revokeObjectURL(e),1e3)},children:`Download JSON`}),(0,X.jsx)(G,{onClick:o,children:`Close`})]})]})})}function Vm({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,J.useState)(``),[a,o]=(0,J.useState)(!1),[s,c]=(0,J.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||typeof e!=`object`||!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(e){c(e instanceof Error?e.message:`Import failed`)}finally{o(!1)}},u=()=>{i(``),c(null),t()};return(0,uo.createPortal)((0,X.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,X.jsx)(`div`,{className:`bg-background border rounded-(--panel-radius) max-w-3xl w-full max-h-viewport-card overflow-y-auto max-md:h-full max-md:max-h-none max-md:max-w-none`,children:(0,X.jsxs)(`div`,{className:`p-6`,children:[(0,X.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,X.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data or choose a document export file`})]}),(0,X.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,X.jsxs)(`div`,{className:`space-y-4`,children:[(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,X.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,X.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,X.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,X.jsxs)(`p`,{children:[(0,X.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,X.jsxs)(`p`,{children:[(0,X.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,X.jsxs)(`label`,{className:`mt-4 block text-sm`,children:[`Import JSON file`,(0,X.jsx)(`input`,{type:`file`,accept:`.json,application/json`,disabled:a,className:`mt-2 block w-full text-sm`,onChange:e=>{let t=e.target.files?.[0];t&&t.text().then(e=>{i(e),c(null)}).catch(e=>c(String(e)))}})]}),(0,X.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,X.jsx)(G,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,X.jsx)(G,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function Hm({document:e}){let{replicating:t,label:n}=K(e);return t?(0,X.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,X.jsx)(ut,{className:`h-3 w-3 animate-spin`}),n]}):null}function Um(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:hc(e.currentTarget,`inside`)}function Wm({documentId:e,onOpenActions:t,className:n}){return t?(0,X.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,X.jsx)(Pe,{className:`h-4 w-4`})}):null}function Gm(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function Km({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Gu(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=hf(),[u,d]=(0,J.useState)(!1),{replicating:f}=K(e),p=e.schema===`data/schema/tab`,m=p?e.data.url:null,h=Gt(e),g=Jm(e),_=g||Xm(e),{blobUrl:v}=$o(n??``,e.id,128,{enabled:_,blobFallback:g,version:e.checksumArray?.[0]??null}),y=t=>{o?.(t,e.id)},b=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),x=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),S=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||(p&&m?window.open(m,`_blank`,`noopener,noreferrer`):d(!0))},C=e=>{e.shiftKey&&e.preventDefault()},w=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(Pp,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>Gm(n,()=>p&&m?window.open(m,`_blank`,`noopener,noreferrer`):d(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:text-accent-foreground cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring transition-opacity ${f?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:S,onMouseDown:C,...l,onContextMenu:w,draggable:!0,onDragStart:y,children:[(0,X.jsx)(Ip,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,X.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,X.jsx)(Ip,{className:`w-12`,children:v?(0,X.jsx)(`img`,{src:v,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,X.jsx)(el,{document:e,chip:!0})}),(0,X.jsx)(Ip,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,X.jsx)(`span`,{className:`truncate`,title:h.title,children:h.title}),h.isExternal&&(0,X.jsx)(Ae,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,X.jsx)(Hm,{document:e})]}),h.subtitle&&(0,X.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:h.subtitle,children:h.subtitle})]})}),(0,X.jsx)(Ip,{className:`hidden md:table-cell`,children:(0,X.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:h.schemaLabel})}),(0,X.jsx)(Ip,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,X.jsx)(Ip,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:x&&(0,X.jsx)(`span`,{className:`font-mono`,title:`${x.algo} checksum`,children:x.hash})}),(0,X.jsx)(Ip,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:b(e.createdAt)}),(0,X.jsx)(Ip,{className:`w-12 text-right`,children:(0,X.jsx)(Wm,{documentId:e.id,onOpenActions:a})})]}),(0,X.jsx)(Jp,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function qm({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=Gu(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=hf(),[u,d]=(0,J.useState)(!1),f=e.schema===`data/schema/tab`,{replicating:p}=K(e),m=f?e.data.url:null,h=Gt(e),g=Jm(e),_=g||Xm(e),{blobUrl:v,loading:y}=$o(n??``,e.id,128,{enabled:_,blobFallback:g,version:e.checksumArray?.[0]??null}),b=t=>{o?.(t,e.id)},x=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),S=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),C=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||(f&&m?window.open(m,`_blank`,`noopener,noreferrer`):d(!0))},w=e=>{e.shiftKey&&e.preventDefault()},T=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>Gm(n,()=>f&&m?window.open(m,`_blank`,`noopener,noreferrer`):d(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:border-primary border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${p?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${f&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:C,onMouseDown:w,...l,onContextMenu:T,draggable:!0,onDragStart:b,children:(0,X.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[_&&(0,X.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:v?(0,X.jsx)(`img`,{src:v,alt:h.title,loading:`lazy`,className:`h-full w-full object-cover`}):y?(0,X.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,X.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,X.jsx)(el,{document:e})})}),(0,X.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,X.jsx)(el,{document:e,chip:!0}),(0,X.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:h.title,children:h.title}),h.isExternal&&(0,X.jsx)(Ae,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,X.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:h.schemaLabel}),(0,X.jsx)(Hm,{document:e})]}),h.subtitle&&(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:h.subtitle,children:h.subtitle}),h.preview&&(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:h.preview}),(0,X.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,X.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,X.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,X.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),S&&(0,X.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,X.jsx)(D,{className:`h-3 w-3`}),(0,X.jsx)(`span`,{className:`font-mono`,title:`${S.algo} checksum`,children:S.hash})]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,X.jsx)(z,{className:`h-3 w-3`}),(0,X.jsx)(`span`,{title:`Created: ${x(e.createdAt)}`,children:x(e.createdAt)})]})]})]}),(0,X.jsx)(Wm,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,X.jsx)(Jp,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function Jm(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function Ym(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function Xm(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Zm({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=zn(e,t),[a,o]=(0,J.useState)(!1);return i||a?(0,X.jsx)(X.Fragment,{children:n}):r?(0,X.jsxs)(`div`,{className:`relative`,children:[(0,X.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(0,X.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,X.jsx)(j,{className:`h-3.5 w-3.5`})})]}):(0,X.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function Qm({document:e,workspaceId:t,markdown:n}){let r=(0,J.useRef)(null),[i,a]=(0,J.useState)(()=>typeof IntersectionObserver>`u`);(0,J.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}=Vn(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,X.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,X.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,X.jsx)(cs,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,X.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,X.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,X.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,X.jsx)(el,{document:e,size:10,chip:!0}),i&&s&&(0,X.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function $m({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let c=Gu(),l=c.alwaysOn&&c.entry?.workspaceId===n&&c.entry?.document.id===e.id,u=hf(),[d,f]=(0,J.useState)(!1),p=e.schema===`data/schema/tab`,m=p?e.data.url:null,h=Jm(e),g=Ym(e),_=h||Xm(e),v=Gt(e),y=Vt(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||Ft(e)),b=e.schema===`data/schema/file`&&(y===`markdown`||y===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,x=!_&&e.schema!==`data/schema/file`&&!!(v.preview||v.subtitle),{replicating:S}=K(e),{blobUrl:C,loading:w}=$o(n??``,e.id,768,{enabled:_,blobFallback:h,version:e.checksumArray?.[0]??null}),T=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||(p&&m?window.open(m,`_blank`,`noopener,noreferrer`):f(!0))},E=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,"data-reading":l||void 0,"aria-selected":!!t,onKeyDown:n=>Gm(n,()=>p&&m?window.open(m,`_blank`,`noopener,noreferrer`):f(!0),()=>r?.(e.id,!t,!0)),className:`data-[reading=true]:bg-accent data-[reading=true]:border-primary group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-(--card-radius) border transition cursor-pointer outline-none hover:shadow-elevation-2 focus-visible:ring-2 focus-visible:ring-ring ${S?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:T,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...u,onContextMenu:E,draggable:!0,onDragStart:t=>s?.(t,e.id),title:v.title,children:[(0,X.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,X.jsxs)(`div`,{className:`relative w-full bg-muted/40 ${_&&C||x||b&&n||g&&n?``:`aspect-square`}`,children:[_&&w&&(0,X.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),_&&C?(0,X.jsx)(`img`,{src:C,alt:v.title,loading:`lazy`,className:`block h-auto w-full`}):g&&n?(0,X.jsx)(Zm,{workspaceId:n,documentId:e.id,fallback:(0,X.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,X.jsx)(el,{document:e,size:10,chip:!0})})}):b&&n?(0,X.jsx)(Qm,{document:e,workspaceId:n,markdown:y===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):x?(0,X.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,X.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,X.jsx)(el,{document:e}),(0,X.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:v.schemaLabel})]}),(0,X.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:v.title}),v.subtitle&&(0,X.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:v.subtitle}),(0,X.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:v.preview})]}):(0,X.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,X.jsx)(el,{document:e,size:10,chip:!0})}),(0,X.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,X.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,X.jsx)(le,{className:`h-3.5 w-3.5`})}),o&&(0,X.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,X.jsx)(Pe,{className:`h-3.5 w-3.5`})})]})]}),!x&&(0,X.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,X.jsx)(`span`,{className:`truncate text-xs font-medium`,title:v.title,children:v.title}),v.isExternal&&(0,X.jsx)(Ae,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,X.jsx)(Jp,{document:e,isOpen:d,onClose:()=>f(!1),workspaceId:n})]})}function eh(e,t,n,r,i){let[a,o]=(0,J.useState)(!1),s=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:a,onDragOver:e=>{!t||!s(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,a||o(!0))},onDragLeave:()=>o(!1),onDrop:async a=>{if(o(!1),!t||!s(a))return;a.preventDefault(),a.stopPropagation();let c=null;try{c=JSON.parse(a.dataTransfer.getData(`application/json`))}catch{c=null}if(!(c?.type!==`document`||!Array.isArray(c.documentIds)||c.documentIds.length===0)&&!Dp(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function th(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function nh({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,X.jsx)(gt,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,X.jsx)(de,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var rh=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function ih({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=eh(e,r,i,a,o);return(0,X.jsxs)(`button`,{type:`button`,title:rh(e),onClick:()=>t?.(e.path),onContextMenu:t=>th(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 max-w-full items-center gap-2 rounded-md border px-2.5 py-1.5 text-sm transition-colors hover:bg-accent ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,X.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,X.jsx)(nh,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,X.jsx)(gt,{className:`hidden h-4 w-4 group-hover:block`}):(0,X.jsx)(me,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,X.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,X.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function ah({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=eh(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,X.jsxs)(`button`,{type:`button`,title:rh(e),onClick:()=>t?.(e.path),onContextMenu:t=>th(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,className:`folder-surface group flex min-w-0 flex-col items-center gap-1.5 rounded-(--card-radius) border px-2 py-3 text-sm transition hover:bg-accent hover:shadow-elevation-2 ${s.over?`ring-2 ring-info border-info bg-accent`:``} ${e.isParent?`text-muted-foreground`:``}`,children:[(0,X.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,X.jsx)(gt,{className:`h-10 w-10`,strokeWidth:1.5}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(de,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,X.jsx)(me,{className:`hidden h-14 w-14 group-hover:block ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c})]})}),(0,X.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,X.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function oh({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,X.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,X.jsx)(ah,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function sh({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,X.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,X.jsx)(ih,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function ch({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=eh(e,r,i,a,o);return(0,X.jsxs)(Pp,{"data-selection-ignore":``,className:`cursor-pointer ${s.over?`bg-accent ring-1 ring-inset ring-info`:``} ${e.isParent?`text-muted-foreground`:``}`,onClick:()=>t?.(e.path),onContextMenu:t=>th(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:rh(e),children:[(0,X.jsx)(Ip,{className:`w-10`}),(0,X.jsx)(Ip,{className:`w-12`,children:(0,X.jsx)(nh,{folder:e})}),(0,X.jsx)(Ip,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,X.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,X.jsx)(Ip,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,X.jsx)(Ip,{className:`hidden lg:table-cell`}),(0,X.jsx)(Ip,{className:`hidden lg:table-cell`}),(0,X.jsx)(Ip,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,X.jsx)(Ip,{className:`w-12 md:w-auto`})]})}function lh({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,X.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,X.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,X.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,X.jsx)(vt,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,X.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,X.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,X.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function uh({readingPane:e=!1,externalSearchQuery:t,toolbarActions:n,documents:r,isLoading:i,contextPath:a,treeName:o,workspaceId:s,totalCount:d,onRemoveDocument:f,onDeleteDocument:p,onDestroyDocument:m,onRemoveDocuments:h,onDeleteDocuments:g,onDestroyDocuments:y,onCopyDocuments:b,onCutDocuments:x,onPasteDocuments:S,onImportDocuments:C,onSelectionChange:w,pastedDocumentIds:T,viewMode:D=`card`,allowViewToggle:A=!1,activeContextUrl:j,currentContextUrl:M,currentPage:N=1,pageSize:P=50,onPageChange:L,onPageSizeChange:te,onPurgeDocuments:re,disablePurgeDocuments:ie=!1,backendSearchQueries:ae=[],onBackendSearch:oe,onRemoveBackendQuery:R,serverSort:ce,onServerSortChange:de,scope:z=`path`,onScopeChange:fe,canSaveChanges:me=!1,isSavingChanges:he=!1,onSaveChanges:ge,linkTree:_e,folders:ve,onOpenFolder:ye}){let[be,xe]=(0,J.useState)(()=>{if(!A)return D;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return D}),B=A?be:D,Se=(0,J.useCallback)(e=>{xe(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[Te,Ee]=(0,J.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),De=(0,J.useCallback)(()=>{Ee(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[Oe,ke]=(0,J.useState)(new Set),Pe=(0,J.useCallback)(e=>{ke(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[V,Fe]=(0,J.useState)(new Set),[Ie,Le]=(0,J.useState)(null),[Re,Be]=(0,J.useState)(null),He=er(),Ue=!!(He&&s),Ke=(0,J.useCallback)((e,t=!1)=>{if(!He||!s)return;let n=e.map(e=>r.find(t=>t.id===e)).filter(e=>!!e);n.length!==0&&He.openAddRelated({workspaceName:s,documents:n},t)},[He,s,r]),[qe,Je]=(0,J.useState)(!1),[Ye,Qe]=(0,J.useState)(null),[$e,et]=(0,J.useState)(!1),[tt,nt]=(0,J.useState)(null),[at,ot]=(0,J.useState)(!1),st=(0,J.useRef)(!1),ct=(0,J.useRef)(!1),lt=o===`backends`&&z===`path`?Ud(a):null;(0,J.useEffect)(()=>()=>{st.current=!0},[]);let[ut,pt]=(0,J.useState)(!1),[ht,gt]=(0,J.useState)(null),[_t,yt]=(0,J.useState)(!1),[H,bt]=(0,J.useState)(null),U=Yn()==null&&!!s,[W,xt]=(0,J.useState)(null),[St,Ct]=(0,J.useState)(null),Et=!!(_e&&S),Dt=!!s,{showSuccessToast:Ot,showErrorToast:kt}=Tt(),{showProgress:At}=wt(),jt=Gu(),Mt=s?e=>jt.open(e,s):void 0,Nt=z===`workspace`,Pt=Nt?void 0:f,It=Nt?void 0:h,[Lt,Rt]=(0,J.useState)(!1),[zt,Bt]=(0,J.useState)(!1),[Vt,Ht]=(0,J.useState)(``),K=t??Vt,Ut=t!==void 0,[Wt,Kt]=(0,J.useState)(!1),qt=ae.length>0,Jt=(0,J.useRef)(null),Yt=(0,J.useCallback)(()=>{Ht(``),Jt.current&&(Jt.current.value=``)},[]);(0,J.useEffect)(()=>{if(!A||window.matchMedia(`(max-width: 767px)`).matches)return;let e=Jt.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[A]);let Xt=JSON.stringify([s,o,a]),[Zt,Qt]=(0,J.useState)(Xt);Xt!==Zt&&(Qt(Xt),Fe(new Set),Qe(null),Be(null),Le(null)),(0,J.useEffect)(()=>{w?.(Array.from(V))},[V,w]);let $t=(0,J.useCallback)(()=>{if(!oe)return;let e=K.trim();e&&(oe(e),Yt())},[oe,K,Yt]),en=(0,J.useCallback)(()=>{Yt(),R&&ae.length>0&&R(-1)},[R,ae.length,Yt]),tn=(0,J.useCallback)((e,t)=>{let n;V.has(t)&&V.size>1?n=Array.from(V):(n=[t],Fe(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:z===`path`?a:void 0,sourceTreeName:o,sourceWorkspaceId:s};e.dataTransfer.setData(`application/json`,JSON.stringify(r)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[V,a,o,s,z]),nn=(0,J.useCallback)(async e=>{if(!S)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let n=null;try{n=JSON.parse(t)}catch{return}n?.type!==`document`||!Array.isArray(n.documentIds)||n.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),Kt(!1),!Dp(n,s,o,a)&&(await S(a,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),Fe(new Set)))},[a,o,s,S]),rn=(0,J.useCallback)(e=>{S&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,Kt(!0))},[S]),an=(0,J.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||Kt(!1)},[]),on=(0,J.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),sn=(0,J.useMemo)(()=>r.length===0?null:new ur(r,on),[r,on]),cn=(0,J.useDeferredValue)(K),q=(0,J.useMemo)(()=>{if(!cn.trim())return r;let{text:e,ids:t,invalid:n}=pf(cn);if(n)return[];let i=e&&sn?sn.search(e).map(e=>e.item):r;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[r,cn,sn]),ln=(0,J.useMemo)(()=>{if(!ve||ve.length===0||cn.trim())return[];let e=ce?.order===`desc`?-1:1;return[...ve].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)},[ve,cn,ce?.order]),un=ln.length>0,[dn,fn]=(0,J.useState)(null),pn=(0,J.useMemo)(()=>s&&o&&ye?(e,t)=>fn({x:t.clientX,y:t.clientY,path:e}):void 0,[s,o,ye]),mn={folders:ln,onOpen:ye,onMenu:pn,onPasteDocuments:S,contextPath:a,treeName:o,workspaceId:s},{sorted:gn,sort:_n,toggleSort:yn}=zp(q,(0,J.useMemo)(()=>({title:e=>Gt(e).title?.toLowerCase()??``,schema:e=>Gt(e).schemaLabel??``,type:vn,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),bn=(0,J.useCallback)(e=>lm(e,ce?.sortBy),[ce?.sortBy]),xn=(0,J.useMemo)(()=>vm(q,bn,ce?.order===`asc`?`asc`:`desc`),[q,bn,ce?.order]),Sn=Te&&!hn(ce?.sortBy)&&xn.length>1,Cn=(0,J.useCallback)((e,t)=>{Fe(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),wn=(0,J.useMemo)(()=>(B===`table`?gn:Sn?xn.filter(e=>!Oe.has(e.key)).flatMap(e=>e.items):q).map(e=>e.id),[B,gn,Sn,xn,Oe,q]),Tn=(0,J.useRef)(null),En=JSON.stringify([s,a,o,N]),Dn=(0,J.useCallback)(e=>{Tn.current=null,Fe(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),On=(0,J.useCallback)((e,t,n,r=!1)=>{let i=Tn.current,a=i?.scope===En&&wn.includes(i.id)?i.id:null;(!r||a===null)&&(Tn.current={scope:En,id:e}),Fe(i=>{if(r)return gf(wn,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[En,wn]),jn=(0,J.useCallback)((e,t)=>{let n;V.has(e)?n=Array.from(V):(n=[e],Fe(new Set([e]))),Le({anchor:t,ids:n})},[V]),Mn=(0,J.useCallback)((e,t)=>{jn(t,hc(e))},[jn]),Nn=(0,J.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),jn(t,Um(e)))},[jn]),Pn=(0,J.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){Je(!0);try{for(let n of t)await kn(s,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;Ot(`Created ${n} relation${n===1?``:`s`}`),hl(),Be(null)}catch(e){kt(e instanceof Error?e.message:`Failed to create relations`)}finally{Je(!1)}}},[s,Ot,kt]),Fn=(0,J.useCallback)(async(e,t,n)=>{if(S){for(let r of e)await S(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});Fe(new Set)}},[S]),In=(0,J.useCallback)(async(e,t,n)=>{if(!s||!Ye||ct.current)return;ct.current=!0,st.current=!1,ot(!1),et(!0);let i=At({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${Ye.ids.length} document(s) · ${e.join(`, `)}`});try{let a=r=>An(s,r,{to:e,mode:t,keepDocument:n.keepDocument,...t===`delete`&&lt?{deleteFrom:{backend:lt.backend,folder:lt.rel}}:{},folder:n.folder,filename:n.filename,onConflict:n.onConflict}),o=t===`delete`?await Dd(Ye.ids,a,{shouldStop:()=>st.current,onProgress:(t,n)=>{nt({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(Ye.ids),pending:[]},c=o.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,l=o.successful.filter(e=>e.transfers?.some(e=>e.state===`pending`)).length,u=o.successful.length-c-l,d=o.failed.length,f=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,p=e.join(`, `),m=[c?`${c} already there`:null,l?`${l} queued for backend sync`:null,d?`${d} skipped`:null,o.pending.length?`${o.pending.length} not processed`:null].filter(Boolean).join(` · `),h=`${f} ${p}: ${u} document${u===1?``:`s`}${m?` · ${m}`:``}`;d>0?(i.fail({title:`Operation incomplete`,description:`${h}. ${Rl(o.failed,new Map(r.map(e=>[e.id,Gt(e).title])))}`,variant:`destructive`}),console.warn(`Backend transfer skipped documents:`,o.failed)):i.done({title:o.pending.length?`Operation stopped`:l?`Transfer queued`:`Operation complete`,description:h}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`));let g=[...o.failed.map(e=>e.id),...o.pending];Qe(g.length?{ids:g,mode:t}:null),Fe(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{ct.current=!1,et(!1),nt(null)}},[s,Ye,lt,r,At]),Ln=(0,J.useCallback)(()=>{V.size===q.length?Fe(new Set):Fe(new Set(q.map(e=>e.id)))},[V.size,q]),Rn=(0,J.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)}},[]),zn=e=>{if(e.length===0)return[];let t=e.length,n=t>1?` (${t})`:``,i=t===1?r.find(t=>t.id===e[0]):void 0,a=()=>Fe(new Set),s=e.some(e=>r.find(t=>t.id===e)?.locations?.some(e=>e.status==null||e.status===`available`)),c=[],l=e=>{e&&c.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;l({id:`view`,group:`open`,label:`View details`,icon:dt,run:()=>Ct({document:i})}),l(U&&{id:`edit`,group:`open`,label:`Edit`,icon:k,run:()=>Ct({document:i,edit:!0})}),l(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:Ae,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),l(Mt&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:le,run:()=>Mt(i)})}return l(b&&{id:`copy`,group:`clipboard`,label:`Copy${n}`,icon:u,shortcut:`Mod+C`,run:()=>b(e)}),l(x&&{id:`cut`,group:`clipboard`,label:`Cut${n}`,icon:we,shortcut:`Mod+X`,run:()=>x(e)}),l(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:We,run:()=>Rn(String(i.id))}),l(i&&U&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:Ze,run:()=>xt(i)}),l(Et&&{id:`link-to`,group:`organize`,label:`Link to…${n}`,icon:Ne,run:()=>Be(e)}),l(Ue&&{id:`add-related`,group:`organize`,label:`Add related document…${n}`,icon:ze,run:t=>Ke(e,t?.shiftKey)}),l(U&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${n}`,icon:k,run:()=>bt(e)}),l(U&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:u,run:t=>{yt(!!t?.shiftKey),gt(e)}}),l({id:`export`,group:`organize`,label:`Export…${n}`,icon:Me,run:()=>Rt(!0)}),l(o!==`backends`&&(Pt||It)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${n}`,icon:v,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&Pt?Pt(e[0]):It?.(e),a()}}),l(o!==`backends`&&(p||g)&&{id:`delete`,group:`remove`,label:`Delete from index${n}`,icon:pe,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&p?p(e[0]):g?.(e),a()}}),s&&Dt?(l({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${n}`,icon:F,hint:`Copy the file data to another storage backend (keeps the existing copies)`,run:()=>Qe({ids:e,mode:`copy`})}),l({id:`backend-move`,group:`backends`,label:`Move to backend…${n}`,icon:Ve,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Qe({ids:e,mode:`move`})}),l({id:`backend-delete`,group:`backends`,label:`Delete from backend…${n}`,icon:pe,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Qe({ids:e,mode:`delete`})})):s&&(m||y)&&l({id:`destroy`,group:`backends`,label:`Delete from backend(s)${n}`,icon:pe,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&m?m(e[0]):y?.(e),a()}}),c},Bn=()=>{let e=[],t=t=>{t&&e.push(t)},n=T??[];return t(S&&n.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${n.length})`,icon:ee,shortcut:`Mod+V`,run:async()=>{try{await S(a,n)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(q.length>0&&{id:`select-all`,group:`select`,label:K?`Select all matches (${q.length})`:`Select all on this page`,icon:Ce,shortcut:`Mod+A`,run:()=>Fe(new Set(q.map(e=>e.id)))}),t(V.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:it,run:()=>Fe(new Set)}),t(S&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:Xe,hint:`Browse and add existing documents to this folder`,run:()=>pt(!0)}),t(C&&{id:`import`,group:`add`,label:`Import…`,icon:ue,run:()=>Bt(!0)}),t(r.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:Me,run:()=>{Fe(new Set),Rt(!0)}}),t(re&&d>0&&{id:`purge`,group:`purge`,label:`Purge all (${d})`,icon:pe,destructive:!0,disabled:ie||!!K,hint:K?`Purge is disabled while local search is active`:ie?`Purge requires loaded server results with no browser-only or live selection`:`Delete all documents matching the current server-side filters across all pages`,run:re}),e},Vn=!!(de&&ce&&s),Hn=Ie?Ie.ids?zn(Ie.ids):Bn():[],Un=Ie?.ids?.length===1?r.find(e=>e.id===Ie.ids[0]):void 0,Wn=Un?(0,X.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,X.jsx)(el,{document:Un,chip:!0}),(0,X.jsxs)(`div`,{className:`min-w-0`,children:[(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Gt(Un).title}),(0,X.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Un.id,` · `,Un.schema]})]})]}):(0,X.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Ie?.ids?`${Ie.ids.length} documents`:`This folder`}),Gn=e=>{Le({anchor:hc(e.currentTarget),ids:V.size>0?Array.from(V):null})},Kn=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),Fe(new Set),Le({anchor:Um(e),ids:null}))},qn=e=>{if(e.defaultPrevented||dc(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(pc(e)){e.preventDefault(),t?jn(Number(t.dataset.documentId),hc(t,`inside`)):Le({anchor:hc(e.target,`inside`),ids:V.size>0?Array.from(V):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&&On(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&V.size>0){e.preventDefault(),Fe(new Set);return}fc(e,[...zn(Array.from(V)),...Bn()])},Jn=(0,J.useCallback)(async e=>{if(!C)return!1;try{return await C(e,a)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[C,a]),Xn=e=>Sn?xn.map(t=>{let n=Oe.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!V.has(t),0);return(0,X.jsxs)(`section`,{className:`group mb-4`,children:[(0,X.jsx)(lh,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>Pe(t.key),onSelectAll:e=>Cn(r,e)}),!n&&e(t.items)]},t.key)}):e(q);return i?(0,X.jsx)(Td,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:[],loading:!0,children:(0,X.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,X.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,X.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})})}):(0,X.jsx)(Td,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:B===`table`?gn:q,loading:!1,children:(0,X.jsxs)(`div`,{tabIndex:-1,onKeyDown:qn,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${Wt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:rn,onDragLeave:an,onDrop:nn,children:[(0,X.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,X.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,X.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,X.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,X.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:K?`${q.length} of ${r.length}`:`${d.toLocaleString()} document${d===1?``:`s`}`})]}),(0,X.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,X.jsxs)(`p`,{hidden:Ut,className:`min-w-0 truncate`,children:[`Context: `,(0,X.jsx)(`span`,{className:`font-mono`,children:a}),j&&M&&j!==M&&(0,X.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,X.jsxs)(`p`,{className:`shrink-0`,children:[V.size>0&&(0,X.jsxs)(`span`,{className:`text-info`,children:[V.size,` selected`]}),V.size>0&&(K||d>P)&&(0,X.jsx)(`span`,{className:`mx-1`,children:`·`}),K?`on this page`:d>P?`Showing ${Math.min((N-1)*P+1,d)}–${Math.min(N*P,d)}`:null]})]})]}),!Ut&&(0,X.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,X.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[!Ut&&fe&&(0,X.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,X.jsx)(`button`,{type:`button`,onClick:()=>fe(`path`),className:`px-2.5 py-2 transition-colors ${z===`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,X.jsxs)(`button`,{type:`button`,onClick:()=>fe(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${z===`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,X.jsx)(se,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!Ut&&(0,X.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,X.jsx)(mt,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,X.jsx)(`input`,{ref:Jt,type:`text`,placeholder:oe?qt?`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=>Ht(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`&&oe&&(e.preventDefault(),$t())},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`}),(K||qt)&&(0,X.jsx)(`button`,{onClick:en,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,X.jsx)(E,{className:`h-4 w-4`})})]}),!Ut&&oe&&K.trim()&&!ae.includes(K.trim())&&(0,X.jsxs)(G,{size:`sm`,variant:`default`,onClick:$t,className:`shrink-0`,title:qt?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,X.jsx)(mt,{className:`h-3.5 w-3.5 mr-1`}),qt?`Refine`:`Search server`]})]}),!Ut&&qt&&(0,X.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,X.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),ae.map((e,t)=>(0,X.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,X.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,X.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,X.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),R&&(0,X.jsx)(`button`,{onClick:()=>R(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,X.jsx)(E,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),R&&ae.length>1&&(0,X.jsx)(`button`,{onClick:()=>R(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,X.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,X.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,X.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[A&&(0,X.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,ft,`Tile view`],[`card`,je,`Card view`]].map(([e,t,n])=>(0,X.jsx)(`button`,{type:`button`,onClick:()=>Se(e),title:n,"aria-pressed":B===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${B===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,X.jsx)(t,{className:`h-4 w-4`})},e))}),A&&B!==`table`&&!hn(ce?.sortBy)&&(0,X.jsx)(`button`,{type:`button`,onClick:De,title:Te?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":Te,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${Te?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,X.jsx)(_,{className:`h-4 w-4`})})]}),L&&d>0&&(0,X.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,X.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,X.jsxs)(`select`,{value:P,onChange:e=>te?.(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,X.jsx)(`option`,{value:25,children:`25`}),(0,X.jsx)(`option`,{value:50,children:`50`}),(0,X.jsx)(`option`,{value:100,children:`100`}),(0,X.jsx)(`option`,{value:200,children:`200`})]}),(0,X.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,X.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[Vn&&(0,X.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,X.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,X.jsx)(cm,{workspaceId:s,value:ce,onChange:de})]}),(0,X.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(r.length>0||C||S)&&(0,X.jsxs)(`div`,{className:`contents`,children:[(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:Gn,"aria-haspopup":`menu`,"aria-label":V.size>0?`Actions (${V.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${lc(`Shift+F10`)} or right-click)`,children:[(0,X.jsx)(Ge,{className:`h-4 w-4`}),(0,X.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,V.size>0?` (${V.size} selected)`:``]})]}),V.size>0&&(0,X.jsxs)(G,{variant:`ghost`,size:`sm`,onClick:()=>Fe(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,X.jsx)(E,{className:`h-3.5 w-3.5`}),(0,X.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),T&&T.length>0&&S&&(0,X.jsxs)(G,{variant:`outline`,size:`sm`,onClick:()=>S(a,T),className:`flex items-center gap-1.5`,title:`Paste into this folder (${lc(`Mod+V`)})`,children:[(0,X.jsx)(ee,{className:`h-4 w-4`}),`Paste (`,T.length,`)`]})]}),me&&ge&&(0,X.jsx)(G,{size:`sm`,variant:`outline`,onClick:ge,disabled:he,className:`w-control-sm shrink-0 px-0 touch-target`,"aria-label":he?`Saving filters`:`Save current query and filters`,title:`Save current query and filters`,children:(0,X.jsx)(ne,{className:`h-3.5 w-3.5`})}),n]})]})]})}),L&&d>P&&(0,X.jsxs)(`div`,{className:`document-pagination mt-3 flex min-w-0 flex-wrap items-center justify-end gap-2 border-t pt-3 max-sm:gap-0.5`,children:[(0,X.jsxs)(`span`,{className:`text-sm text-muted-foreground max-md:hidden`,children:[`Showing `,Math.min((N-1)*P+1,d),` - `,Math.min(N*P,d),` of `,d]}),(0,X.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,X.jsx)(G,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>L(1),disabled:N===1,className:`p-1 touch-target`,children:(0,X.jsx)(I,{className:`h-4 w-4`})}),(0,X.jsx)(G,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>L(N-1),disabled:N===1,className:`p-1 touch-target`,children:(0,X.jsx)(l,{className:`h-4 w-4`})}),(0,X.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,X.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),N,(0,X.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,X.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(d/P)]}),(0,X.jsx)(G,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>L(N+1),disabled:N>=Math.ceil(d/P),className:`p-1 touch-target`,children:(0,X.jsx)(vt,{className:`h-4 w-4`})}),(0,X.jsx)(G,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>L(Math.ceil(d/P)),disabled:N>=Math.ceil(d/P),className:`p-1 touch-target`,children:(0,X.jsx)(O,{className:`h-4 w-4`})})]})]})]}),(0,X.jsx)(bp,{scope:JSON.stringify([En,B,wn]),selected:V,onSelectionChange:Dn,onContextMenu:Kn,children:q.length===0&&!un?(0,X.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,X.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,X.jsx)(rt,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,X.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:K?`No documents match your search`:`No documents found in this context`}),(0,X.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:K?(0,X.jsxs)(X.Fragment,{children:[`Search: `,(0,X.jsxs)(`span`,{className:`font-mono`,children:[`"`,K,`"`]})]}):(0,X.jsxs)(X.Fragment,{children:[`Path: `,(0,X.jsx)(`span`,{className:`font-mono`,children:a})]})}),!Ut&&K&&(0,X.jsx)(`button`,{onClick:Yt,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!K&&T&&T.length>0&&(0,X.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,lc(`Mod+V`),` to paste `,T.length,` document(s)`]})]})}):B===`tile`?(0,X.jsxs)(`div`,{children:[(0,X.jsx)(oh,{...mn}),q.length===0&&(0,X.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Xn(e=>(0,X.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,X.jsx)($m,{document:e,isSelected:V.has(e.id),workspaceId:s,onSelect:On,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn},e.id))}))]}):B===`table`?(0,X.jsx)(`div`,{children:(0,X.jsxs)(Ap,{children:[(0,X.jsx)(jp,{children:(0,X.jsxs)(Pp,{children:[(0,X.jsx)(Fp,{className:`w-10`,children:(0,X.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:q.length>0&&V.size===q.length,ref:e=>{e&&(e.indeterminate=V.size>0&&V.size<q.length)},onChange:Ln,title:`Select all on this page`})}),(0,X.jsx)(Rp,{label:(0,X.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:_n,onSort:yn,className:`w-12`}),(0,X.jsx)(Rp,{label:`Title`,sortKey:`title`,sort:_n,onSort:yn,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,X.jsx)(Rp,{label:`Schema`,sortKey:`schema`,sort:_n,onSort:yn,className:`hidden md:table-cell`}),(0,X.jsx)(Rp,{label:`ID`,sortKey:`id`,sort:_n,onSort:yn,className:`hidden lg:table-cell`}),(0,X.jsx)(Fp,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,X.jsx)(Rp,{label:`Created`,sortKey:`created`,sort:_n,onSort:yn,className:`hidden sm:table-cell`}),(0,X.jsx)(Fp,{className:`w-12 md:w-auto`,children:(0,X.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,X.jsxs)(Mp,{children:[ln.map(e=>(0,X.jsx)(ch,{folder:e,onOpen:ye,onMenu:pn,onPasteDocuments:S,contextPath:a,treeName:o,workspaceId:s},e.path)),gn.map(e=>(0,X.jsx)(Km,{document:e,isSelected:V.has(e.id),workspaceId:s,onSelect:On,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn},e.id))]})]})}):(0,X.jsxs)(`div`,{children:[(0,X.jsx)(sh,{...mn}),q.length===0&&(0,X.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Xn(e=>(0,X.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,X.jsx)(`div`,{children:(0,X.jsx)(qm,{document:e,isSelected:V.has(e.id),workspaceId:s,onSelect:On,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn})},e.id))}))]})}),Ie&&(0,X.jsx)(bc,{anchor:Ie.anchor,items:Hn,onClose:()=>Le(null),label:Ie.ids?`Document actions`:`Folder actions`,header:Wn}),(0,X.jsx)(Bm,{isOpen:Lt,onClose:()=>Rt(!1),documents:r,selectedDocuments:V}),(0,X.jsx)(Vm,{isOpen:zt,onClose:()=>Bt(!1),onImport:Jn}),ht&&s&&(0,X.jsx)(Sp,{modal:_t,workspaceId:s,ids:ht,onClose:()=>gt(null)}),Re&&_e&&(0,X.jsx)(Sf,{label:`Link to`,onClose:()=>Be(null),children:(0,X.jsx)(pl,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:Re.length,fixedWorkspaceName:s,tabs:[`context`,`directory`,`relations`],saving:qe,relationExcludeIds:new Set(Re),onConfirm:(e,t)=>Fn(e,Re,t),onConfirmRelation:e=>Pn(e,Re),onClose:()=>Be(null)})}),Ye&&s&&(0,uo.createPortal)((0,X.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,X.jsx)(Gl,{workspaceId:s,documentCount:Ye.ids.length,initialMode:Ye.mode,defaultFilename:Ye.ids.length===1?Ft(r.find(e=>e.id===Ye.ids[0])??{}):``,saving:$e,progress:tt,stopping:at,onStop:()=>{st.current=!0,ot(!0)},deleteFrom:lt?{backend:lt.backend,folder:lt.rel}:void 0,onConfirm:In,onClose:()=>{$e||Qe(null)}})}),window.document.body),ut&&S&&(0,uo.createPortal)((0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>pt(!1),"aria-hidden":!0}),(0,X.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,X.jsx)(Op,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:s,onConfirm:async e=>{await S(a,e),pt(!1)},onClose:()=>pt(!1)})})]}),window.document.body),W&&s&&(0,X.jsx)(mp,{workspaceId:s,document:W,onClose:()=>xt(null)},`${s}:${W.id}`),H&&s&&(0,X.jsx)(Tp,{workspaceId:s,documentIds:H,onClose:()=>bt(null)}),(0,X.jsx)(Jp,{document:St?.document??null,isOpen:!!St,onClose:()=>Ct(null),workspaceId:s,initialEdit:St?.edit}),dn&&s&&o&&ye&&(0,X.jsx)(Rm,{x:dn.x,y:dn.y,workspaceName:s,treeName:o,path:dn.path,onClose:()=>fn(null),onOpen:ye,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:s,treeName:o,path:e}})),pastedDocumentIds:T,onPasteDocuments:S?(e,t)=>S(e,t):void 0})]})})}function dh(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,po.createRoot)(t);n.render((0,X.jsx)(Vm,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function fh(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,po.createRoot)(t);n.render((0,X.jsx)(Bm,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{Gd as $,da as $n,tl as $t,Ap as A,Os as An,Uu as At,kf as B,wo as Bn,zl as Bt,tm as C,Ns as Cn,hd as Ct,qp as D,ks as Dn,qu as Dt,Gp as E,Cs as En,Qu as Et,Pp as F,Ko as Fn,ku as Ft,Sf as G,Za as Gn,kl as Gt,Ef as H,ho as Hn,Il as Ht,Op as I,Lo as In,bu as It,$d as J,sa as Jn,yl as Jt,_f as K,Qa as Kn,xl as Kt,Dp as L,Ro as Ln,hu as Lt,Ip as M,bs as Mn,Bu as Mt,Fp as N,cs as Nn,Hu as Nt,zp as O,Es as On,Ku as Ot,jp as P,$o as Pn,Pu as Pt,Xd as Q,Ci as Qn,nl as Qt,Tp as R,No as Rn,$l as Rt,em as S,Ps as Sn,vd as St,Jp as T,js as Tn,fd as Tt,Tf as U,fo as Un,Fl as Ut,Of as V,go as Vn,Bl as Vt,Df as W,mr as Wn,Dl as Wt,of as X,ca as Xn,hl as Xt,ff as Y,xi as Yn,gl as Yt,tf as Z,la as Zn,pl as Zt,Qp as _,dc as _n,rf as _t,Mm as a,Tc as an,Fi as ar,Zd as at,nm as b,ac as bn,wd as bt,km as c,Oc as cn,Ld as ct,Dm as d,Nc as dn,Yd as dt,el as en,Sr as er,Md as et,ym as f,Sc as fn,Qd as ft,im as g,bc as gn,jd as gt,cm as h,Cc as hn,sf as ht,Im as i,Hc as in,Mi as ir,lf as it,Mp as j,As as jn,Gu as jt,Rp as k,Ds as kn,Ju as kt,Cm as l,Dc as ln,Id as lt,xm as m,Pc as mn,Wd as mt,Lm as n,Wc as nn,Er as nr,nf as nt,Om as o,wc as on,zi as or,Bd as ot,bm as p,Fc as pn,cf as pt,hf as q,Si as qn,bl as qt,Fm as r,Uc as rn,Cr as rr,Ad as rt,Tm as s,Ec as sn,io as sr,af as st,uh as t,zc as tn,fa as tr,uf as tt,wm as u,Mc as un,kd as ut,Xp as v,uc as vn,zd as vt,Zp as w,Fs as wn,md as wt,$p as x,Ms as xn,xd as xt,rm as y,oc as yn,Ud as yt,pp as z,So as zn,Kl as zt};