@augmentd-labs/canvas-web 2.26.10 → 2.26.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/document-list-C3BYe-Bx.js +19 -0
- package/dist/assets/document-list-r-TfV16D.css +1 -0
- package/dist/assets/index-C3CrR-Lb.js +40 -0
- package/dist/assets/index-VRpQX_cE.css +2 -0
- package/dist/index.html +4 -4
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/document-list-Czq5vO7b.js +0 -19
- package/dist/assets/document-list-DA2cbw9T.css +0 -1
- package/dist/assets/index-BIaKTlod.css +0 -2
- package/dist/assets/index-CD9Vf1gH.js +0 -40
|
@@ -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 Se,an as B,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 Fe,ii as V,in as H,ir as Ie,jn as Le,jt as Re,kn as ze,li as Be,ln as Ve,lr as He,mn as Ue,mr as We,ni as Ge,nn as Ke,nr as qe,nt as Je,or as Ye,ot as Xe,pt as Ze,qn as Qe,qr as $e,qt as et,rn as tt,rr as nt,rt,sr as it,st as at,tr as ot,tt as st,ui as ct,un as lt,ur as ut,vn as dt,vr as ft,vt as pt,wt as mt,xr as ht,yr as gt,zr as _t,zt as vt}from"./ui-NWo4bzrd.js";import{t as U}from"./utils-2pl1SbIp.js";import{_ as yt,b as W,u as G,v as bt,x as K,y as xt}from"./alert-dialog-CDKOX-MP.js";import{t as St}from"./socket-hM4c-ZSl.js";import{l as Ct,s as wt}from"./blobs-B3DY8Rsp.js";import{$ as Tt,$t as Et,A as Dt,At as Ot,En as kt,Fn as At,Ft as jt,Gn as Mt,Ht as Nt,In as Pt,It as Ft,J as It,Jn as Lt,Jt as Rt,K as zt,Kn as Bt,Lt as Vt,On as Ht,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 ln,g as un,gt as dn,h as fn,hn as pn,ht as mn,it as hn,jn as gn,jt as _n,k as vn,kn as yn,l as bn,mn as xn,nt as Sn,pn as Cn,q as wn,qn as Tn,r as En,s as Dn,t as On,u as kn,v as An,vn as jn,wn as Mn,xn as Nn,yn as Pn,zt as Fn}from"./workspace-BYMC2sfI.js";import{a as In,c as Ln,d as Rn,f as zn,h as Bn,i as Vn,m as Hn,n as Un,o as Wn,p as Gn,r as Kn,s as qn,t as Jn,v as Yn,y as Xn}from"./text-documents-D4tmVh-7.js";import{A as Zn,C as Qn,E as $n,M as er,R as tr,S as nr,k as rr,l as ir,o as ar,v as or,x as sr}from"./useAddTarget-Bprwjjdn.js";import{t as cr}from"./sanitize-DrVcFY1Q.js";import{t as lr}from"./markdown-it-DRESbtwK.js";import{n as ur}from"./map-BxCwdK0d.js";import{t as dr}from"./search-COMZIxA7.js";var q=e(r(),1),fr=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,pr=/^[\\/]{2}/;function mr(e,t){return t+e.replace(/\\/g,`/`)}var hr=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(hr||{}),gr=`popstate`;function _r(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function vr(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return Sr(``,{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:Cr(t)}return Tr(t,n,null,e)}function J(e,t){if(e===!1||e==null)throw Error(t)}function yr(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function br(){return Math.random().toString(36).substring(2,10)}function xr(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 Sr(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?wr(t):t,state:n,key:t&&t.key||r||br(),mask:i}}function Cr({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 wr(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 Tr(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=_r(e)?e:Sr(h.location,e,t);n&&n(r,e),l=u()+1;let d=xr(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=_r(e)?e:Sr(h.location,e,t);n&&n(r,e),l=u();let i=xr(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 Er(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(gr,d),c=e,()=>{i.removeEventListener(gr,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 Er(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),J(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:Cr(t);return i=i.replace(/ $/,`%20`),!n&&pr.test(i)&&(i=r+i),new URL(i,r)}function Dr(e,t,n=`/`){return Or(e,t,n,!1)}function Or(e,t,n,r,i){let a=qr((typeof t==`string`?wr(t):t).pathname||`/`,n);if(a==null)return null;let o=i??kr(e),s=null,c=Kr(a);for(let e=0;s==null&&e<o.length;++e)s=Hr(o[e],c,r);return s}function kr(e){let t=Ar(e);return Mr(t),t}function Ar(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;J(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=ti([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(J(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),Ar(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:Br(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Gr(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 jr(e.path))a(e,t,!0,n)}),t}function jr(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=jr(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 Mr(e){e.sort((e,t)=>e.score===t.score?Vr(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var Nr=/^:[\w-]+$/,Pr=3,Fr=2,Ir=1,Lr=10,Rr=-2,zr=e=>e===`*`;function Br(e,t){let n=e.split(`/`),r=n.length;return n.some(zr)&&(r+=Rr),t&&(r+=Fr),n.filter(e=>!zr(e)).reduce((e,t)=>e+(Nr.test(t)?Pr:t===``?Ir:Lr),r)}function Vr(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 Hr(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?Wr(u,l,s.matcher,s.compiledParams):Ur(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=Ur({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:ti([a,d.pathname]),pathnameBase:ri(ti([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=ti([a,d.pathnameBase]))}return o}function Ur(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Gr(e.path,e.caseSensitive,e.end);return Wr(e,t,n,r)}function Wr(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 Gr(e,t=!1,n=!0){yr(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 Kr(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return yr(!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 qr(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 Jr(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?wr(e):e,a;return n?(n=ei(n),a=n.startsWith(`/`)?Yr(n.substring(1),`/`):Yr(n,t)):a=t,{pathname:a,search:ii(r),hash:ai(i)}}function Yr(e,t){let n=ni(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Xr(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 Zr(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Qr(e){let t=Zr(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function $r(e,t,n,r=!1){let i;typeof e==`string`?i=wr(e):(i={...e},J(!i.pathname||!i.pathname.includes(`?`),Xr(`?`,`pathname`,`search`,i)),J(!i.pathname||!i.pathname.includes(`#`),Xr(`#`,`pathname`,`hash`,i)),J(!i.search||!i.search.includes(`#`),Xr(`#`,`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=Jr(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var ei=e=>e.replace(/[\\/]{2,}/g,`/`),ti=e=>ei(e.join(`/`)),ni=e=>e.replace(/\/+$/,``),ri=e=>ni(e).replace(/^\/*/,`/`),ii=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,ai=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,oi=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 si(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function ci(e){return ti(e.map(e=>e.route.path).filter(Boolean))||`/`}var li=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function ui(e,t){let n=e;if(typeof n!=`string`||!fr.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(li)try{let e=new URL(window.location.href),r=pr.test(n)?new URL(mr(n,e.protocol)):new URL(n),a=qr(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{yr(!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 di=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(di);var fi=[`GET`,...di];new Set(fi);var pi=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function mi(e){try{return pi.includes(new URL(e).protocol)}catch{return!1}}var hi=q.createContext(null);hi.displayName=`DataRouter`;var gi=q.createContext(null);gi.displayName=`DataRouterState`;var _i=q.createContext(!1);function vi(){return q.useContext(_i)}var yi=q.createContext({isTransitioning:!1});yi.displayName=`ViewTransition`;var bi=q.createContext(new Map);bi.displayName=`Fetchers`;var xi=q.createContext(null);xi.displayName=`Await`;var Si=q.createContext(null);Si.displayName=`Navigation`;var Ci=q.createContext(null);Ci.displayName=`Location`;var wi=q.createContext({outlet:null,matches:[],isDataRoute:!1});wi.displayName=`Route`;var Ti=q.createContext(null);Ti.displayName=`RouteError`;var Ei=`REACT_ROUTER_ERROR`,Di=`REDIRECT`,Oi=`ROUTE_ERROR_RESPONSE`;function ki(e){if(e.startsWith(`${Ei}:${Di}:{`))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 Ai(e){if(e.startsWith(`${Ei}:${Oi}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new oi(t.status,t.statusText,t.data)}catch{}}function ji(e,{relative:t}={}){J(Mi(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=q.useContext(Si),{hash:i,pathname:a,search:o}=Vi(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:ti([n,a])),r.createHref({pathname:s,search:o,hash:i})}function Mi(){return q.useContext(Ci)!=null}function Ni(){return J(Mi(),`useLocation() may be used only in the context of a <Router> component.`),q.useContext(Ci).location}var Pi=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Fi(e){q.useContext(Si).static||q.useLayoutEffect(e)}function Ii(){let{isDataRoute:e}=q.useContext(wi);return e?ia():Li()}function Li(){J(Mi(),`useNavigate() may be used only in the context of a <Router> component.`);let e=q.useContext(hi),{basename:t,navigator:n}=q.useContext(Si),{matches:r}=q.useContext(wi),{pathname:i}=Ni(),a=JSON.stringify(Qr(r)),o=q.useRef(!1);return Fi(()=>{o.current=!0}),q.useCallback((r,s={})=>{if(yr(o.current,Pi),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=$r(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:ti([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var Ri=q.createContext(null);function zi(e){let t=q.useContext(wi).outlet;return q.useMemo(()=>t&&q.createElement(Ri.Provider,{value:e},t),[t,e])}function Bi(){let{matches:e}=q.useContext(wi);return e[e.length-1]?.params??{}}function Vi(e,{relative:t}={}){let{matches:n}=q.useContext(wi),{pathname:r}=Ni(),i=JSON.stringify(Qr(n));return q.useMemo(()=>$r(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Hi(e,t){return Ui(e,t)}function Ui(e,t,n){J(Mi(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=q.useContext(Si),{matches:i}=q.useContext(wi),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||``;oa(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=Ni(),d;if(t){let e=typeof t==`string`?wr(t):t;J(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})):Dr(e,{pathname:p});yr(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),yr(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=Xi(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:ti([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:ti([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?q.createElement(Ci.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function Wi(){let e=ra(),t=si(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=q.createElement(q.Fragment,null,q.createElement(`p`,null,`💿 Hey developer 👋`),q.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,q.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,q.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),q.createElement(q.Fragment,null,q.createElement(`h2`,null,`Unexpected Application Error!`),q.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?q.createElement(`pre`,{style:i},n):null,o)}var Gi=q.createElement(Wi,null),Ki=class extends q.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=Ai(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:q.createElement(wi.Provider,{value:this.props.routeContext},q.createElement(Ti.Provider,{value:e,children:this.props.component}));return this.context?q.createElement(Ji,{error:e},t):t}};Ki.contextType=_i;var qi=new WeakMap;function Ji({children:e,error:t}){let{basename:n}=q.useContext(Si);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=ki(t.digest);if(e){let r=qi.get(t);if(r)throw r;let i=ui(e.location,n),a=i.absoluteURL||i.to;if(mi(a))throw Error(`Invalid redirect location`);if(li&&!qi.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 qi.set(t,n),n}}return q.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function Yi({routeContext:e,match:t,children:n}){let r=q.useContext(hi);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),q.createElement(wi.Provider,{value:e},n)}function Xi(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);J(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:ci(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||Gi,o&&(s<0&&c===0?(oa(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?q.createElement(n.route.Component,null):n.route.element?n.route.element:e,q.createElement(Yi,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?q.createElement(Ki,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Zi(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Qi(e){let t=q.useContext(hi);return J(t,Zi(e)),t}function $i(e){let t=q.useContext(gi);return J(t,Zi(e)),t}function ea(e){let t=q.useContext(wi);return J(t,Zi(e)),t}function ta(e){let t=ea(e),n=t.matches[t.matches.length-1];return J(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function na(){return ta(`useRouteId`)}function ra(){let e=q.useContext(Ti),t=$i(`useRouteError`),n=ta(`useRouteError`);return e===void 0?t.errors?.[n]:e}function ia(){let{router:e}=Qi(`useNavigate`),t=ta(`useNavigate`),n=q.useRef(!1);return Fi(()=>{n.current=!0}),q.useCallback(async(r,i={})=>{yr(n.current,Pi),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var aa={};function oa(e,t,n){!t&&!aa[e]&&(aa[e]=!0,yr(!1,n))}q.memo(sa);function sa({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Ui(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function ca({to:e,replace:t,state:n,relative:r}){J(Mi(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=q.useContext(Si);yr(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:a}=q.useContext(wi),{pathname:o}=Ni(),s=Ii(),c=$r(e,Qr(a),o,r===`path`),l=JSON.stringify(c);return q.useEffect(()=>{s(JSON.parse(l),{replace:t,state:n,relative:r})},[s,l,r,t,n]),null}function la(e){return zi(e.context)}function ua(e){J(!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 da({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){J(!Mi(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=q.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=wr(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=q.useMemo(()=>{let e=qr(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 yr(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:q.createElement(Si.Provider,{value:c},q.createElement(Ci.Provider,{children:t,value:h}))}function fa({children:e,location:t}){return Hi(pa(e),t)}q.Component;function pa(e,t=[]){let n=[];return q.Children.forEach(e,(e,r)=>{if(!q.isValidElement(e))return;let i=[...t,r];if(e.type===q.Fragment){n.push.apply(n,pa(e.props.children,i));return}J(e.type===ua,`[${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>`),J(!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=pa(e.props.children,i)),n.push(a)}),n}var ma=`get`,ha=`application/x-www-form-urlencoded`;function ga(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function _a(e){return ga(e)&&e.tagName.toLowerCase()===`button`}function va(e){return ga(e)&&e.tagName.toLowerCase()===`form`}function ya(e){return ga(e)&&e.tagName.toLowerCase()===`input`}function ba(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function xa(e,t){return e.button===0&&(!t||t===`_self`)&&!ba(e)}function Sa(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 Ca(e,t){let n=Sa(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var wa=null;function Ta(){if(wa===null)try{new FormData(document.createElement(`form`),0),wa=!1}catch{wa=!0}return wa}var Ea=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Da(e){return e!=null&&!Ea.has(e)?(yr(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${ha}"`),null):e}function Oa(e,t){let n,r,i,a,o;if(va(e)){let o=e.getAttribute(`action`);r=o?qr(o,t):null,n=e.getAttribute(`method`)||ma,i=Da(e.getAttribute(`enctype`))||ha,a=new FormData(e)}else if(_a(e)||ya(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?qr(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||ma,i=Da(e.getAttribute(`formenctype`))||Da(o.getAttribute(`enctype`))||ha,a=new FormData(o,e),!Ta()){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(ga(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=ma,r=null,i=ha,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 ka(e,t){if(e===!1||e==null)throw Error(t)}function Aa(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&&qr(i.pathname,t)===`/`?`${ni(t)}/_root.${r}`:`${ni(i.pathname)}.${r}`,i}async function ja(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 Ma(e){return e!=null&&typeof e.page==`string`}function Na(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 Pa(e,t,n){return za((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await ja(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Na).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Fa(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 Ia(e,t,{includeHydrateFallback:n}={}){return La(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 La(e){return[...new Set(e)]}function Ra(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function za(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!Ma(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(Ra(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function Ba(){let e=q.useContext(hi);return ka(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function Va(){let e=q.useContext(gi);return ka(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Ha=q.createContext(void 0);Ha.displayName=`FrameworkContext`;function Ua(){let e=q.useContext(Ha);return ka(e,`You must render this element inside a <HydratedRouter> element`),e}function Wa(e,t){let n=q.useContext(Ha),[r,i]=q.useState(!1),[a,o]=q.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=q.useRef(null);q.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),q.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:Ga(s,p),onBlur:Ga(c,m),onMouseEnter:Ga(l,p),onMouseLeave:Ga(u,m),onTouchStart:Ga(d,p)}]:[a,f,{}]:[!1,f,{}]}function Ga(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Ka({page:e,...t}){let n=vi(),{nonce:r}=Ua(),{router:i}=Ba(),a=q.useMemo(()=>Dr(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?q.createElement(Ja,{page:e,matches:a,...t}):q.createElement(Ya,{page:e,matches:a,...t})):null}function qa(e){let{manifest:t,routeModules:n}=Ua(),[r,i]=q.useState([]);return q.useEffect(()=>{let r=!1;return Pa(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Ja({page:e,matches:t,...n}){let r=Ni(),{future:i}=Ua(),{basename:a}=Ba(),o=q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=Aa(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return q.createElement(q.Fragment,null,o.map(e=>q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function Ya({page:e,matches:t,...n}){let r=Ni(),{future:i,manifest:a,routeModules:o}=Ua(),{basename:s}=Ba(),{loaderData:c,matches:l}=Va(),u=q.useMemo(()=>Fa(e,t,l,a,r,`data`),[e,t,l,a,r]),d=q.useMemo(()=>Fa(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=Aa(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=q.useMemo(()=>Ia(d,a),[d,a]),m=qa(d);return q.createElement(q.Fragment,null,f.map(e=>q.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>q.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>q.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Xa(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}q.Component;var Za=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Za&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Qa({basename:e,children:t,useTransitions:n,window:r}){let i=q.useRef();i.current??=vr({window:r,v5Compat:!0});let a=i.current,[o,s]=q.useState({action:a.action,location:a.location}),c=q.useCallback(e=>{n===!1?s(e):q.startTransition(()=>s(e))},[n]);return q.useLayoutEffect(()=>a.listen(c),[a,c]),q.createElement(da,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var $a=q.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:_}=q.useContext(Si),v=typeof l==`string`&&fr.test(l),y=ui(l,h);l=y.to;let b=ji(l,{relative:r}),x=Ni(),S=null;if(o){let e=$r(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:ti([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=Wa(n,p),E=io(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:_});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(y.isExternal||i),k=q.createElement(`a`,{...p,...T,href:(O?S:void 0)||y.absoluteURL||b,onClick:O?D:e,ref:Xa(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?q.createElement(q.Fragment,null,k,q.createElement(Ka,{page:b})):k});$a.displayName=`Link`;var eo=q.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=Vi(a,{relative:c.relative}),d=Ni(),f=q.useContext(gi),{navigator:p,basename:m}=q.useContext(Si),h=f!=null&&uo(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=qr(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(g.length)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return q.createElement($a,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});eo.displayName=`NavLink`;var to=q.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=ma,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=q.useContext(Si),g=co(),_=lo(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&fr.test(s);return q.createElement(`form`,{ref:m,method:v,action:_,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?q.startTransition(()=>p()):p()},...p,"data-discover":!y&&e===`render`?`true`:void 0})});to.displayName=`Form`;function no(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function ro(e){let t=q.useContext(hi);return J(t,no(e)),t}function io(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Ii(),d=Ni(),f=Vi(e,{relative:o});return q.useCallback(p=>{if(xa(p,t)){p.preventDefault();let t=n===void 0?Cr(d)===Cr(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?q.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function ao(e){yr(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=q.useRef(Sa(e)),n=q.useRef(!1),r=Ni(),i=q.useMemo(()=>Ca(r.search,n.current?null:t.current),[r.search]),a=Ii();return[i,q.useCallback((e,t)=>{let r=Sa(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var oo=0,so=()=>`__${String(++oo)}__`;function co(){let{router:e}=ro(`useSubmit`),{basename:t}=q.useContext(Si),n=na(),r=e.fetch,i=e.navigate;return q.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Oa(e,t);if(a.navigate===!1){let e=a.fetcherKey||so();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 lo(e,{relative:t}={}){let{basename:n}=q.useContext(Si),r=q.useContext(wi);J(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...Vi(e||`.`,{relative:t})},o=Ni();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:ti([n,a.pathname])),Cr(a)}function uo(e,{relative:t}={}){let n=q.useContext(yi);J(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=ro(`useViewTransitionState`),i=Vi(e,{relative:t});if(!n.isTransitioning)return!1;let a=qr(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=qr(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Ur(i.pathname,o)!=null||Ur(i.pathname,a)!=null}var fo=e(o(),1),Y=n(),po=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(xe,{ref:n,className:U(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));po.displayName=xe.displayName;var mo=a();function ho(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var go=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=xt,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||ho();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=St(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 _o({className:e=`h-5 w-5`,...t}){return(0,Y.jsxs)(`svg`,{className:`animate-spin ${e}`,xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 24 24`,...t,children:[(0,Y.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Y.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 vo=[{id:`square`,label:`Square (Lychee-like)`},{id:`flickr`,label:`Justified (Flickr-like)`},{id:`masonry`,label:`Masonry (500px-like)`},{id:`original`,label:`Original proportions`}],yo=`canvas:tileStyle`;function bo(){try{let e=localStorage.getItem(yo);return vo.some(t=>t.id===e)?e:`masonry`}catch{return`masonry`}}var xo=bo(),So=new Set;function Co(){return xo}function wo(e){try{localStorage.setItem(yo,e)}catch{}xo=e;for(let e of So)e()}function To(e){So.add(e);let t=t=>{(t.key===yo||t.key===null)&&(xo=bo(),e())};return window.addEventListener(`storage`,t),()=>{So.delete(e),window.removeEventListener(`storage`,t)}}function Eo(){return(0,q.useSyncExternalStore)(To,Co,()=>`masonry`)}var Do=`canvas:alwaysOnReader`;function Oo(){try{return localStorage.getItem(Do)!==`off`}catch{return!0}}var ko=Oo(),Ao=new Set;function jo(){return ko}function Mo(e){try{localStorage.setItem(Do,e?`on`:`off`)}catch{}ko=e;for(let e of Ao)e()}function No(e){Ao.add(e);let t=t=>{(t.key===Do||t.key===null)&&(ko=Oo(),e())};return window.addEventListener(`storage`,t),()=>{Ao.delete(e),window.removeEventListener(`storage`,t)}}function Po(){return(0,q.useSyncExternalStore)(No,jo,()=>!0)}var Fo=`canvas:readerWidth`,Io=320,Lo=1600;function Ro(){try{let e=Number(sessionStorage.getItem(Fo));return Number.isFinite(e)&&e>=Io&&e<=Lo?e:null}catch{return null}}var zo=Ro(),Bo=new Set;function Vo(e){return Bo.add(e),()=>{Bo.delete(e)}}function Ho(e){zo=e===null?null:Math.round(Math.max(Io,Math.min(Lo,e)));try{zo===null?sessionStorage.removeItem(Fo):sessionStorage.setItem(Fo,String(zo))}catch{}Bo.forEach(e=>e())}function Uo(){return(0,q.useSyncExternalStore)(Vo,()=>zo,()=>null)}var Wo=`(max-width: 767px)`,Go=new Map;function Ko(e){let t=Go.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},Go.set(e,t)}return t}function qo(){let e=Ko(Wo);return(0,q.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>!1)}function Jo(){return Yo(`(max-width: 1023px)`)}function Yo(e){let t=Ko(e);return(0,q.useSyncExternalStore)(t.subscribe,t.getSnapshot,()=>!1)}var Xo=1,Zo=8,Qo=320,$o=28,es=2.5,ts={scale:1,x:0,y:0};function ns({src:e,alt:t,className:n=``,onZoomChange:r}){let i=(0,q.useRef)(null),a=(0,q.useRef)(null),[o,s]=(0,q.useState)(ts),c=(0,q.useRef)(new Map),l=(0,q.useRef)(null),u=(0,q.useRef)(null),d=(0,q.useRef)(!1),f=(0,q.useRef)(null),[p,m]=(0,q.useState)(!1),[h,g]=(0,q.useState)(e);h!==e&&(g(e),s(ts)),(0,q.useEffect)(()=>{r?.(o.scale>1.001)},[o.scale,r]);let _=(0,q.useCallback)(e=>{let t=i.current,n=a.current;if(!t||!n)return e;let r=Math.min(Zo,Math.max(Xo,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,q.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,q.useCallback)(()=>{let e=i.current,t=a.current;if(!e||!t||!t.offsetWidth||!t.offsetHeight)return es;let n=Math.max(e.clientWidth/t.offsetWidth,e.clientHeight/t.offsetHeight),r=Math.max(t.naturalWidth/t.offsetWidth,t.naturalHeight/t.offsetHeight)||Zo;return Math.min(Zo,Math.max(es,Math.min(Math.max(n,es),r)))},[]),b=(0,q.useCallback)((e,t)=>{o.scale>1.001?s(ts):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<Qo&&Math.hypot(e.clientX-n.x,e.clientY-n.y)<$o){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<=Xo?s(ts):v(Math.min(Zo,t),e.clientX,e.clientY)},T=o.scale>1.001;return(0,Y.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<Qo)&&b(e.clientX,e.clientY)},children:(0,Y.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 rs=(0,q.createContext)(null);function is(){return!/android|iphone|ipad|mobile/i.test(navigator.userAgent)&&navigator.pdfViewerEnabled!==!1}var as=40,os=1600;function ss({blob:e,filename:t}){let n=(0,q.useRef)(null),[r,i]=(0,q.useState)({error:null,pages:0,truncated:!1});return(0,q.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,as),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,os*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>as})}})().catch(e=>{a||i(t=>({...t,error:e instanceof Error?e.message:String(e)}))}),()=>{a=!0,o?.(),r.replaceChildren()}},[e,t]),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[r.error&&(0,Y.jsxs)(`p`,{className:`text-sm text-destructive`,children:[`Could not render PDF: `,r.error]}),!r.error&&r.pages===0&&(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering PDF…`}),(0,Y.jsx)(`div`,{ref:n,className:`space-y-2`}),r.truncated&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,as,` pages. Download the file for the full document.`]})]})}function cs({blob:e,blobUrl:t,filename:n,className:r=``}){let i=(0,q.useMemo)(()=>e&&e.type!==`application/pdf`?URL.createObjectURL(e.slice(0,e.size,`application/pdf`)):null,[e]);return(0,q.useEffect)(()=>()=>{i&&URL.revokeObjectURL(i)},[i]),is()||!e?(0,Y.jsx)(`div`,{className:`min-h-[300px] ${r}`,children:(0,Y.jsx)(`iframe`,{src:i??t,className:`h-full min-h-[300px] w-full rounded border`,title:n})}):(0,Y.jsx)(`div`,{className:`max-h-viewport-pane overflow-y-auto ${r}`,children:(0,Y.jsx)(ss,{blob:e,filename:n})})}function ls(e,t,n=256,{enabled:r=!0,blobFallback:i=!0,version:a=null}={}){let{isPublic:o,fetchBlob:s,fetchThumbnail:c}=Yn(e),l=`${o?`pub`:`ws`}:${e}:${t}:${n}:${r}:${a??``}`,[u,d]=(0,q.useState)({blobUrl:null,error:null,loading:r}),[f,p]=(0,q.useState)(l);return l!==f&&(p(l),d({blobUrl:null,error:null,loading:r})),(0,q.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 us({workspaceId:e,document:t}){let{download:n}=Yn(e),[r,i]=(0,q.useState)(!1),a=Pt(t)||`document-${t.id}`;return(0,Y.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,Y.jsx)(Me,{className:`h-3.5 w-3.5`}),r?`Preparing…`:`Download`]})}var ds=1600;function fs({error:e,loading:t,children:n}){return e?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:e}):t?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading preview...`}):(0,Y.jsx)(Y.Fragment,{children:n})}function ps({workspaceId:e,document:t,className:n=``}){let r=(0,q.useContext)(rs),i=qo(),a=Yo(`(pointer: coarse)`),{blobUrl:o,error:s,loading:c}=ls(e,t.id,ds,{version:t.checksumArray?.[0]??null}),{fetchBlob:l}=Yn(e),u=Pt(t)||`document-${t.id}`,[d,f]=(0,q.useState)(!1);return(0,Y.jsx)(fs,{error:s,loading:c,children:o&&(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[i||a?(0,Y.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Y.jsx)(ns,{src:o,alt:u,className:`max-h-full max-w-full object-contain`})}):(0,Y.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,Y.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,Y.jsx)(Me,{className:`h-3.5 w-3.5`}),d?`Preparing…`:`Download original`]})]})})}function ms({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Bn(e,t.id);return(0,Y.jsx)(fs,{error:i,loading:a,children:r&&(0,Y.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Y.jsx)(`audio`,{src:r,controls:!0,preload:`metadata`,className:`w-full`}),(0,Y.jsx)(us,{workspaceId:e,document:t})]})})}function hs({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Bn(e,t.id),[o,s]=(0,q.useState)(!1);return(0,Y.jsx)(fs,{error:i,loading:a,children:r&&(0,Y.jsxs)(`div`,{className:`space-y-2 ${n}`,children:[(0,Y.jsx)(`video`,{src:r,controls:!0,playsInline:!0,preload:`metadata`,onError:()=>s(!0),className:`max-h-viewport-pane w-full rounded border`}),o&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This video can’t be played inline in your browser. Download it to view.`}),(0,Y.jsx)(us,{workspaceId:e,document:t})]})})}function gs({workspaceId:e,document:t,className:n=``}){let{blobUrl:r,blob:i,error:a,loading:o}=Hn(e,t.id,{typeHint:`application/pdf`}),s=Pt(t)||`document-${t.id}`;return(0,Y.jsx)(fs,{error:a,loading:o,children:r&&(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${n}`,children:[(0,Y.jsx)(cs,{blob:i,blobUrl:r,filename:s,className:`min-h-0 flex-1`}),(0,Y.jsx)(`div`,{children:(0,Y.jsx)(us,{workspaceId:e,document:t})})]})})}var _s=(0,q.lazy)(()=>s(()=>import(`./markdown-html-XoABNf32.js`),__vite__mapDeps([2,3,4,5,6,7,8])));function vs({content:e,className:t=``,preview:n=!1}){return(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`div`,{className:`whitespace-pre-wrap break-words ${t}`,children:e}),children:(0,Y.jsx)(_s,{content:e,className:t,preview:n})})}function ys({workspaceId:e,document:t,className:n=``}){let{text:r,error:i,loading:a}=Hn(e,t.id,{mode:`text`,version:t.checksumArray?.[0]});return i?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):a||r==null?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Y.jsx)(`pre`,{className:`bg-muted p-3 rounded text-xs overflow-auto max-h-viewport-pane whitespace-pre-wrap ${n}`,children:r})}function bs({workspaceId:e,document:t,className:n=``}){let r=t.schema===Yt,{text:i,error:a,loading:o}=Hn(e,t.id,{mode:`text`,enabled:!r,version:t.checksumArray?.[0]});return r?(0,Y.jsxs)(`div`,{className:`markdown-note space-y-3 ${n}`,children:[t.data?.title?(0,Y.jsx)(`h3`,{className:`text-lg font-semibold`,children:String(t.data.title)}):null,(0,Y.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent`,children:(0,Y.jsx)(vs,{content:String(t.data?.content??``),className:`markdown-doc px-4 py-3`})})]}):a?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:a}):o||i==null?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading...`}):(0,Y.jsx)(`div`,{className:`markdown-document-frame rounded-md border border-input bg-transparent overflow-auto max-h-viewport-pane ${n}`,children:(0,Y.jsx)(vs,{content:i,className:`markdown-doc px-4 py-3`})})}function xs({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),r=Lt(n);return r?(0,Y.jsx)(`div`,{className:`aspect-video w-full ${t}`,children:(0,Y.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 Ss({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),[r,i]=(0,q.useState)({blobUrl:null,blob:null,failed:!1,loading:!0}),[a,o]=(0,q.useState)(n);n!==a&&(o(n),i({blobUrl:null,blob:null,failed:!1,loading:!0})),(0,q.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(`${bt}/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,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-2 ${t}`,children:[(0,Y.jsxs)(`div`,{className:`flex shrink-0 flex-wrap items-center gap-3`,children:[(0,Y.jsxs)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`inline-flex items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Y.jsx)(Ae,{className:`h-3 w-3`}),` `,n]}),c&&(0,Y.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,Y.jsx)(Me,{className:`h-3.5 w-3.5`}),` Download`]})]}),u&&(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading PDF…`}),l&&(0,Y.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,Y.jsx)(cs,{blob:c,blobUrl:s,filename:d,className:`min-h-[300px] flex-1`})]})}function Cs(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 ws(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function Ts({document:e,className:t=``}){let n=e.data||{},r=String(n.url??n.uri??``),i=String(n.title??n.label??``)||ws(r),a=typeof n.favIconUrl==`string`?n.favIconUrl:``,o=n.pinned===!0,s=typeof n.timestamp==`string`?n.timestamp:null,[c,l]=(0,q.useState)(!1);return(0,Y.jsxs)(`div`,{className:`space-y-3 ${t}`,children:[(0,Y.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,Y.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,Y.jsx)(`img`,{src:a,alt:``,className:`h-5 w-5`,onError:()=>l(!0)}):(0,Y.jsx)(se,{className:`h-4 w-4 text-muted-foreground`})}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Y.jsx)(`span`,{className:`truncate font-medium leading-tight`,children:i}),o&&(0,Y.jsx)(M,{className:`h-3 w-3 shrink-0 fill-warning text-warning`})]}),(0,Y.jsx)(`div`,{className:`mt-0.5 truncate text-xs text-muted-foreground`,children:ws(r)}),(0,Y.jsx)(`div`,{className:`mt-1 truncate font-mono text-[11px] text-muted-foreground/70`,children:r})]}),(0,Y.jsx)(Ae,{className:`mt-1 h-4 w-4 shrink-0 text-muted-foreground reveal-on-hover`})]}),s&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Saved `,new Date(s).toLocaleString()]})]})}var Es={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4};function Ds(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 Os(){return new Promise((e,t)=>navigator.geolocation.getCurrentPosition(e,t,Es))}function ks(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 As(){let e=typeof navigator<`u`&&`geolocation`in navigator&&typeof window<`u`&&window.isSecureContext,[t,n]=(0,q.useState)(e?`prompt`:`unsupported`),[r,i]=(0,q.useState)(!1),[a,o]=(0,q.useState)(!1),[s,c]=(0,q.useState)(null),[l,u]=(0,q.useState)(null),[d,f]=(0,q.useState)(null),[p,m]=(0,q.useState)(null),h=(0,q.useRef)(!1),g=(0,q.useRef)(null),_=(0,q.useRef)(null);(0,q.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,q.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,q.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),Os().then(e=>{let t=Ds(e);g.current=t,u(t),n(`granted`)}).catch(e=>{c(ks(e)),e?.code===1&&(n(`denied`),h.current=!1,i(!1))}).finally(()=>o(!1)))},[e]),manual:d,manualLabel:p,setManual:v,capture:(0,q.useCallback)(async()=>{if(_.current)return _.current;if(!h.current||!e)return null;try{return Ds(await Os())}catch{return g.current}},[e])}}var js=`2.1`,Ms=[`pending`,`in-progress`,`completed`,`cancelled`],Ns={pending:`Pending`,"in-progress":`In progress`,completed:`Completed`,cancelled:`Cancelled`};function Ps(e){return String(e).padStart(2,`0`)}function Fs(e){return`${e.getFullYear()}-${Ps(e.getMonth()+1)}-${Ps(e.getDate())}T${Ps(e.getHours())}:${Ps(e.getMinutes())}`}function Is(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:Fs(t)}function Ls(e){if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function Rs(){let e=new Date;return e.setHours(23,59,0,0),Fs(e)}function zs(e){let t=Ls(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 Bs(){let[e,t]=(0,q.useState)(``),[n,r]=(0,q.useState)(``),[i,a]=(0,q.useState)(`pending`),[o,s]=(0,q.useState)(``),[c,l]=(0,q.useState)(Rs()),[u,d]=(0,q.useState)([]),[f,p]=(0,q.useState)(``),[m,h]=(0,q.useState)(!1),g=As(),_=e.trim().length>0&&!m;async function v(t){h(!0);try{let r=await g.capture(),a=f.trim(),s={schema:Mt,schemaVersion:js,data:zs({title:e,description:n,status:i,priority:o,due:c}),...a?{comment:a}:{},metadata:{features:Gn(u),...r?{geo:r}:{}}};return await ar(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 Vs(e){return e.data||{}}var Hs={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 Us(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 Ws(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 Gs(e,t,n){let r=n===`completed`,i={...t.data||{},status:n,completed:r};r?i.completedAt=new Date().toISOString():delete i.completedAt,await Mn(e,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:i}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}function Ks({document:e,workspaceId:t,className:n=``}){let r=Vs(e),i=Xn()!=null,[a,o]=(0,q.useState)(!1),{replicating:s,label:c}=Ht(e),l=r.status===`completed`,u=r.status??`pending`,d=Us(r);return(0,Y.jsx)(`div`,{className:`space-y-3 ${n}`,children:(0,Y.jsxs)(`div`,{className:`relative flex items-start gap-3 rounded-lg border bg-card p-3 transition-opacity ${s?`opacity-60`:``}`,children:[(0,Y.jsx)(`button`,{type:`button`,onClick:async()=>{if(!(i||a)){o(!0);try{await Gs(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,Y.jsx)(lt,{className:`h-3 w-3 animate-spin`}):l&&(0,Y.jsx)(b,{className:`h-3.5 w-3.5`})}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,Y.jsx)(`div`,{className:`font-medium leading-tight ${l?`text-muted-foreground line-through`:``}`,children:r.title||`Todo ${e.id}`}),(0,Y.jsxs)(`div`,{className:`mt-1.5 flex flex-wrap items-center gap-2 text-xs`,children:[(0,Y.jsx)(`span`,{className:`rounded-full px-2 py-0.5 ${Hs[u]}`,children:Ns[u]}),r.dueDate&&(0,Y.jsxs)(`span`,{className:`inline-flex items-center gap-1 ${d?`font-medium text-destructive`:`text-muted-foreground`}`,children:[(0,Y.jsx)(T,{className:`h-3 w-3`}),Ws(r.dueDate),d?` · overdue`:``]}),typeof r.priority==`number`&&(0,Y.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-muted-foreground`,children:[(0,Y.jsx)(Oe,{className:`h-3 w-3`}),`P`,r.priority]})]}),r.description&&(0,Y.jsx)(vs,{content:String(r.description),className:`mt-2 text-sm text-muted-foreground`}),s&&(0,Y.jsxs)(`div`,{className:`mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground`,role:`status`,children:[(0,Y.jsx)(lt,{className:`h-3 w-3 animate-spin`}),c]})]})]})})}function qs(e,t){let{fetchBlob:n}=Yn(e),r=Xn(),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,q.useState)(null);return(0,q.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 Js(e){return e?typeof e==`string`?e:e.name&&e.address?`${e.name} <${e.address}>`:e.address||e.name||``:``}function Ys(e){return e?(Array.isArray(e)?e:[e]).map(e=>Js(e)).filter(Boolean).join(`, `):``}function Xs(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 Zs(e,t,n){let r=0;cr.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=cr.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{cr.removeHook(`afterSanitizeAttributes`)}}function Qs(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 $s(e){return(0,Y.jsx)(ec,{...e},`${e.workspaceId}:${e.document.id}`)}function ec({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=Yn(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],{body:s,bodyHtml:c,loading:l,error:u}=qs(e,t),[d,f]=(0,q.useState)(null),[p,m]=(0,q.useState)(!1),[h,g]=(0,q.useState)(!1),[_,v]=(0,q.useState)(0),[y,b]=(0,q.useState)(null);(0,q.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 Qs(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}=Zs(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,Y.jsxs)(`div`,{className:`flex h-full min-h-0 min-w-0 flex-col gap-3 ${n}`,children:[(0,Y.jsx)(`div`,{className:`shrink-0 rounded-md border bg-muted/30 p-2 text-sm sm:p-3`,children:(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2 sm:gap-3`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 basis-64 space-y-1`,children:[(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:String(a.subject??`(no subject)`)}),(0,Y.jsxs)(`details`,{className:`sm:hidden`,children:[(0,Y.jsxs)(`summary`,{className:`cursor-pointer text-xs`,children:[(0,Y.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,Y.jsx)(`span`,{className:`ml-2 text-muted-foreground`,children:`Details`})]}),(0,Y.jsxs)(`div`,{className:`mt-2 space-y-1 break-words text-xs`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Js(a.from)]}),Ys(a.to)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Ys(a.to)]}),Ys(a.cc)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Ys(a.cc)]}),x&&(0,Y.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:x})]})]}),(0,Y.jsxs)(`div`,{className:`hidden space-y-1 break-words sm:block`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`From:`}),` `,Js(a.from)]}),Ys(a.to)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Ys(a.to)]}),Ys(a.cc)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Ys(a.cc)]}),x&&(0,Y.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:x})]})]}),c&&(0,Y.jsxs)(`div`,{className:`flex max-w-full flex-wrap gap-2`,children:[(0,Y.jsxs)(K,{size:`sm`,variant:`outline`,onClick:()=>m(!p),children:[p?(0,Y.jsx)(re,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Y.jsx)(Ie,{className:`mr-1.5 h-3.5 w-3.5`}),p?`HTML`:`Plain text`]}),!p&&_>0&&(0,Y.jsxs)(K,{size:`sm`,variant:h?`secondary`:`outline`,onClick:()=>g(!h),title:`Remote images can reveal your IP/read status to the sender`,children:[h?(0,Y.jsx)(Le,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Y.jsx)(ze,{className:`mr-1.5 h-3.5 w-3.5`}),h?`Hide remote images`:`Show remote images (${_})`]})]})]})}),(y||u)&&(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:y||u}),l?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading message…`}):u?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:String(a.bodyPreview||`Message content could not be loaded.`)}):!p&&c?d?(0,Y.jsx)(`iframe`,{src:d,sandbox:``,title:String(a.subject??`email`),className:`min-h-[12rem] w-full flex-1 rounded border bg-white`}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Rendering...`}):(0,Y.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,Y.jsxs)(`div`,{className:`shrink-0 space-y-1`,children:[(0,Y.jsxs)(`div`,{className:`text-xs font-medium text-muted-foreground`,children:[`Attachments (`,S.length,`)`]}),S.map((e,t)=>(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-sm`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(Ie,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`truncate`,children:e.filename||`attachment`}),(0,Y.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:Xs(e.size)})]}),e.url&&(0,Y.jsxs)(`button`,{onClick:()=>C(e),className:`inline-flex shrink-0 items-center gap-1 text-xs text-primary hover:underline`,children:[(0,Y.jsx)(Me,{className:`h-3 w-3`}),` Download`]})]},e.url||t))]})]})}function tc({attachment:e,workspaceId:t,document:n}){let{download:r}=Yn(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}=Hn(t,n.id,{url:e.url,typeHint:i,enabled:!o&&!!e.url}),{src:u,error:d,loading:f}=Bn(t,n.id,{url:e.url,enabled:o&&!!e.url}),[p,m]=(0,q.useState)(!1),[h,g]=(0,q.useState)(``),_=o?d:c;return(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border p-2`,children:[_&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:_}),(o?f:l)&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading attachment…`}),!o&&s&&i.startsWith(`image/`)&&(0,Y.jsx)(`img`,{src:s,alt:a,className:`max-h-96 max-w-full rounded object-contain`}),o&&u&&(i.startsWith(`video/`)?(0,Y.jsx)(`video`,{controls:!0,playsInline:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`max-h-96 w-full rounded`},u):(0,Y.jsx)(`audio`,{controls:!0,preload:`metadata`,src:u,onError:()=>m(!0),className:`w-full`},u)),p&&(0,Y.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,Y.jsx)(`p`,{role:`alert`,className:`text-xs text-destructive`,children:h}),e.url&&(0,Y.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 nc(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,Y.jsxs)(`article`,{className:`space-y-4 p-3 ${e.className||``}`,children:[(0,Y.jsxs)(`header`,{className:`space-y-1 border-b pb-3`,children:[(0,Y.jsx)(`p`,{className:`font-medium`,children:n?.name||n?.displayName||n?.username||n?.id||`Unknown sender`}),(0,Y.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,Y.jsx)(`p`,{className:`whitespace-pre-wrap break-words text-sm`,children:String(t.text||`(No text)`)}),!!t.mediaError&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:String(t.mediaError)}),i.map((t,n)=>(0,Y.jsx)(tc,{...e,attachment:t},t.url||n))]})}var rc={email:B,phone:S,sms:be,chat:be,slack:be,matrix:be,web:se,url:se},ic={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},ac=e=>Array.isArray(e)?e:[];function oc(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 sc({title:e,count:t,children:n}){return t===0?null:(0,Y.jsxs)(`div`,{className:`space-y-1`,children:[(0,Y.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:e}),(0,Y.jsx)(`div`,{className:`space-y-1`,children:n})]})}function cc({icon:e,primary:t,children:n,title:r}){return(0,Y.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,Y.jsx)(e,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`div`,{className:`min-w-0 flex-1 truncate`,children:n}),t&&(0,Y.jsx)(Je,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function lc({document:e,className:t}){let n=e.data??{},r=ac(n.identifiers),i=ac(n.channels),a=ac(n.organizations),o=ac(n.links),s=ac(n.tags),c=String(n.displayName||``).trim(),l=Tn(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,Y.jsxs)(`div`,{className:U(`space-y-4`,t),children:[(0,Y.jsxs)(`div`,{className:`space-y-1`,children:[(0,Y.jsx)(`h2`,{className:`text-lg font-semibold`,children:c||`Identity ${e.id}`}),(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[l&&(0,Y.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5`,children:ic[l]||l}),f&&f!==c&&(0,Y.jsx)(`span`,{children:f}),String(n.timezone||``)&&(0,Y.jsx)(`span`,{children:String(n.timezone)}),String(n.locale||``)&&(0,Y.jsx)(`span`,{children:String(n.locale)})]})]}),u&&!p&&(0,Y.jsx)(sc,{title:`Primary email`,count:1,children:(0,Y.jsx)(cc,{icon:B,primary:!0,children:(0,Y.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,Y.jsx)(sc,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=oc(n,r),a=rc[n]||be;return(0,Y.jsxs)(cc,{icon:a,primary:e.primary,title:e.platform||n,children:[i?(0,Y.jsx)(`a`,{href:i,className:`hover:underline`,target:i.startsWith(`http`)?`_blank`:void 0,rel:`noopener noreferrer`,children:r}):r,e.label&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.label})]},`${n}:${r}:${t}`)})}),(0,Y.jsx)(sc,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,Y.jsxs)(cc,{icon:ot,primary:e.primary,children:[(0,Y.jsx)(`span`,{className:`font-mono text-xs`,children:e.identifier}),(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.type,e.provider].filter(Boolean).join(` · `)})]},`${e.type}:${e.identifier}:${t}`))}),(0,Y.jsx)(sc,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,Y.jsxs)(cc,{icon:$e,children:[e.name,e.role&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.role})]},`${e.name}:${t}`))}),(0,Y.jsx)(sc,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,Y.jsxs)(cc,{icon:Ue,children:[(0,Y.jsx)(`span`,{className:`font-mono text-xs`,children:e.target}),e.type&&(0,Y.jsx)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:e.type})]},`${e.type}:${e.target}:${t}`))}),s.length>0&&(0,Y.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>(0,Y.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:e},e))})]})}function uc({document:e}){let t=String(e.metadata?.contentType||`application/octet-stream`);return(0,Y.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No inline preview available for `,(0,Y.jsx)(`span`,{className:`font-mono`,children:t}),`. Use Download.`]})}function dc(e){let t=e.schema;if(t===`data/schema/note`)return bs;if(t===`data/schema/drawing`)return ps;if(t===`data/schema/task`)return Ks;if(t===`data/schema/message/email`)return $s;if(t===`data/schema/message`)return nc;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return lc;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return Lt(t)?xs:Cs(t)?Ss:Ts}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(Bt(n,Pt(e))){case`image`:return ps;case`audio`:return ms;case`video`:return hs;case`pdf`:return gs;case`markdown`:return bs;case`text`:return ys;default:return uc}}function fc(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 pc=[];function mc(e){if(e.key!==`Escape`||e.isComposing||e.defaultPrevented)return;let t=pc[pc.length-1];t&&(e.preventDefault(),t())}function hc(e,t=!0){let n=(0,q.useRef)(e);(0,q.useEffect)(()=>{n.current=e});let r=t&&!!e;(0,q.useEffect)(()=>{if(!r)return;let e=()=>n.current?.();return pc.push(e),pc.length===1&&window.addEventListener(`keydown`,mc),()=>{let t=pc.indexOf(e);t>=0&&pc.splice(t,1),pc.length===0&&window.removeEventListener(`keydown`,mc)}},[r])}function gc({x:e,y:t,onClose:n,className:r,children:i}){let a=(0,q.useRef)(null),[o,s]=(0,q.useState)({x:e,y:t});return hc(n),(0,q.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,fo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`fixed inset-0 z-menu-scrim`,onClick:n,onContextMenu:e=>{e.preventDefault(),n()}}),(0,Y.jsx)(`div`,{ref:a,style:{left:o.x,top:o.y},className:U(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r,`bg-popover text-popover-foreground`),children:i})]}),document.body)}var _c=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),vc={Delete:`Del`,Backspace:`⌫`,Enter:`↵`,ArrowUp:`↑`,ArrowDown:`↓`};function yc(e){let t=e.split(`+`),n=t.pop()||``,r=vc[n]||(n.length===1?n.toUpperCase():n);if(_c){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 bc(e,t){let n=t.split(`+`),r=n.pop()||``;return(_c?e.metaKey:e.ctrlKey)!==n.includes(`Mod`)||e.shiftKey!==n.includes(`Shift`)||e.altKey!==n.includes(`Alt`)||_c&&e.ctrlKey!==n.includes(`Ctrl`)?!1:r.length===1?e.key.toLowerCase()===r.toLowerCase():e.key===r}function xc(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 Sc(e,t){if(e.defaultPrevented||e.nativeEvent.isComposing||xc(e.target))return!1;let n=t.find(t=>t.shortcut&&!t.disabled&&bc(e,t.shortcut));return n?(e.preventDefault(),e.stopPropagation(),n.run({shiftKey:e.shiftKey}),!0):!1}function Cc(e){return e.key===`ContextMenu`||e.key===`F10`&&e.shiftKey}function wc(){return typeof window<`u`&&window.matchMedia(`(max-width: 767px)`).matches}function Tc(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 Ec(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 Dc(e,t,n){t(),setTimeout(()=>{e.run({shiftKey:n})},0)}function Oc({anchor:e,items:t,onClose:n,label:r}){let i=(0,q.useRef)(null);return(0,q.useEffect)(()=>{let e=document.activeElement;return i.current?.querySelector(`[role="menuitem"]:not([aria-disabled="true"])`)?.focus(),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[]),(0,Y.jsx)(gc,{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,Y.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:Ec(t).map((e,t)=>(0,Y.jsxs)(q.Fragment,{children:[t>0&&(0,Y.jsx)(`div`,{role:`separator`,className:`my-1 h-px bg-border`}),e[0].groupLabel&&(0,Y.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,Y.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,"aria-disabled":e.disabled||void 0,title:e.hint,onClick:t=>{e.disabled||Dc(e,n,t.shiftKey)},className:U(`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,Y.jsx)(t,{className:`h-3.5 w-3.5 shrink-0`}):(0,Y.jsx)(`span`,{className:`w-3.5 shrink-0`}),(0,Y.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.shortcut&&(0,Y.jsx)(`kbd`,{className:`ml-4 shrink-0 font-sans text-[11px] text-muted-foreground`,children:yc(e.shortcut)})]},e.id)})]},`${e[0].group??``}:${t}`))})})}function kc({items:e,onClose:t,header:n}){hc(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,fo.createPortal)((0,Y.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,Y.jsxs)(`div`,{className:`flex shrink-0 items-start gap-3 border-b p-4`,onClick:e=>e.stopPropagation(),children:[(0,Y.jsx)(`div`,{className:`min-w-0 flex-1`,children:n}),(0,Y.jsx)(`button`,{type:`button`,onClick:t,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,"aria-label":`Close`,children:(0,Y.jsx)(E,{className:`h-5 w-5`})})]}),(0,Y.jsx)(`div`,{className:`min-h-4 flex-1`}),(0,Y.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:[Ec(e).map((e,n)=>(0,Y.jsxs)(`div`,{className:U(`space-y-2`,n>0&&`pt-2`),children:[e[0].groupLabel&&(0,Y.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,Y.jsxs)(`button`,{type:`button`,disabled:e.disabled,onClick:n=>Dc(e,t,n.shiftKey),className:U(r,e.destructive&&`border-destructive/30 text-destructive`,e.disabled&&`opacity-50`),children:[n&&(0,Y.jsx)(n,{className:U(`h-5 w-5 shrink-0`,!e.destructive&&`text-muted-foreground`)}),e.label]},e.id)})]},`${e[0].group??``}:${n}`)),(0,Y.jsx)(`button`,{type:`button`,onClick:t,className:`${r} justify-center bg-muted`,children:`Cancel`})]})]}),window.document.body)}function Ac({anchor:e,items:t,onClose:n,label:r,header:i}){return t.length===0?null:wc()?(0,Y.jsx)(kc,{items:t,onClose:n,header:i??(r&&(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:r}))}):(0,Y.jsx)(Oc,{anchor:e,items:t,onClose:n,label:r})}var jc=null;function Mc(){return jc||=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(()=>(jc=null,[])),jc}async function Nc(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 Pc=`ph:folder-fill`,Fc=`ph:squares-four-fill`,Ic=`ph:stack-fill`,Lc=[`#ef4444`,`#f97316`,`#f59e0b`,`#eab308`,`#84cc16`,`#22c55e`,`#14b8a6`,`#06b6d4`,`#3b82f6`,`#6366f1`,`#8b5cf6`,`#a855f7`,`#ec4899`,`#f43f5e`,`#64748b`,`#78716c`],Rc={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`}},zc={"workspace:home":{icon:`ph:house-fill`,color:`#3b82f6`},"workspace:data":{icon:`ph:database-fill`,color:`#14b8a6`}},Bc={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`}},Vc={icon:`ph:hard-drive-fill`,color:`#64748b`};function Hc(e){let t=e.config?.ui??{},n=e.address&&zc[e.address]||e.driver&&Bc[e.driver]||Vc;return{icon:typeof t.icon==`string`?t.icon:n.icon??Vc.icon,color:typeof t.color==`string`?t.color:n.color??Vc.color}}function Uc(e){let t=e.metadata?.ui??{},n=Rc[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 Wc(e){let t=Rc[(e.split(`/`).filter(Boolean).pop()??``).trim().toLowerCase()];return t?{metadata:Gc(void 0,t)}:null}function Gc(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 Kc=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,qc=()=>({h:Kc(0,360),s:Kc(42,98),l:Kc(40,90)}),Jc=(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)}`},Yc=()=>{let{h:e,s:t,l:n}=qc();return Jc(e,t,n)},Xc=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)},Zc=(e,t=.82)=>{let n=Xc(e);return n===null||n>t},Qc=e=>e&&!Zc(e)?e:void 0,$c=e=>{if(!e)return`text-muted-foreground/70`;let t=Xc(e);return t!==null&&t>.5?`text-black/45`:`text-white/80`},el=e=>{let t=Xc(e);return t!==null&&(t+.05)/.05>=1.05/(t+.05)?`text-black`:`text-white`},tl=[{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 X(e,t){return{Icon:e,...tl[t-1]}}var nl={tab:X(se,7),link:X(se,7),email:X(B,3),note:X(st,3),task:X(Ce,5),message:X(be,6),identity:X(ae,2),contact:X(ae,2),device:X(et,10),application:X(R,11),dotfile:X(Fe,4),document:X(Ie,9)},rl=[{test:/^image\//,spec:X(ze,5)},{test:/^video\//,spec:X(qe,11)},{test:/^audio\//,spec:X(fe,10)},{test:/pdf$/,spec:X(Ie,1)},{test:/zip|tar|gzip|7z|rar|compressed/,spec:X(He,12)},{test:/json|javascript|typescript|xml|html|css|x-sh|python/,spec:X(Ee,6)},{test:/^text\//,spec:X(Ie,12)}],il=X(nt,6),al=X(nt,9);function ol(e){let t=(e.schema||``).split(`/`).pop()||``;if(t===`file`){let t=String(e.metadata?.contentType||``).toLowerCase();return rl.find(({test:e})=>e.test(t))?.spec||il}return nl[t]||al}var sl={3.5:`h-3.5 w-3.5`,4:`h-4 w-4`,5:`h-5 w-5`,10:`h-10 w-10`};function cl(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 ll({document:e,size:t=4,chip:n=!1,className:r}){let i=ol(e),a=e.schema===`data/schema/tab`?cl(e.data):[],[o,s]=(0,q.useState)(0),c=a[o]??null,l=c?(0,Y.jsx)(`img`,{src:c,alt:``,loading:`lazy`,onError:()=>s(e=>e+1),className:U(sl[t],`rounded-xs object-contain`,!n&&`shrink-0`,!n&&r)}):(0,Y.jsx)(i.Icon,{className:U(sl[t],i.color,!n&&`shrink-0`,!n&&r)});return n?(0,Y.jsx)(`span`,{className:U(`inline-flex shrink-0 items-center justify-center rounded-md`,t>=10?`p-3`:`p-1`,i.chip,r),children:l}):l}function ul({items:e,onNavigate:t,disabled:n,className:r,label:i=`Tree path`}){let a=(0,q.useRef)(null),o=e[e.length-1]?.path;return(0,q.useEffect)(()=>{let e=a.current;e&&(e.scrollLeft=e.scrollWidth)},[o]),(0,Y.jsx)(`nav`,{"aria-label":i,className:U(`min-w-0 flex-1`,r),children:(0,Y.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=U(`block max-w-56 truncate rounded px-1.5 py-1`,a?`font-medium text-foreground`:`text-muted-foreground`);return(0,Y.jsxs)(`li`,{className:`flex shrink-0 items-center gap-1`,children:[i>0&&(0,Y.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted-foreground/60`,children:`/`}),t&&!a?(0,Y.jsx)(`button`,{type:`button`,title:r.path===`/`?`${r.label} (root)`:r.path,disabled:n,onClick:()=>t(r.path),className:U(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,Y.jsx)(`span`,{title:r.path===`/`?r.label:r.path,"aria-current":a?`location`:void 0,className:o,children:r.label})]},r.path)})})})}function dl(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 fl={context:(0,Y.jsx)(y,{className:`h-3.5 w-3.5`}),directory:(0,Y.jsx)(g,{className:`h-3.5 w-3.5`}),backends:(0,Y.jsx)(F,{className:`h-3.5 w-3.5`}),relations:(0,Y.jsx)(Ze,{className:`h-3.5 w-3.5`})},pl={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function ml(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function hl(e,t){let n=(0,q.useRef)(null),r=(0,q.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 gl(e,t,n){let r=ml(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>gl(e,r,n))??!1}var _l=200;function vl({onConfirm:e,onCancel:t,busy:n}){let[r,i]=(0,q.useState)(``);return(0,Y.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,Y.jsx)(te,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.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,Y.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:`Creating…`})]})}function yl({node:e,parentPath:t,query:n,selected:r,onToggle:a,onActivate:o,onRowMenu:s,createParent:c,onCreateConfirm:l,onCreateCancel:u,creating:d}){let f=ml(t,e.name),p=!!e.children?.length,[m,h]=(0,q.useState)(!1),{handlers:g,guardClick:_}=hl(f,s);if(n&&!gl(e,t,n))return null;let v=c===f,y=m||n.length>0||v,b=r.has(f),x=e.type===`canvas`,S=Uc(e);return(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`div`,{className:U(`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,Y.jsx)(`button`,{type:`button`,"aria-label":`${y?`Collapse`:`Expand`} ${e.label||e.name}`,"aria-expanded":p?y:void 0,disabled:!p,className:U(`shrink-0 text-muted-foreground hover:text-foreground`,!p&&`invisible`),onClick:e=>{e.stopPropagation(),e.detail<=1&&h(e=>!e)},children:y?(0,Y.jsx)(ce,{className:`w-4 h-4`}):(0,Y.jsx)(_t,{className:`w-4 h-4`})}),(0,Y.jsx)(i,{icon:S.icon||(x?`ph:squares-four-fill`:`ph:folder-fill`),width:16,height:16,color:Qc(S.color),className:U(`shrink-0`,!Qc(S.color)&&(x?`text-primary`:`text-muted-foreground`))}),(0,Y.jsx)(`span`,{className:`flex-1 truncate font-medium`,title:e.description||void 0,children:e.label||e.name})]}),y&&p||v?(0,Y.jsxs)(`div`,{className:`ml-[22px] mt-1.5 space-y-1.5`,children:[v&&l&&u&&(0,Y.jsx)(vl,{busy:d,onConfirm:e=>{h(!0),l(f,e)},onCancel:u}),y&&e.children?.map(e=>(0,Y.jsx)(yl,{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 bl({workspaces:e,loading:t,onPick:n}){return t&&e.length===0?(0,Y.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):e.length===0?(0,Y.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`No workspaces found`}):(0,Y.jsx)(`div`,{className:`space-y-1.5`,children:e.map(e=>{let t=Qc(e.color);return(0,Y.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,Y.jsx)(i,{icon:e.icon||`ph:stack-fill`,width:18,height:18,color:t,className:U(`shrink-0`,!t&&`text-muted-foreground`)}),(0,Y.jsx)(`span`,{className:`flex-1 truncate text-sm font-medium`,children:e.label||e.name}),(0,Y.jsx)(_t,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function xl({workspaceName:e,treeTab:t,onTreeTabChange:n,selectedDocIds:r,onToggleDoc:i,onNavigate:a,excludeDocumentIds:o}){let[s,c]=(0,q.useState)(`folder`),[l,u]=(0,q.useState)(``),d=l.trim().toLowerCase(),[f,p]=(0,q.useState)(`/`),[m,h]=(0,q.useState)(null),[g,_]=(0,q.useState)(!1),[v,y]=(0,q.useState)([]),[b,x]=(0,q.useState)(!1),[S,C]=(0,q.useState)(``),[w,T]=(0,q.useState)(``),[D,O]=(0,q.useState)(t),k=n?t:D,A=e=>{p(`/`),c(`folder`),C(``),T(``),a?.(`/`),n?n(e):O(e)},[j,ee]=(0,q.useState)(k);k!==j&&(ee(k),p(`/`),c(`folder`)),(0,q.useEffect)(()=>{let e=setTimeout(()=>T(S.trim()),300);return()=>clearTimeout(e)},[S]),(0,q.useEffect)(()=>{let t=!1;async function n(){_(!0);try{let n=await zt(e,k);t||h(n)}catch{t||h(null)}finally{t||_(!1)}}return n(),()=>{t=!0}},[e,k]),(0,q.useEffect)(()=>{if(s!==`documents`)return;let t=!1,n=k===`directory`?`directory`:On,r=k===`context`?`context`:`directory`;async function i(){x(!0);try{let i=w?await hn(e,f,[],{treeName:n,treeType:r,q:w,limit:_l}):await wn(e,f,n,{limit:_l});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,Y.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Y.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[!n&&(0,Y.jsx)(`div`,{className:`flex items-center gap-1 rounded-md border border-input p-0.5`,children:[`context`,`directory`].map(e=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>A(e),className:U(`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 ${pl[e].toLowerCase()}`,children:[fl[e],(0,Y.jsx)(`span`,{className:`font-mono`,children:e===`directory`?`dir://`:`ctx://`})]},e))}),(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Step 1 of 2 · Pick a folder`}),(0,Y.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,Y.jsx)(_t,{className:`h-3.5 w-3.5`})]})]}),(0,Y.jsx)(ul,{items:dl(f,e),onNavigate:M,label:`Folder path`}),(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(pt,{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,Y.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,Y.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:g?(0,Y.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:U(`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,Y.jsx)(ce,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Y.jsx)(`div`,{className:`ml-[22px] space-y-1.5`,children:m?.children?.length?m.children.map(e=>(0,Y.jsx)(yl,{node:e,parentPath:`/`,query:d,selected:new Set([f]),onToggle:M,onActivate:e=>{M(e),c(`documents`)}},e.id||e.name)):(0,Y.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})})]})})]}):(0,Y.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Y.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-muted/30 px-3 py-2`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.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,Y.jsx)(_t,{className:`h-3.5 w-3.5 shrink-0 rotate-180`}),(0,Y.jsx)(`span`,{children:`Folders`})]}),(0,Y.jsx)(`span`,{className:`ml-auto shrink-0 text-xs text-muted-foreground`,children:`Step 2 of 2 · Pick a document`})]}),(0,Y.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,Y.jsxs)(`span`,{className:`shrink-0 font-mono text-xs text-muted-foreground`,children:[`[`,k,`]`]}),(0,Y.jsx)(ul,{items:dl(f,e),onNavigate:M,label:`Document folder path`})]}),(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(pt,{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,Y.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,Y.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,Y.jsx)(E,{className:`h-3.5 w-3.5`})})]})]}),(0,Y.jsx)(`div`,{className:`min-h-0 flex-1 space-y-1 overflow-y-auto p-3`,children:b?(0,Y.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading documents…`}):N.length===0?(0,Y.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,Y.jsxs)(`div`,{onClick:()=>i(e.id),className:U(`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,Y.jsx)(`input`,{type:`checkbox`,checked:n,onChange:()=>i(e.id),className:`shrink-0`,onClick:e=>e.stopPropagation()}),(0,Y.jsx)(ll,{document:e,size:3.5}),(0,Y.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function Sl({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,q.useState)(r?`tree`:`workspace`),[b,x]=(0,q.useState)([]),[S,C]=(0,q.useState)(!r),[w,T]=(0,q.useState)(r??null),D=u&&l.includes(u)?u:l.includes(`context`)||l.includes(`directory`)?`pins`:l[0]??`context`,[O,k]=(0,q.useState)(D),A=g?.length?g:[...En],[j,ee]=(0,q.useState)(A[0]??`references`),[N,P]=(0,q.useState)(`out`),[F,I]=(0,q.useState)(new Set),[L,te]=(0,q.useState)(null),[ne,re]=(0,q.useState)(`context`),[ie,ae]=(0,q.useState)(!1),oe=O===`pins`?ne:O;(0,q.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,q.useState)(null),[ue,de]=(0,q.useState)(!1),[z,fe]=(0,q.useState)(new Set),[pe,me]=(0,q.useState)(``),he=pe.trim().toLowerCase(),{showErrorToast:ge}=wt(),[ve,ye]=(0,q.useState)(null),[be,xe]=(0,q.useState)(null),[Se,B]=(0,q.useState)(!1);hc(e,!o&&!Se);let Ce=hl(`/`,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||Se||!we(e))){B(!0);try{let t=`${e===`/`?``:e}/${n}`,r=O===`context`?On:O;O===`backends`?await p.create(e,n):await mn(w,t,!0,r),dn(w,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:w,treeName:r,cacheInvalidated:!0}}));let i=await zt(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{B(!1)}}},[Ee,De]=(0,q.useState)(r);r!==Ee&&(De(r),r||C(!0)),(0,q.useEffect)(()=>{r||Kt().then(e=>x(e.filter(e=>e.id!==i&&e.name!==i))).catch(()=>x([])).finally(()=>C(!1))},[r,i]),(0,q.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 zt(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||dn(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`?On:oe,treeType:oe===`context`?`context`:`directory`})}},Pe=n??1;return o&&s?(0,Y.jsx)(`div`,{className:U(`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,Y.jsxs)(`div`,{className:U(`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,Y.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Y.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Y.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,Y.jsx)(`button`,{type:`button`,onClick:e,disabled:o||Se,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Y.jsx)(E,{className:`h-4 w-4`})})]}),(0,Y.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Y.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,Y.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Y.jsx)(bl,{workspaces:b,loading:S,onPick:Oe})}),(0,Y.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 pt-2`,children:[!r&&(0,Y.jsx)(`button`,{type:`button`,disabled:Se,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,Y.jsx)(_t,{className:`h-4 w-4 rotate-180`})}),(l.includes(`context`)||l.includes(`directory`))&&(0,Y.jsxs)(`button`,{type:`button`,disabled:Se,onClick:()=>{k(`pins`),fe(new Set),xe(null)},className:U(`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,Y.jsx)(M,{className:`h-3.5 w-3.5`}),`Pins`]}),l.map(e=>(0,Y.jsxs)(`button`,{type:`button`,disabled:Se,onClick:()=>{k(e),fe(new Set),xe(null)},className:U(`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:[fl[e],pl[e]]},e))]}),!R&&(0,Y.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(pt,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Y.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,Y.jsxs)(`div`,{className:`shrink-0 space-y-2 border-b bg-primary/[0.04] px-3 py-2`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`relation-predicate`,className:`shrink-0 text-xs text-muted-foreground`,children:`Predicate`}),(0,Y.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,Y.jsx)(`option`,{value:e,children:e},e))})]}),(0,Y.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,Y.jsx)(`button`,{type:`button`,title:n,onClick:()=>P(e),className:U(`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,Y.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,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Selected folders appear here`}),Array.from(z).map(e=>(0,Y.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,Y.jsx)(`span`,{className:`truncate`,title:e,children:e}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>Ae(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,Y.jsx)(E,{className:`h-3 w-3`})})]},e))]}),R&&(h??w)&&(0,Y.jsx)(xl,{workspaceName:h??w,treeTab:`context`,selectedDocIds:F,onToggleDoc:ke,excludeDocumentIds:_}),O===`pins`&&(0,Y.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!L&&!ie&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),ie&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!ie&&L?.length===0&&(0,Y.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,Y.jsxs)(`button`,{type:`button`,"aria-pressed":ne===t&&z.has(e.path),className:U(`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,Y.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(M,{className:`h-3.5 w-3.5`}),e.label||e.name||e.path]}),(0,Y.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t,` · `,e.path]})]},e.id)})]}),(0,Y.jsx)(`div`,{className:U(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(R||O===`pins`)&&`hidden`),children:ue?(0,Y.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading…`}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:U(`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,Y.jsx)(ce,{className:`w-4 h-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`flex-1 truncate font-medium`,children:`/`})]}),(0,Y.jsxs)(`div`,{className:`ml-[22px] space-y-1.5`,children:[be===`/`&&(0,Y.jsx)(vl,{busy:Se,onConfirm:e=>Te(`/`,e),onCancel:()=>xe(null)}),se?.children?.length?se.children.map(e=>(0,Y.jsx)(yl,{node:e,parentPath:`/`,query:he,selected:z,onToggle:Ae,onRowMenu:e=>{we(e.path)&&ye(e)},createParent:be,onCreateConfirm:Te,onCreateCancel:()=>xe(null),creating:Se},e.id||e.name)):be===`/`?null:(0,Y.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`Empty tree`})]})]})})]})]})}),v===`tree`&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Y.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,Y.jsx)(K,{size:`sm`,onClick:Me,disabled:!je||o||Se,children:o?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(_o,{className:`mr-1.5 h-3.5 w-3.5`}),R?`Relating…`:`Linking…`]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Ne,{className:`mr-1 h-3.5 w-3.5`}),R?`Relate`:f??`Link`]})})]}),ve&&(0,Y.jsx)(Oc,{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 Cl=`workspace:relations:refresh`;function wl(){window.dispatchEvent(new CustomEvent(Cl))}function Tl({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=Ii(),[y,b]=(0,q.useState)(`portrait`),[x,S]=(0,q.useState)(!1),C=g??x,w=e=>{S(e),_?.(e)},[T,D]=(0,q.useState)(!1),[O,k]=(0,q.useState)(!1),[A,j]=(0,q.useState)(!1),ee=o||A;hc(()=>D(!1),T&&!ee),hc(()=>w(!1),C&&!T);let M=(0,q.useRef)(null),N=qo(),{showSuccessToast:P,showErrorToast:F}=wt(),I=N&&!u&&!C,[L,te]=(0,q.useState)(!1),ne=!u&&!C&&!m&&!L;(0,q.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(fc({...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 An(l,p,e.predicate,e.targetIds,e.direction),P(`Created ${e.targetIds.length} relation${e.targetIds.length===1?``:`s`}`),wl(),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,Y.jsx)(Sl,{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,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[!u&&(0,Y.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,Y.jsx)(d,{className:`h-4 w-4`})}),r&&(typeof h==`function`?(0,Y.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,Y.jsx)(Ne,{className:`h-4 w-4`})}):(0,Y.jsx)(K,{size:`sm`,variant:`outline`,onClick:()=>D(!0),disabled:!a||ee,children:ee?`Saving…`:`Save / Link to…`})),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>m&&!C?m.onToggleExpanded():w(!C),className:U(`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,Y.jsx)(ve,{className:`h-4 w-4`}):(0,Y.jsx)(Ke,{className:`h-4 w-4`})}),n&&(0,Y.jsx)(`button`,{type:`button`,onClick:n,disabled:ee,className:U(`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,Y.jsx)(E,{className:`h-4 w-4`})})]}),ce=(0,Y.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:U(`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,Y.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between gap-2 border-b px-4`,children:[(0,Y.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 truncate text-sm font-medium`,children:[(0,Y.jsx)(t,{className:`h-4 w-4 shrink-0`}),(0,Y.jsx)(`span`,{className:`truncate`,children:e})]}),se]}),(0,Y.jsx)(rs.Provider,{value:()=>w(!C),children:(0,Y.jsx)(`div`,{className:U(`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,fo.createPortal)((0,Y.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,Y.jsx)(`div`,{className:`flex max-md:absolute max-md:inset-2 max-md:z-10`,children:R})]}),document.body):(0,Y.jsxs)(Y.Fragment,{children:[ce,!m&&R&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`fixed inset-0 z-card bg-scrim animate-fade-in md:hidden`,onClick:()=>!ee&&D(!1),"aria-hidden":!0}),(0,Y.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 El({onSearch:e,onDraftChange:t,inputRef:n,label:r=`Search documents`,clearOnSubmit:i=!0,showSubmitButton:a=!0}){return(0,Y.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,Y.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,Y.jsx)(`button`,{type:`submit`,className:`canvas-nav-button`,"aria-label":`Run search`,title:`Run search`,children:(0,Y.jsx)(pt,{size:17})})]})}function Dl({queries:e,onRemoveQuery:t,scope:n=`path`,onScopeChange:r}){return(0,Y.jsxs)(`div`,{className:`canvas-search-options`,children:[r&&(0,Y.jsxs)(`div`,{className:`canvas-search-scopes`,"aria-label":`Search scope`,children:[(0,Y.jsx)(`span`,{children:`Search in`}),(0,Y.jsx)(`button`,{type:`button`,"aria-pressed":n===`path`,onClick:()=>r(`path`),children:`This path`}),(0,Y.jsx)(`button`,{type:`button`,"aria-pressed":n===`workspace`,onClick:()=>r(`workspace`),children:`Workspace`})]}),e.length>0&&(0,Y.jsxs)(`div`,{className:`canvas-search-queries`,"aria-label":`Active searches`,children:[e.map((e,n)=>(0,Y.jsxs)(`span`,{className:`canvas-search-query`,children:[(0,Y.jsx)(pt,{size:12,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{title:e,children:e}),t&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>t(n),"aria-label":`Remove search: ${e}`,children:(0,Y.jsx)(E,{size:14})})]},`${e}-${n}`)),t&&e.length>1&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>t(-1),className:`canvas-search-clear`,children:`Clear all`})]})]})}function Ol({children:e,accentColor:t}){return(0,Y.jsxs)(`div`,{className:`canvas-navigation-tabs`,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,className:`canvas-tab-divider`,style:t?{backgroundColor:t}:void 0}),e]})}function kl({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,q.useState)(!1),[w,T]=(0,q.useState)(!1),D=(0,q.useRef)(null),O=(0,q.useRef)(null),k=(0,q.useRef)(null),A=(0,q.useRef)(!1),j=JSON.stringify([e,n,r,a]),[ee,M]=(0,q.useState)(j);ee!==j&&(M(j),C(!1)),(0,q.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=dl(r,e).slice(1),I=(e,t,n,r,i=!1)=>n?(0,Y.jsx)(`button`,{type:`button`,className:t,onClick:n,title:r,"aria-current":i?`location`:void 0,children:e}):(0,Y.jsx)(`span`,{className:`canvas-address-label ${t}`,title:r,"aria-current":i?`location`:void 0,children:e});return(0,Y.jsxs)(`header`,{className:`canvas-navigation${y?` has-tabs`:``}`,style:b?{borderTopColor:b}:void 0,children:[y&&(0,Y.jsx)(Ol,{accentColor:b,children:y}),(0,Y.jsxs)(`div`,{className:`canvas-address-row`,children:[(0,Y.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,Y.jsx)(ct,{size:19})}),(0,Y.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,Y.jsx)(El,{inputRef:O,onSearch:_.onSearch,onDraftChange:v,clearOnSubmit:!_.localOnly,showSubmitButton:!1,label:_.queries.length?`Refine search…`:`Search documents…`}):(0,Y.jsxs)(Y.Fragment,{children:[I((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(i,{icon:t||`ph:stack-fill`,className:`h-4 w-4 shrink-0`,"aria-hidden":`true`}),(0,Y.jsx)(`span`,{className:`truncate`,children:e})]}),`canvas-address-workspace`,c,`Browse workspaces`),(0,Y.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,Y.jsxs)(`span`,{className:`canvas-address-segment`,children:[t>0&&(0,Y.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,Y.jsxs)(`span`,{className:`canvas-address-segment`,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:F.length?`/`:``}),I(a,``,d,a)]}),o&&I(`#${o}`,`canvas-address-section`,f,o,!0)]})]}),_&&(0,Y.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,Y.jsx)(pt,{size:17}),_.queries.length>0&&(0,Y.jsx)(`span`,{className:`canvas-nav-dot`})]})]}),p&&(0,Y.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,Y.jsx)(at,{size:19}),m&&(0,Y.jsx)(`span`,{className:`canvas-nav-dot`})]}),g&&(0,Y.jsx)(`button`,{type:`button`,className:`canvas-nav-button canvas-add-button`,onClick:g,"aria-label":`Add here`,title:`Add here`,children:(0,Y.jsx)(Re,{size:21})}),x]}),S&&_&&(0,Y.jsxs)(`div`,{className:`canvas-search-dropdown`,children:[(0,Y.jsxs)(`div`,{className:`canvas-search-heading`,children:[(0,Y.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,Y.jsx)(`button`,{type:`button`,className:`canvas-nav-button`,onClick:N,"aria-label":`Close search`,children:(0,Y.jsx)(E,{size:16})})]}),(0,Y.jsx)(Dl,{..._})]}),!S&&_&&_.queries.length>0&&(0,Y.jsx)(`div`,{className:`px-3 pb-2`,children:(0,Y.jsx)(Dl,{queries:_.queries,onRemoveQuery:_.onRemoveQuery})})]})}function Al({tabs:e,active:t,onChange:n,className:r=``,iconOnly:i=!1}){return(0,Y.jsx)(`div`,{className:`flex gap-1 border-b overflow-x-auto ${r}`,children:e.map(e=>{let r=e.icon;return(0,Y.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,Y.jsx)(r,{className:`h-3.5 w-3.5`}),(!i||!r)&&e.label]},e.id)})})}function jl({workspaceId:e,document:t,className:n}){let r=dc(t);return r?(0,Y.jsx)(r,{workspaceId:e,document:t,className:n}):(0,Y.jsx)(`pre`,{className:`overflow-auto p-2 text-xs`,children:JSON.stringify(t.data,null,2)})}var Ml=e=>`${yt.workspaces}/${encodeURIComponent(e)}/messages`,Nl=e=>G.get(`${Ml(e)}/accounts`),Pl=(e,t)=>G.get(`${Ml(e)}/reply-target/${t}`),Fl=(e,t)=>G.post(`${Ml(e)}/send`,t),Il=(e,t)=>G.get(`${Ml(e)}/whatsapp/${encodeURIComponent(t)}/connection`),Ll=(e,t)=>G.get(`${Ml(e)}/outbox/${encodeURIComponent(t)}`),Rl=(e,t)=>G.delete(`${Ml(e)}/whatsapp/${encodeURIComponent(t)}/connection`),zl=(e,t)=>G.get(`${Ml(e)}/thread/${t}`),Bl=new lr({html:!1});function Vl(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(Bl.parse(e,{})).trim()}function Hl(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 Ul={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function Wl({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${Hl(e)}:smtp-test:${i?.address}`:Hl(e,t,s),l=()=>({requestId:crypto.randomUUID(),text:a?`This is a test email sent from Canvas to check the SMTP configuration.`:``,replyToDocumentId:t,...i,...a?{subject:`Canvas SMTP test`}:{},...s?{forward:!0}:t?{replyAll:n===`replyAll`,quote:!0}:{}}),[u,d]=(0,q.useState)(()=>{try{let e=localStorage.getItem(c);if(e){let r=JSON.parse(e),i=r.draft||r;if(s||!t||r.attempted)return i;let a=n===`replyAll`;return{...i,replyAll:a,...!!i.replyAll===a?{}:{to:void 0,cc:void 0}}}}catch{}return l()}),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)([]),[g,_]=(0,q.useState)(navigator.onLine);(0,q.useEffect)(()=>{let e=()=>_(navigator.onLine);return window.addEventListener(`online`,e),window.addEventListener(`offline`,e),()=>{window.removeEventListener(`online`,e),window.removeEventListener(`offline`,e)}},[]);let v=(0,q.useRef)(!1),[y,b]=(0,q.useState)(!1),[x,S]=(0,q.useState)(!1),[C,w]=(0,q.useState)(()=>{try{return JSON.parse(localStorage.getItem(c)||`{}`).attempted===!0}catch{return!1}}),[T,E]=(0,q.useState)(``),[D,O]=(0,q.useState)(null);(0,q.useEffect)(()=>{let n=!0;return Promise.all([Nl(e),t?Pl(e,t):Promise.resolve(null)]).then(([e,r])=>{n&&(p(r),h(e.filter(e=>e.canSend&&(!r||e.driver===r.driver&&e.address===r.address))),t&&!r&&E(`This message has no supported reply account.`),r&&d(e=>{let t=e.replyAll?r.allRecipients:r.recipients;return{...e,driver:r.driver,address:r.address,...!s&&t&&!C?{to:e.to?.some(e=>e.trim())?e.to:t.to,cc:e.cc?.some(e=>e.trim())?e.cc:t.cc}:{}}}))}).catch(e=>{n&&E(e.message)}),()=>{n=!1}},[e,t,s,C]),(0,q.useEffect)(()=>{try{D?.status===`accepted`?localStorage.removeItem(c):localStorage.setItem(c,JSON.stringify({draft:u,attempted:C}))}catch{}},[c,u,C,D]);let k=m.find(e=>e.driver===u.driver&&e.address===u.address),A=k?.driver===`imap`,j=k?.driver===`whatsapp`,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?Vl(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await Ll(e,u.requestId).catch(n=>{if(n.statusCode===404)return Fl(e,t);throw n}):await Fl(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?Ul.forward:Ul[u.replyAll?`replyAll`:`reply`]:`New message`,ne=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Y.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,Y.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Y.jsx)(`strong`,{className:`text-sm`,children:te}),(0,Y.jsx)(K,{size:`sm`,variant:`ghost`,onClick:o,children:`Close`})]}),(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Send from`,(0,Y.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,Y.jsx)(`option`,{value:``,children:`Select an enabled sending account`}),m.map(e=>(0,Y.jsxs)(`option`,{value:`${e.driver}:${e.address}`,children:[e.driver,` · `,e.from||e.address]},`${e.driver}:${e.address}`))]})]}),a&&(0,Y.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,Y.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,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`To `,t&&!s?`(leave blank to reply to the sender)`:``,(0,Y.jsx)(W,{"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,Y.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,Y.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Y.jsx)(W,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:L,value:u[e]?.join(`, `)||``,onChange:t=>N({[e]:[t.target.value]})})]},e)),(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Y.jsx)(W,{"aria-label":`Subject`,disabled:L,value:u.subject||``,placeholder:ne,onChange:e=>N({subject:e.target.value||void 0})})]}),t&&!s&&(0,Y.jsxs)(`div`,{className:`flex flex-wrap gap-4 text-xs`,children:[(0,Y.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Y.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,Y.jsxs)(`label`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{type:`checkbox`,disabled:L,checked:u.quote||!1,onChange:e=>N({quote:e.target.checked})}),`Quote original message`]})]}),s&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The original message and its attachments are included below your note.`}),(0,Y.jsx)(Rn,{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,Y.jsxs)(Y.Fragment,{children:[!t&&(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Conversation (configured channel name or ID)`,(0,Y.jsx)(W,{"aria-label":`Conversation`,disabled:L,value:u.target||``,onChange:e=>N({target:e.target.value})})]}),j?(0,Y.jsx)(Rn,{format:`markdown`,editable:!L,value:u.text,placeholder:`Write a message…`,onChange:e=>N({text:e.slice(0,32e3)})}):(0,Y.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,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Paste a picture into the reply, or attach one`,(0,Y.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,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(`img`,{className:`h-20 w-20 rounded object-contain`,src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name}),(0,Y.jsx)(`span`,{className:`text-xs`,children:e.name}),(0,Y.jsx)(K,{size:`sm`,variant:`ghost`,disabled:L,onClick:()=>N({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),j&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Bold, italic, strikethrough and code are supported. Your reply becomes the picture caption.`})]}),T&&(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:T}),D&&(0,Y.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,Y.jsx)(K,{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,Y.jsx)(K,{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,Y.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 Gl(e){let t=(0,q.useRef)(null),n=(0,q.useRef)(e.onClose);return(0,q.useEffect)(()=>{n.current=e.onClose}),(0,q.useEffect)(()=>{let e=t.current;if(!e)return;let n=document.activeElement;return e.showModal(),()=>{e.close(),n?.focus()}},[]),(0,Y.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,Y.jsx)(Wl,{...e})})}function Kl({workspaceId:e,documentId:t}){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(``),[o,s]=(0,q.useState)({}),[c,l]=(0,q.useState)(null),u=(0,q.useCallback)(async()=>{try{let n=await zl(e,t);r(n),a(``)}catch(e){a(e instanceof Error?e.message:`Could not load thread`)}},[e,t]);return(0,q.useEffect)(()=>{let n=!0;zl(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(Cl,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(Cl,i)}},[e,t,u]),i?(0,Y.jsxs)(`div`,{className:`p-3`,children:[(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:i}),(0,Y.jsx)(K,{variant:`outline`,size:`sm`,onClick:()=>void u(),children:`Retry`})]}):!n||n.documentId!==t?(0,Y.jsx)(`p`,{className:`p-3 text-sm text-muted-foreground`,children:`Loading thread…`}):(0,Y.jsxs)(`section`,{"aria-label":`Message thread`,className:`space-y-3 p-2`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Y.jsxs)(`h3`,{className:`text-sm font-medium`,children:[`Thread · `,n.documents.length,` message`,n.documents.length===1?``:`s`]}),(0,Y.jsx)(K,{size:`sm`,variant:`outline`,onClick:()=>void u(),children:`Refresh`})]}),n.documents.length===1&&(0,Y.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,Y.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,Y.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,Y.jsxs)(`summary`,{className:`cursor-pointer space-y-1 p-3 text-sm`,children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:i.title}),(0,Y.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[i.subtitle,d&&!Number.isNaN(d.getTime())?` · ${d.toLocaleString()}`:``]}),f.length>0&&(0,Y.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Reply to `,f.join(`, `)]})]}),p&&c&&(0,Y.jsx)(`div`,{className:`flex flex-wrap gap-2 px-3 pb-2`,children:(a?[`reply`,`replyAll`,`forward`]:[`reply`]).map(e=>(0,Y.jsx)(K,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,Y.jsx)(jl,{workspaceId:e,document:r})]},r.id)}),c&&(0,Y.jsx)(Gl,{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 ql(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 Jl=`h-full w-[380px] max-w-[90vw] max-md:w-full`;function Yl({onClose:e,children:t}){return(0,fo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-stretch justify-end bg-scrim animate-fade-in`,onClick:e,children:(0,Y.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 Xl=[{mode:`copy`,label:`Copy to`,icon:(0,Y.jsx)(u,{className:`h-3.5 w-3.5`})},{mode:`move`,label:`Move to`,icon:(0,Y.jsx)(Te,{className:`h-3.5 w-3.5`})},{mode:`delete`,label:`Delete from`,icon:(0,Y.jsx)(pe,{className:`h-3.5 w-3.5`})}],Zl=[{value:`rename`,label:`Rename mine (file-1.ext)`},{value:`overwrite`,label:`Overwrite the existing file`},{value:`error`,label:`Skip the document`}],Ql=`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 $l(e){return e.driver===`cacache`?ft:e.config?.remote===!0?p:F}function eu({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}=wt(),[m,h]=(0,q.useState)(!1);hc(a,!o&&!m);let[_,v]=(0,q.useState)(n),[y,b]=(0,q.useState)(null),[x,S]=(0,q.useState)(null),[w,T]=(0,q.useState)(()=>new Set(n===`delete`&&c?[c.backend]:[])),[D,O]=(0,q.useState)(!1),[k,A]=(0,q.useState)(``),[j,ee]=(0,q.useState)(r),[M,N]=(0,q.useState)(`rename`);(0,q.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,q.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,q.useMemo)(()=>(y||[]).filter(e=>w.has(e.address)&&bn(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(!bn(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,Y.jsxs)(`div`,{className:U(`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,Y.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Y.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Y.jsx)(F,{className:`h-4 w-4`}),ue]}),(0,Y.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,Y.jsx)(E,{className:`h-4 w-4`})})]}),(0,Y.jsx)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:Xl.map(({mode:e,label:t,icon:n})=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>te(e),disabled:o,className:U(`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,Y.jsxs)(`div`,{className:`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,children:[x&&(0,Y.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-destructive`,children:x}),!y&&!x&&(0,Y.jsx)(`div`,{className:`px-2 py-3 text-xs text-muted-foreground`,children:`Loading backends…`}),y?.length===0&&(0,Y.jsx)(`p`,{className:`px-2 py-1.5 text-xs text-muted-foreground`,children:`No storage backends configured.`}),y?.map(e=>{let t=$l(e),n=I(e),r=w.has(e.address),i=e.config?.remote===!0;return(0,Y.jsxs)(`div`,{onClick:()=>!n&&!o&&ne(e.address),className:U(`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,Y.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,Y.jsx)(t,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,Y.jsx)(`span`,{className:`block truncate font-medium`,children:e.config?.label||e.address}),(0,Y.jsxs)(`span`,{className:`block truncate font-mono text-[10px] text-muted-foreground`,children:[e.driver,` · `,e.address]})]}),i&&(0,Y.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,Y.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,Y.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,Y.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,Y.jsxs)(`span`,{children:[`Keep the index entry when its `,(0,Y.jsx)(`strong`,{children:`last`}),` copy is deleted.`,(0,Y.jsx)(`span`,{className:`block text-muted-foreground`,children:`Otherwise the document moves to workspace Trash once no locations remain.`})]})]}),ie&&(0,Y.jsxs)(`div`,{className:`mt-3 space-y-2 rounded-md border px-3 py-2`,children:[(0,Y.jsxs)(`p`,{className:`text-xs font-medium`,children:[`Destination on `,re.map(e=>e.config?.label||e.address).join(`, `)]}),(0,Y.jsxs)(`div`,{className:`space-y-1`,children:[(0,Y.jsx)(`label`,{htmlFor:`backend-transfer-folder`,className:`text-[11px] text-muted-foreground`,children:`Folder (relative to the backend root)`}),(0,Y.jsxs)(`div`,{className:`flex gap-1.5`,children:[(0,Y.jsx)(W,{id:`backend-transfer-folder`,value:k,onChange:e=>A(e.target.value),placeholder:`/`,disabled:o,className:`h-9 font-mono text-xs`}),(0,Y.jsx)(K,{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,Y.jsx)(g,{className:`h-4 w-4`})})]})]}),t===1?(0,Y.jsxs)(`div`,{className:`space-y-1`,children:[(0,Y.jsx)(`label`,{htmlFor:`backend-transfer-filename`,className:`text-[11px] text-muted-foreground`,children:`File name`}),(0,Y.jsx)(W,{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,Y.jsx)(`p`,{className:`text-[11px] text-muted-foreground`,children:`Each document keeps its own file name and extension.`}),(0,Y.jsxs)(`div`,{className:`space-y-1`,children:[(0,Y.jsx)(`label`,{htmlFor:`backend-transfer-conflict`,className:`text-[11px] text-muted-foreground`,children:`If a different file already has that name`}),(0,Y.jsx)(`select`,{id:`backend-transfer-conflict`,className:Ql,value:M,onChange:e=>N(e.target.value),disabled:o,children:Zl.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),_===`move`&&L.length>0&&(0,Y.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,Y.jsxs)(`div`,{role:`status`,className:`flex items-center justify-between gap-2 border-t px-4 py-2 text-xs`,children:[(0,Y.jsxs)(`span`,{children:[d?`Stopping after current file`:`Processing`,` · `,l.completed,`/`,l.total]}),f&&(0,Y.jsx)(K,{size:`sm`,variant:`outline`,onClick:f,disabled:d,children:`Stop`})]}),(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-t px-4 py-3`,children:[(0,Y.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[w.size,` backend`,w.size===1?``:`s`,` selected`]}),(0,Y.jsx)(K,{size:`sm`,variant:_===`delete`?`destructive`:`default`,onClick:se,disabled:w.size===0||o,children:o?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(_o,{className:`mr-1.5 h-3.5 w-3.5`}),`Working…`]}):(0,Y.jsxs)(Y.Fragment,{children:[_===`delete`?(0,Y.jsx)(pe,{className:`mr-1 h-3.5 w-3.5`}):_===`move`?(0,Y.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}):(0,Y.jsx)(u,{className:`mr-1 h-3.5 w-3.5`}),z]})})]}),_===`delete`&&(0,Y.jsxs)(`div`,{className:`flex items-start gap-2 border-t bg-destructive/5 px-4 py-2 text-[11px] text-muted-foreground`,children:[(0,Y.jsx)(C,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive`}),(0,Y.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,Y.jsx)(Yl,{onClose:()=>h(!1),children:(0,Y.jsx)(Sl,{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 tu({tags:e,onChange:t,placeholder:n=`Add tag, press Enter`,suggestions:r=[]}){let[i,a]=(0,q.useState)(``),[o,s]=(0,q.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,Y.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,Y.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-xs`,children:[n,(0,Y.jsx)(`button`,{type:`button`,onClick:()=>t(e.filter(e=>e!==n)),className:`text-muted-foreground hover:text-foreground`,"aria-label":`Remove ${n}`,children:(0,Y.jsx)(E,{className:`h-3 w-3`})})]},n)),(0,Y.jsxs)(`div`,{className:`relative flex-1 min-w-[8ch]`,children:[(0,Y.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,Y.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,Y.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 nu=e(ur(),1),ru=`#8b5cf6`,iu=`https://nominatim.openstreetmap.org`,au=700,ou=e=>Math.round(e*1e6)/1e6;function su(){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:${ru};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 nu.default.divIcon({html:e,className:`canvas-map-pick`,iconSize:[28,28],iconAnchor:[14,28]})}function cu({initial:e,onPick:t,onClose:n}){let r=(0,q.useRef)(null),i=(0,q.useRef)(null),a=(0,q.useRef)(null),o=(0,q.useRef)(null);(0,q.useEffect)(()=>()=>o.current?.abort(),[]);let[s,c]=(0,q.useState)(e?{lat:e.lat,lon:e.lon}:null),[l,u]=(0,q.useState)(``),[d,f]=(0,q.useState)([]),[p,m]=(0,q.useState)(!1),[h,g]=(0,q.useState)(null),[_,v]=(0,q.useState)(!1),[y,x]=(0,q.useState)(!1),[S,C]=(0,q.useState)(!1);(0,q.useEffect)(()=>{let e=requestAnimationFrame(()=>C(!0));return()=>cancelAnimationFrame(e)},[]),hc(n);let w=(0,q.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let o=nu.default.latLng(e,t);a.current?a.current.setLatLng(o):(a.current=nu.default.marker(o,{icon:su(),draggable:!0,autoPan:!0}).addTo(r),a.current.on(`dragend`,()=>{let e=a.current.getLatLng();c({lat:ou(e.lat),lon:ou(e.lng)})})),c({lat:ou(e),lon:ou(t),...n?{label:n}:{}})},[]);(0,q.useEffect)(()=>{let t=r.current;if(!t||i.current)return;let n=nu.default.map(t,{center:e?[e.lat,e.lon]:[20,0],zoom:e?13:2,worldCopyJump:!0,zoomControl:!0});nu.default.tileLayer(`https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`,{attribution:`© 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,q.useEffect)(()=>{if(!s||s.label)return;let{lat:e,lon:t}=s,n=new AbortController,r=setTimeout(()=>{v(!0),fetch(`${iu}/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))},au);return()=>{clearTimeout(r),n.abort()}},[s]);let T=(0,q.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(`${iu}/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,q.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,q.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(nu.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,fo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:U(`fixed inset-0 z-[60] bg-scrim transition-opacity duration-normal`,S?`opacity-100`:`opacity-0`),onClick:n}),(0,Y.jsxs)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":`Pick a location on the map`,className:U(`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,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 border-b px-3 py-2`,children:[(0,Y.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Y.jsx)(H,{className:`h-4 w-4 text-info`}),`Custom geotag`]}),(0,Y.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,Y.jsx)(E,{className:`h-4 w-4`})})]}),(0,Y.jsxs)(`div`,{className:`relative z-10 shrink-0 border-b px-3 py-2`,children:[(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsxs)(`div`,{className:`relative flex-1`,children:[(0,Y.jsx)(pt,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,Y.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,Y.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,Y.jsx)(lt,{className:`h-3.5 w-3.5 animate-spin`}):(0,Y.jsx)(Ve,{className:`h-3.5 w-3.5`})}),(0,Y.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,Y.jsx)(lt,{className:`h-3.5 w-3.5 animate-spin`}):(0,Y.jsx)(pt,{className:`h-3.5 w-3.5`}),`Search`]})]}),h&&(0,Y.jsx)(`p`,{role:`status`,className:`mt-1 text-xs text-warning`,children:h}),d.length>0&&(0,Y.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,Y.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,Y.jsxs)(`div`,{className:`relative isolate z-0 min-h-0 flex-1`,children:[(0,Y.jsx)(`div`,{ref:r,className:`h-full w-full`}),!s&&(0,Y.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-3 z-[1000] flex justify-center`,children:(0,Y.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,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-3 border-t px-3 py-2`,children:[(0,Y.jsx)(`div`,{className:`min-w-0 text-xs`,children:s?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 tabular-nums text-foreground`,children:[(0,Y.jsx)(gt,{className:`h-3 w-3 shrink-0 text-muted-foreground`}),s.lat.toFixed(5),`, `,s.lon.toFixed(5),_&&(0,Y.jsx)(lt,{className:`h-3 w-3 animate-spin text-muted-foreground`})]}),s.label&&(0,Y.jsx)(`div`,{className:`truncate text-muted-foreground`,children:s.label})]}):(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`No point selected`})}),(0,Y.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[(0,Y.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,Y.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,Y.jsx)(b,{className:`h-3.5 w-3.5`}),`Use this point`]})]})]})]})]}),document.body)}var lu={exif:`from the photo's EXIF`,device:`from the device at capture`,manual:`placed by hand`};function uu(e){let t=`${e.lat.toFixed(5)}, ${e.lon.toFixed(5)}`,n=e.source?lu[e.source]:null;return[t,e.accuracy==null?null:`±${e.accuracy} m`,n].filter(Boolean).join(` · `)}function du({value:e,onChange:t,idPrefix:n=`edit-geo`}){let[r,i]=(0,q.useState)(!1);return(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${n}-action`,children:`Location`}),(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Y.jsxs)(`span`,{className:`flex min-w-0 items-center gap-2 text-xs`,children:[(0,Y.jsx)(H,{className:e?`h-4 w-4 shrink-0 text-info`:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:e?`truncate tabular-nums`:`truncate text-muted-foreground`,children:e?uu(e):`No location on this document`})]}),(0,Y.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1`,children:[(0,Y.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,Y.jsx)(tt,{className:`h-3.5 w-3.5`}),e?`Move pin`:`Set on map`]}),e&&(0,Y.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,Y.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]}),r&&(0,Y.jsx)(cu,{initial:e,onPick:e=>t({lat:e.lat,lon:e.lon,source:`manual`}),onClose:()=>i(!1)})]})}var fu=15,pu=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function mu(e){return String(e).padStart(2,`0`)}function hu(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 gu(e){return`${e.getFullYear()}-${mu(e.getMonth()+1)}-${mu(e.getDate())}`}function _u(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function vu(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/fu)*fu),`${mu(e.getHours())}:${mu(e.getMinutes())}`}function yu(){let e=[];for(let t=0;t<1440;t+=fu)e.push(`${mu(Math.floor(t/60))}:${mu(t%60)}`);return e}var bu=yu();function xu(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 Su(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 Cu(e){let t=hu(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 wu({value:e,onChange:t,id:n,placeholder:r=`Pick a date & time`,clearable:i=!0,disabled:a=!1,compact:o=!1,className:s=``}){let[c,l]=(0,q.useState)(!1),u=(0,q.useRef)(null),d=hu(e),f=d?Cu(e):``;return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`button`,{ref:u,id:n,type:`button`,disabled:a,onClick:()=>l(e=>!e),"aria-haspopup":`dialog`,"aria-expanded":c,className:U(`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,Y.jsx)(T,{className:U(`shrink-0 text-muted-foreground`,o?`h-3 w-3`:`h-4 w-4`)}),(0,Y.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:f||r}),i&&d&&(0,Y.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,Y.jsx)(E,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Y.jsx)(Tu,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function Tu({anchorRef:e,value:t,onChange:n,onClose:r}){let i=hu(t),a=i?.date??gu(new Date),o=i?.time??null,[s,c]=(0,q.useState)(()=>{let e=_u(a);return new Date(e.getFullYear(),e.getMonth(),1)}),u=(0,q.useRef)(null),d=(0,q.useRef)(null),[f,p]=(0,q.useState)(null);(0,q.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,q.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,q.useMemo)(()=>!o||bu.includes(o)?bu:[...bu,o].sort(),[o]);(0,q.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??vu();h(gu(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??vu();h(gu(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},y=gu(new Date),b=xu(s);return(0,fo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`fixed inset-0 z-40`,onClick:r}),(0,Y.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,Y.jsxs)(`div`,{className:`w-[236px]`,children:[(0,Y.jsxs)(`div`,{className:`mb-1 flex items-center justify-between`,children:[(0,Y.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,Y.jsx)(l,{className:`h-4 w-4`})}),(0,Y.jsx)(`span`,{className:`text-xs font-medium`,children:s.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}),(0,Y.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,Y.jsx)(_t,{className:`h-4 w-4`})})]}),(0,Y.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:pu.map(e=>(0,Y.jsx)(`span`,{children:e},e))}),(0,Y.jsx)(`div`,{className:`grid grid-cols-7 gap-0.5`,children:b.map(e=>{let t=gu(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Y.jsx)(`button`,{type:`button`,onClick:()=>g(e),"aria-pressed":r,className:U(`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,Y.jsx)(`div`,{className:`mt-1.5 flex gap-1`,children:[[`Today`,0],[`Tomorrow`,1],[`Next week`,7]].map(([e,t])=>(0,Y.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,Y.jsxs)(`div`,{className:`flex w-[104px] flex-col`,children:[(0,Y.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,Y.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,Y.jsx)(`button`,{type:`button`,"data-selected":t,onClick:()=>_(e),"aria-pressed":t,className:U(`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:Su(e)},e)})})]})]})]}),document.body)}var Eu={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},Du=`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`,Ou=`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 ku({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,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${u}-title`,children:`Title`}),(0,Y.jsx)(W,{id:`${u}-title`,value:e,onChange:e=>t(e.target.value),placeholder:`What needs doing?`})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${u}-desc`,children:`Description`}),(0,Y.jsx)(`textarea`,{id:`${u}-desc`,value:n,onChange:e=>r(e.target.value),rows:3,placeholder:`Optional details…`,className:Ou})]}),(0,Y.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${u}-due`,children:`Due`}),(0,Y.jsx)(wu,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${u}-priority`,children:`Priority`}),(0,Y.jsxs)(`select`,{id:`${u}-priority`,value:o===``?``:String(o),onChange:e=>s(e.target.value===``?``:Number(e.target.value)),className:Du,children:[(0,Y.jsx)(`option`,{value:``,children:`None`}),[1,2,3,4,5,6,7,8,9].map(e=>(0,Y.jsx)(`option`,{value:e,children:Eu[e]},e))]})]})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${u}-status`,children:`Status`}),(0,Y.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:Du,children:Ms.map(e=>(0,Y.jsx)(`option`,{value:e,children:Ns[e]},e))})]})]})}var Au=`3.0`,ju=[`person`,`organization`,`service`,`bot`],Mu={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Nu=[`email`,`phone`,`sms`,`chat`,`web`],Pu=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function Fu(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 Iu(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Tn(String(e?.schema||``),Xt);return{displayName:String(t.displayName||``),type:ju.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 Lu(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await An(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function Ru(e){let[t,n]=(0,q.useState)(e?.displayName??``),[r,i]=(0,q.useState)(e?.type??`person`),[a,o]=(0,q.useState)(e?.primaryEmail??``),[s,c]=(0,q.useState)(e?.given??``),[l,u]=(0,q.useState)(e?.family??``),[d,f]=(0,q.useState)(e?.channels??[]),[p,m]=(0,q.useState)(e?.identifiers??[]),[h,g]=(0,q.useState)(e?.organizations??[]),[_,v]=(0,q.useState)([]),[y,b]=(0,q.useState)(``),[x,S]=(0,q.useState)(!1),C={displayName:t,type:r,primaryEmail:a,given:s,family:l,channels:d,identifiers:p,organizations:h},w=!a.trim()||/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.trim()),T=t.trim().length>0&&w&&!x;async function E(e){S(!0);try{let t=y.trim(),n={schema:`${Xt}/${C.type}`,schemaVersion:Au,data:Fu(C),...t?{comment:t}:{},metadata:{features:Gn(_)}},r=await ar(e,[n]);return await Lu(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 zu=`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 Bu({label:e,rows:t,onChange:n,blank:r,addLabel:i,children:a}){return(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Y.jsx)(po,{children:e}),(0,Y.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,Y.jsx)(Re,{className:`h-3 w-3`}),` `,i]})]}),t.length===0?(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`None yet.`}):(0,Y.jsx)(`div`,{className:`space-y-1.5`,children:t.map((r,i)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[a(r,e=>n(t.map((t,n)=>n===i?{...t,...e}:t))),(0,Y.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,Y.jsx)(pe,{className:`h-3.5 w-3.5`})})]},i))})]})}function Vu(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 Hu(e){let[t,n]=(0,q.useState)([]);return(0,q.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 Uu({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=Hu(t);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Y.jsx)(W,{id:`${e}-display-name`,value:n,onChange:e=>r(e.target.value),placeholder:`Jane Doe, Acme Ltd, build-bot…`,autoFocus:!0})]}),(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsxs)(`div`,{className:`w-40 space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${e}-type`,children:`Type`}),(0,Y.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:U(zu,`w-full`),children:ju.map(e=>(0,Y.jsx)(`option`,{value:e,children:Mu[e]},e))})]}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Y.jsx)(W,{id:`${e}-email`,type:`email`,value:o,onChange:e=>s(e.target.value),placeholder:`jane@example.com`}),!v&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid email address.`})]})]}),i===`person`&&(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${e}-given`,children:`Given name`}),(0,Y.jsx)(W,{id:`${e}-given`,value:c,onChange:e=>l(e.target.value),placeholder:`Jane`})]}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`${e}-family`,children:`Family name`}),(0,Y.jsx)(W,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Y.jsx)(Bu,{label:`Channels`,rows:f,onChange:p,blank:()=>({kind:`email`,value:``}),addLabel:`Add channel`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`select`,{value:e.kind,onChange:e=>t({kind:e.target.value}),className:U(zu,`w-24`),children:[Nu.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Nu.includes(e.kind)&&(0,Y.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Y.jsx)(W,{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,Y.jsx)(`button`,{type:`button`,onClick:()=>p(Vu(f,f.indexOf(e))),className:U(`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,Y.jsx)(Je,{className:U(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Y.jsx)(Bu,{label:`Identifiers`,rows:m,onChange:h,blank:()=>({type:`github`,identifier:``}),addLabel:`Add identifier`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`select`,{value:e.type,onChange:e=>t({type:e.target.value}),className:U(zu,`w-24`),children:[Pu.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Pu.includes(e.type)&&(0,Y.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Y.jsx)(W,{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,Y.jsx)(Bu,{label:`Organizations`,rows:g,onChange:_,blank:()=>({name:``}),addLabel:`Add organization`,children:(e,t)=>(0,Y.jsxs)(Y.Fragment,{children:[y.length>0?(0,Y.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:U(zu,`min-w-0 flex-1`),children:[(0,Y.jsx)(`option`,{value:``,children:`Other… (type a name)`}),y.map(e=>(0,Y.jsx)(`option`,{value:e.id,children:e.name},e.id))]}):null,!e.identityId&&(0,Y.jsx)(W,{value:e.name,onChange:e=>t({name:e.target.value}),placeholder:`Acme Ltd`,className:`min-w-0 flex-1`}),e.identityId&&(0,Y.jsx)(`span`,{className:`shrink-0 text-muted-foreground`,title:`Linked — saving relates this identity to that organization`,children:(0,Y.jsx)(Ne,{className:`h-3.5 w-3.5`})}),(0,Y.jsx)(W,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function Wu(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 Gu(e){return Wu(e.schema)||Vn(e)}function Ku(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function qu(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 An(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 Ju({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=wt(),a=Wu(e.schema),o=e.schema===Yt,s=Vn(e),c=Kn(e)??`markdown`,l=s&&In(e),u=e.schema===Mt,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=Ku(e.schema),[m,h]=(0,q.useState)(f?String(e.data?.[f]??``):``),[g,_]=(0,q.useState)(String(e.data?.[p]??``)),[v,y]=(0,q.useState)(String(e.data?.content??``)),[b,x]=(0,q.useState)(String(e.data?.description??``)),[S,C]=(0,q.useState)(e.data?.status??`pending`),[w,T]=(0,q.useState)(typeof e.data?.priority==`number`?e.data.priority:``),[E,D]=(0,q.useState)(e.data?.dueDate?Is(String(e.data.dueDate)):Rs()),O=Ru(Iu(e)),[k,A]=(0,q.useState)(String(e.comment??``)),j=e.metadata?.geo??null,[ee,M]=(0,q.useState)(j),N=e.features??e.metadata?.features,[P,F]=(0,q.useState)(zn(N).length?zn(N):e.data?.tags??[]),I=Ln(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=Hn(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Un,version:e.checksumArray?.[0]??null}),[de,z]=(0,q.useState)(null),fe=`${e.id}:${e.checksumArray?.[0]??``}`;s&&ue.text!=null&&de!==fe&&(z(fe),oe(ue.text));let[pe,me]=(0,q.useState)([]),[he,ge]=(0,q.useState)(!1),{replicating:_e,mirror:ve}=Ht(e);(0,q.useEffect)(()=>{let e=!1;return Ot(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/`)),...Gn(re)];try{if(o){await I.save(),n();return}if(s){let i=await Jn(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,...Fu(O.values)}}else if(u)i.data={...e.data,...zs({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 Mn(t,i),d&&(await qu(t,e.id,O.values.organizations),wl()),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,Y.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[a&&f&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`edit-url`,children:`URL`}),(0,Y.jsx)(W,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!ye&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Y.jsx)(Uu,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Y.jsx)(ku,{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,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`edit-title`,children:`Title`}),(0,Y.jsx)(W,{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,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{children:`Body`}),l?(0,Y.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,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:ue.error}):s&&ue.text==null?(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Y.jsx)(Wn,{kind:o?`markdown`:c,value:te,onChange:oe,placeholder:o?`Write your note…`:void 0})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{children:`Tags`}),(0,Y.jsx)(tu,{tags:re,onChange:se,suggestions:pe})]}),(0,Y.jsx)(du,{value:ie,onChange:ce}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(po,{htmlFor:`edit-comment`,children:`Comment`}),(0,Y.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,Y.jsx)(qn,{...I,onRetry:I.save}),(0,Y.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Y.jsx)(K,{variant:`outline`,size:`sm`,onClick:()=>n(),disabled:he,children:o?`Close`:`Cancel`}),(0,Y.jsx)(K,{size:`sm`,onClick:xe,disabled:!be,children:he?_e?`Replicating to ${ve.label}…`:`Saving…`:`Save changes`})]})]})}var Yu=(0,q.createContext)(null),Xu={open:()=>{},close:()=>{}};function Zu(){return(0,q.useContext)(Yu)??Xu}var Qu=(0,q.createContext)(null),$u={entry:null,open:()=>{},close:()=>{}};function ed(){return(0,q.useContext)(Qu)??$u}var td=`main`,nd=(0,q.createContext)(null);function rd(){return(0,q.useContext)(nd)}var id=50;function ad({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=Zu(),o=ed(),s=rd(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?Gt(l).title:``,[d,f]=(0,q.useState)(!1),{showErrorToast:p}=wt(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await Sn(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,Y.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,Y.jsx)(Te,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}):(0,Y.jsx)(ct,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Y.jsx)(ll,{document:l,size:3.5}):null,l?(0,Y.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,Y.jsxs)(`span`,{className:`min-w-0 flex-1 truncate italic text-muted-foreground`,children:[`Document `,c,` (not available)`]}),(0,Y.jsxs)(`span`,{className:`shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`#`,c]}),!h&&(0,Y.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,Y.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,Y.jsx)(pe,{className:`h-3.5 w-3.5`})})]})}function od({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=wt(),[i,a]=(0,q.useState)(null),[o,s]=(0,q.useState)(null),[c,l]=(0,q.useState)(!1),[u,d]=(0,q.useState)(!1),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(0),[g,_]=(0,q.useState)(1),v=(0,q.useRef)(0),y=(0,q.useCallback)(()=>{v.current++},[]),b=(0,q.useCallback)(async()=>{let n=++v.current;try{let r=await $t(t,e.id,{offset:m*id,limit:id,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)/id)-1);if(_(i+1),m>i){h(i);return}a(r),s(null)}catch(e){if(n!==v.current)return;s(e instanceof Error?e.message:String(e))}},[t,e.id,m]),x=`${t}:${e.id}`,[S,C]=(0,q.useState)(x);x!==S&&(C(x),a(null),s(null),h(0),_(1)),(0,q.useEffect)(()=>{async function e(){await b()}return e(),window.addEventListener(Cl,e),()=>{y(),window.removeEventListener(Cl,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`),wl()}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,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-2`,children:[(0,Y.jsx)(`h3`,{className:`font-semibold`,children:`Documents`}),(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Y.jsx)(Re,{className:`mr-1 h-3 w-3`}),` Add relation`]})]}),o?(0,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:o}):i?T.every(e=>e.entries.length===0)?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No related documents.`}):(0,Y.jsx)(`div`,{className:`space-y-4`,children:T.filter(e=>e.entries.length>0).map(({dir:e,title:n,hint:r,entries:i})=>(0,Y.jsxs)(`div`,{children:[(0,Y.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,Y.jsxs)(`div`,{className:`mb-2`,children:[(0,Y.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,Y.jsx)(ad,{relation:n,workspaceId:t,direction:e,removing:f===i,onRemove:()=>void w(n,e)},i)})]},n))]},e))}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading relations…`}),(g>1||m>0)&&(0,Y.jsxs)(`div`,{className:`mt-3 flex items-center justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Y.jsx)(K,{variant:`outline`,size:`sm`,disabled:m===0,onClick:()=>E(m-1),children:`Previous`}),(0,Y.jsxs)(`span`,{children:[`Page `,m+1,` of `,g]}),(0,Y.jsx)(K,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,Y.jsx)(Yl,{onClose:()=>{u||l(!1)},children:(0,Y.jsx)(Sl,{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 An(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),wl()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var sd=(0,q.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]))),cd=(0,q.lazy)(()=>s(()=>import(`./TextDocumentEditor-BKueFXia.js`),__vite__mapDeps([25,3,4,11,10,13,12,14,15,16,26,1,23]))),ld={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},ud={reply:ie,replyAll:m,forward:oe};function dd({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Xn()!=null,{showErrorToast:a}=wt(),[o,s]=(0,q.useState)(!1),c=[`data/schema/message`,`data/schema/message/email`].includes(e.schema),[l,u]=(0,q.useState)(null),d=e.schema===`data/schema/message/email`,f=!i&&(d||[`slack`,`whatsapp`].includes(String(e.data?.platform))),p=d?[`reply`,`replyAll`,`forward`]:[`reply`],m=e=>u(t=>t===e?null:e),h=!i,[g,_]=(0,q.useState)(n&&!i),v=e.schema===qt,[y,b]=(0,q.useState)(!1),x=e.schema===`data/schema/note`||Vn(e),[S,C]=(0,q.useState)(!1),T=`${t}:${e.id}:${n}:${i}`,[E,D]=(0,q.useState)(T);T!==E&&(D(T),_(n&&!i),u(null),s(!1),b(!1),C(!1));let O=t=>{if(!h||!Gu(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,Y.jsx)(Ju,{document:e,workspaceId:t,onClose:e=>{_(!1),r?.(e)}}):(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col gap-3`,children:[h&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 justify-end gap-2`,children:[c&&(0,Y.jsx)(K,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=ud[e];return(0,Y.jsxs)(K,{size:`sm`,variant:l===e?`secondary`:`outline`,onClick:()=>m(e),children:[(0,Y.jsx)(t,{className:`mr-1.5 h-3.5 w-3.5`}),ld[e]]},e)}),e.schema===`data/schema/file`&&(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>Wt(t,e.id,Pt(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Y.jsx)(Me,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Y.jsx)(w,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>C(!0),children:[(0,Y.jsx)(vt,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Y.jsx)(k,{className:`mr-1 h-3 w-3`}),` Edit`]})]}),y&&h&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading sketch editor…`})}),children:(0,Y.jsx)(sd,{doc:e,workspaceName:t,onSaved:()=>{b(!1),r?.()},onClose:()=>b(!1),onDetails:()=>{b(!1),_(!0)}})}),S&&h&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`div`,{className:`fixed inset-0 z-fullscreen flex items-center justify-center bg-background surface-glass`,children:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading editor…`})}),children:(0,Y.jsx)(cd,{doc:e,workspaceName:t,onSaved:e=>{C(!1),r?.(e)},onClose:()=>C(!1),onDetails:()=>{C(!1),_(!0)}})}),(0,Y.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,Y.jsx)(Kl,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,Y.jsx)(jl,{workspaceId:t,document:e}),l&&f&&(0,Y.jsx)(Gl,{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,Y.jsxs)(`div`,{className:`shrink-0 rounded-md border border-border bg-muted/40 px-3 py-2`,children:[(0,Y.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground mb-0.5`,children:`Comment`}),(0,Y.jsx)(`p`,{className:`text-sm whitespace-pre-wrap`,children:e.comment})]})]})}var fd=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,pd=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function md({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,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`span`,{className:`font-medium`,children:[e,`:`]}),(0,Y.jsx)(`span`,{className:`ml-2`,children:t})]});return(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Photo`}),(0,Y.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`,pd(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`,fd(n.capturedAt)),t&&Number.isFinite(t.lat)&&Number.isFinite(t.lon)&&i(`Location`,(0,Y.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 hd({document:e}){let t=e.metadata;return(0,Y.jsxs)(`div`,{className:`space-y-6`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Basic Information`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Y.jsx)(`span`,{className:`ml-2 font-mono`,children:e.id})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Schema:`}),(0,Y.jsx)(`span`,{className:`ml-2 font-mono`,children:e.schema})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Schema Version:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.schemaVersion})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Created:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:fd(e.createdAt)})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:fd(e.updatedAt)})]})]})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Metadata`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Content Type:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentType??`—`})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Content Encoding:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:e.metadata?.contentEncoding??`—`})]}),Number.isFinite(e.metadata?.size)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Size:`}),(0,Y.jsxs)(`span`,{className:`ml-2`,children:[e.metadata?.size,` bytes`]})]})]})]}),(0,Y.jsx)(md,{meta:t}),Array.isArray(e.locations)&&e.locations.length>0&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Locations`}),(0,Y.jsx)(`div`,{className:`space-y-2`,children:e.locations.map((e,t)=>{let{backend:n,key:r}=yd(e.url);return(0,Y.jsxs)(`div`,{className:`flex items-baseline gap-2 text-sm font-mono`,children:[(0,Y.jsx)(`span`,{className:`font-medium shrink-0`,children:n}),e.status&&e.status!==`available`&&(0,Y.jsx)(`span`,{className:`shrink-0 rounded border px-1 text-xs`,title:e.statusChangedAt,children:e.status===`deleted`?`Deleted`:`Not found`}),r&&(0,Y.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),Array.isArray(e.checksumArray)&&e.checksumArray.length>0&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Checksums`}),(0,Y.jsx)(`div`,{className:`space-y-2`,children:e.checksumArray.map((e,t)=>{let[n,r]=e.split(`/`);return(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-mono`,children:[(0,Y.jsxs)(`span`,{className:`font-medium`,children:[n,`:`]}),(0,Y.jsx)(`span`,{className:`break-all text-muted-foreground`,children:r})]},t)})})]}),e.indexOptions&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`font-semibold mb-3`,children:`Index Options`}),(0,Y.jsxs)(`div`,{className:`space-y-3 text-sm`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`FTS Search Fields:`}),(0,Y.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.ftsSearchFields??[]).map((e,t)=>(0,Y.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Vector Embedding Fields:`}),(0,Y.jsx)(`div`,{className:`ml-2 mt-1`,children:(e.indexOptions.vectorEmbeddingFields??[]).map((e,t)=>(0,Y.jsx)(`span`,{className:`mb-1 mr-2 inline-block rounded bg-muted px-2 py-1 text-xs`,children:e},t))})]})]})]})]})}function gd({document:e}){let{showSuccessToast:t,showErrorToast:n}=wt(),r=JSON.stringify(e,null,2);return(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`div`,{className:`flex justify-end`,children:(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:async()=>{try{await navigator.clipboard.writeText(r),t(`Copied to clipboard`)}catch{n(`Copy failed`)}},children:[(0,Y.jsx)(u,{className:`mr-1 h-3 w-3`}),` Copy to clipboard`]})}),(0,Y.jsx)(`pre`,{className:`overflow-x-auto rounded-lg bg-muted p-4 text-xs`,children:r})]})}function _d({document:e,workspaceId:t}){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(null),o=`${t}:${e.id}`,[s,c]=(0,q.useState)(o);return o!==s&&(c(o),r(null),a(null)),(0,q.useEffect)(()=>{let n=!1;return 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,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:i}):n?(0,Y.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,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`mb-3 font-semibold`,children:e}),i.length===0?(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No placements.`}):(0,Y.jsx)(`div`,{className:`space-y-1`,children:i.map(({tree:e,path:t},n)=>(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 text-sm`,children:[(0,Y.jsx)(`span`,{className:`break-all font-mono text-xs`,children:t}),r.length>1&&(0,Y.jsxs)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:[`(`,e,`)`]})]},`${e}:${t}:${n}`))})]},t)}),(0,Y.jsx)(od,{document:e,workspaceId:t})]}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function vd(e){return e===`stored`?ft:e===`workspace-file`?F:e===`imap`?B:e===`readonly`?se:it}function yd(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 bd({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=wt(),[a,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(null),[l,d]=(0,q.useState)(null),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(null),[g,_]=(0,q.useState)(!1),v=`${t}:${e.id}`,[y,b]=(0,q.useState)(v);v!==y&&(b(v),o(null),c(null),p(null));let x=()=>{It(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,q.useEffect)(()=>{let n=!1;return It(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 vn(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 jn(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(ql(i.failed,new Map([[e.id,Pt(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,Y.jsx)(`p`,{className:`text-sm text-destructive`,children:s});if(!a)return(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading locations...`});let T=a.length===0,E=Pt(e);return(0,Y.jsxs)(`div`,{className:`space-y-3`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2 rounded border px-3 py-2 text-sm`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(ft,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`font-mono text-xs`,children:`workspace:db`}),(0,Y.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[`index entry (id `,e.id,`)`]})]}),(0,Y.jsx)(`span`,{className:`shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] uppercase text-muted-foreground`,children:`json`})]}),T?(0,Y.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,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>h(`copy`),title:`Copy the file data to another storage backend (keeps the existing copies)`,children:[(0,Y.jsx)(u,{className:`mr-1 h-3.5 w-3.5`}),` Copy to…`]}),(0,Y.jsxs)(K,{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,Y.jsx)(Te,{className:`mr-1 h-3.5 w-3.5`}),` Move to…`]})]}),a.map(n=>{let r=vd(n.kind),{backend:a,key:o}=yd(n.url),s=l===n.url;return(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border px-3 py-2 text-sm`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,Y.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[(0,Y.jsx)(r,{className:`h-4 w-4 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{className:`shrink-0 font-mono text-xs`,children:n.backend||a}),(0,Y.jsx)(`span`,{className:`truncate font-mono text-xs text-muted-foreground`,title:n.url,children:o||n.url})]}),(0,Y.jsxs)(`span`,{className:`flex shrink-0 items-center gap-2`,children:[(0,Y.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,Y.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,Y.jsx)(Me,{className:`h-3.5 w-3.5`})}),(0,Y.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,Y.jsx)(pe,{className:`h-3.5 w-3.5`})})]})]}),f===n.url&&(0,Y.jsxs)(`div`,{className:`space-y-2 rounded border border-destructive/40 bg-destructive/5 p-2`,children:[(0,Y.jsxs)(`p`,{className:`text-xs`,children:[`This is the object's `,(0,Y.jsx)(`strong`,{children:`last`}),` location. Remove the bytes from the backend and…`]}),(0,Y.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Y.jsx)(K,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!1),children:`Also remove index entry`}),(0,Y.jsx)(K,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Y.jsx)(K,{variant:`ghost`,size:`sm`,onClick:()=>p(null),children:`Cancel`})]})]})]},n.url)}),m&&(0,fo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Y.jsx)(eu,{workspaceId:t,documentCount:1,initialMode:m,defaultFilename:E,saving:g,onConfirm:C,onClose:()=>{g||h(null)}})}),window.document.body)]})}function xd(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 Sd(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 Cd(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&&Sd(e,t,n.points)}function wd(e,t,n=!1){let r=xd(e);return r?Cd(r.lat,r.lon,t):n}var Td=(0,q.lazy)(()=>s(()=>import(`./LocationTab-BONJQfYM.js`),__vite__mapDeps([27,3,4,28,29]))),Ed=[{id:`view`,label:`View`,icon:ut},{id:`location`,label:`Location`,icon:H},{id:`metadata`,label:`Metadata`,icon:f},{id:`json`,label:`JSON`,icon:he},{id:`synapses`,label:`Synapses`,icon:Ze},{id:`backends`,label:`Backends`,icon:ft}];function Dd({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=Xn()!=null,d=xd(e),f=Ed.filter(e=>(e.id!==`location`||d!==null)&&(!u||![`synapses`,`backends`].includes(e.id))),[p,m]=(0,q.useState)(n),h=`${e.id}:${n}`,[g,_]=(0,q.useState)(h);h!==g&&(_(h),m(n));let v=f.some(e=>e.id===p)?p:`view`,y=e=>{m(e),l?.(e)},b=o&&!!c&&!s,x=(0,Y.jsx)(`div`,{className:U(b&&`document-detail-header shrink-0 border-b-[3px] bg-muted`),children:(0,Y.jsxs)(`div`,{className:U(`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,Y.jsx)(Al,{tabs:f,active:v,onChange:y,className:U(`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,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col ${a}`,children:[s?(0,Y.jsx)(kl,{...s,tabs:x,section:v,onDocument:()=>y(`view`),onSection:()=>y(`view`),onBack:v===`view`?s.onBack:()=>y(`view`)}):x,(0,Y.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:(0,Y.jsxs)(`div`,{className:`mx-auto h-full w-full max-w-[var(--document-reading-width,100%)] p-4`,children:[v===`view`&&(0,Y.jsx)(dd,{document:e,workspaceId:t,initialEdit:r&&!u,onChanged:i}),v===`location`&&d&&(0,Y.jsx)(q.Suspense,{fallback:(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading map…`}),children:(0,Y.jsx)(Td,{lat:d.lat,lon:d.lon})}),v===`metadata`&&(0,Y.jsx)(hd,{document:e,workspaceId:t}),v===`json`&&(0,Y.jsx)(gd,{document:e,workspaceId:t}),v===`synapses`&&!u&&(0,Y.jsx)(_d,{document:e,workspaceId:t}),v===`backends`&&!u&&(0,Y.jsx)(bd,{document:e,workspaceId:t,onChanged:i})]})})]})}function Od(e,t){let[n,r]=(0,q.useState)(null),i=t?.id??null,a=`${e}:${i}`,[o,s]=(0,q.useState)(a);a!==o&&(s(a),r(null));let c=(0,q.useRef)(a),l=(0,q.useRef)(0);(0,q.useEffect)(()=>(c.current=a,l.current++,()=>{c.current=``}),[a]);let u=n?.id??i,d=(0,q.useCallback)(t=>{if(!e||u==null||c.current!==a)return;let n=++l.current;if(t){r(t);return}Sn(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}function kd(e){return e.schema===`data/schema/note`?st:e.schema===`data/schema/tab`?Ue:e.schema===`data/schema/file`?nt:e.schema===`data/schema/message/email`?B:it}function Ad({entry:e,onClose:t,frame:n}={}){let r=ed(),i=e??r.entry,a=t??r.close,{document:o,refresh:s}=Od(i?.workspaceId,i?.document??null);if(!i||!o)return!e&&(r.loading||r.error)?(0,Y.jsxs)(`div`,{className:`flex h-full w-full flex-col overflow-hidden rounded-(--card-radius) border bg-card`,children:[(0,Y.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,Y.jsx)(`span`,{className:`text-sm`,children:`Document`}),(0,Y.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,Y.jsx)(E,{className:`h-4 w-4`})})]}),(0,Y.jsxs)(`div`,{className:`p-4 text-sm`,role:r.error?`alert`:`status`,children:[r.error||`Loading document…`,r.error&&(0,Y.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,Y.jsx)(Tl,{title:Gt(o).title,icon:kd(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:dc(o)===ps,maximized:e?void 0:r.location?.maximized,onMaximizedChange:e?void 0:e=>r.update?.({maximized:e}),children:t=>(0,Y.jsx)(`div`,{className:`document-side-content h-full min-h-0 min-w-0 w-full`,children:(0,Y.jsx)(Dd,{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 jd=320,Md=1600;function Nd({edge:e}){let t=Uo(),n=(0,q.useRef)(null),r=e===`left`?-1:1;return(0,Y.jsx)(`div`,{role:`separator`,"aria-label":`Resize document reader`,"aria-orientation":`vertical`,"aria-valuemin":jd,"aria-valuemax":Md,"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(jd,i)},t.currentTarget.setPointerCapture(t.pointerId)},onPointerMove:e=>{n.current&&Ho(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:()=>Ho(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`?Ho(null):Ho(t.getBoundingClientRect().width+(e.key===`ArrowRight`?1:-1)*r*(e.shiftKey?64:16))}})}function Pd(e){let t=Po(),n=qo(),r=ed();return!e.enabled||!e.workspaceId||!t||n||r.location?e.children:(0,Y.jsx)(Fd,{...e,workspaceId:e.workspaceId},e.scope)}function Fd({workspaceId:e,scope:t,documents:n,loading:r,children:i}){let a=Uo(),o=`canvas:readerSelection:${t}`,[s,c]=(0,q.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,q.useCallback)((t,n)=>{if(n===e){c(t.id);try{sessionStorage.setItem(o,String(t.id))}catch{}}},[e,o]),d=(0,q.useMemo)(()=>({entry:l?{document:l,workspaceId:e}:null,alwaysOn:!0,open:u,preview:u,replace:u,close:()=>{}}),[l,e,u]);return(0,Y.jsx)(Qu.Provider,{value:d,children:(0,Y.jsxs)(`div`,{"data-always-reader":!0,className:`flex h-full min-h-0 min-w-0 flex-1 gap-shell`,children:[(0,Y.jsx)(`div`,{className:`min-h-0 min-w-0 flex-1 overflow-auto`,children:i}),(0,Y.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,Y.jsx)(Nd,{edge:`left`}),l?(0,Y.jsx)(Ad,{},`${e}:${l.id}`):(0,Y.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 Id(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 Ld(e){return`/workspaces/${e}/hooks`}async function Rd(e){return await G.get(Ld(e))||[]}async function zd(e,t){return(await G.get(`${Ld(e)}/${t}`))?.content??``}async function Bd(e,t,n){await G.put(`${Ld(e)}/${t}`,{content:n})}async function Vd(e,t){await G.delete(`${Ld(e)}/${t}`)}var Hd=[`example-`,`disabled-`,`_`];function Ud(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function Wd(e){return Hd.find(t=>e.startsWith(t))??null}function Gd(e){return Wd(Ud(e).base)===null}function Kd(e){return Ud(e).base.startsWith(`example-`)}function qd(e){let{dir:t,base:n}=Ud(e),r=Wd(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function Jd(e,t,n){if(Gd(t)===n)return t;let r=qd(t);return await Bd(e,r,await zd(e,t)),await Vd(e,t),r}function Yd(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 Xd(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function Zd(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function Qd(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 $d(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 ef(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var tf=`rules.json`;async function nf(e){try{let t=await zd(e,tf),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function rf(e,t){await Bd(e,tf,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
14
|
+
`)}async function af(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 G.get(`${Ld(e)}/pending${r?`?${r}`:``}`)||[]}async function of(e,t){return await G.post(`${Ld(e)}/pending/decisions`,t)}async function sf(e,t){return await G.get(`${Ld(e)}/runs/${encodeURIComponent(t)}`)}async function cf(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 G.get(`${Ld(e)}/runs${r?`?${r}`:``}`)||[]}var lf=1e4,uf=`canvas.hooks.backfillLimit`;function df(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?100:Math.min(t,lf)}function ff(){try{let e=localStorage.getItem(uf);return e?df(e):100}catch{return 100}}function pf(e){let t=df(e);try{localStorage.setItem(uf,String(t))}catch{}return t}function mf(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 hf(e,t){return await G.post(`${Ld(e)}/backfill`,t)}async function gf(e,t){return await G.post(`${Ld(e)}/run`,t)}async function _f(e,t){return await G.post(`${Ld(e)}/runs/${t}/replay`,{})}async function vf(e){return await G.get(`${Ld(e)}/meta`)}async function yf(e,t){return await G.post(`${Ld(e)}/generate`,t)}async function bf(e,t){let n=await zd(e,tf),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 Bd(e,tf,JSON.stringify(o,null,2)+`
|
|
15
|
+
`)}var xf=bf;function Sf(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 Cf(){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 wf(){let[e]=(0,q.useState)(Cf);return(0,q.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 Tf(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 Ef(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 Df=e=>typeof e==`string`?e:``,Of=e=>e&&typeof e==`object`?e:{},kf=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);function Af(e){let t=e.data||{},n=e.schema===`data/schema/message/email`,r=!n&&e.schema.startsWith(`data/schema/message`),i=Df(t.platform),a=Df(Of(t.channel).id)||Df(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=Df(Of(t.from).address)||Df(t.from);e&&s(`sender`,`Mail from ${e}`,{from:{equals:e}}),t.subject&&s(`subject`,`Subject matches regex`,{subject:{regex:kf(t.subject)}})}else if(r){let e=Df(Of(t.sender).id)||Df(Of(t.sender).username)||Df(Of(t.sender).name)||Df(t.sender),n=Df(Of(t.sender).name)||Df(Of(t.sender).username)||e;e&&s(`sender`,`Messages from ${n}`,{...c,sender:{equals:e}})}let l=Df(t.body)||Df(t.text)||Df(t.content)||Df(t.bodyHtml)||Df(t.bodyPreview);if((n||r||l)&&s(`body`,n?`Email body matches regex`:`Text matches regex`,{...c,body:{regex:kf(l.slice(0,160))}}),r){let n=Df(t.threadId)||([`slack`,`teams`].includes(i)?Df(Of(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:kf(t.url)}}),s(`schema`,`All items of this type`,{}),o}function jf({label:e,onClose:t,children:n}){return hc(t),(0,fo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-dialog flex items-center justify-center bg-scrim p-4`,onClick:t,children:(0,Y.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 Mf(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 Nf(e){return`/workspaces/${e}/scripts`}async function Pf(e){return await G.get(Nf(e))||[]}async function Ff(e,t){return(await G.get(`${Nf(e)}/${t}`))?.content??``}async function If(e,t,n){await G.put(`${Nf(e)}/${t}`,{content:n})}async function Lf(e,t){await G.delete(`${Nf(e)}/${t}`)}function Rf({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,q.useState)(!1),h=e.match(/^(.*?):\/\//)?.[0]||``,_=h?e.slice(h.length):e;return(0,Y.jsxs)(`div`,{className:U(`flex gap-2`,u),children:[f===`breadcrumbs`?(0,Y.jsx)(ul,{items:dl(_,h.replace(`://`,``)||r||`Workspace`),onNavigate:e=>t(h?`${h}${e.replace(/^\/+/,``)}`:e),disabled:l,className:U(`rounded border px-1`,d)}):(0,Y.jsx)(W,{id:c,value:e,onChange:e=>t(e.target.value),placeholder:s,disabled:l,className:U(`font-mono`,d)}),(0,Y.jsx)(K,{type:`button`,variant:`outline`,size:`icon`,onClick:()=>m(!0),disabled:l,"aria-label":`Browse tree paths`,title:`Browse…`,className:`shrink-0`,children:(0,Y.jsx)(g,{className:`h-4 w-4`})}),p&&(0,Y.jsx)(Yl,{onClose:()=>m(!1),children:(0,Y.jsx)(Sl,{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 zf=[{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`}],Bf=[{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.`}],Vf=[{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`}],Hf=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),Uf=e=>Hf.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),Wf=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:B,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:B,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:B,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:Qe,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:Qe,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:Ge,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`}],Gf=e=>Wf.find(t=>t.key===e)||Wf[1],Kf=`{{title}}{{ext}}`,qf=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,Jf=[{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.`}],Yf=[{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}),Xf={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[Z(`link`)]},Zf=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function Qf(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var $f=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),ep=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:B,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:()=>({...Xf,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:B,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:()=>({...Xf,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})=>({...Xf,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:ze,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})=>({...Xf,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:Qe,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:()=>({...Xf,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:B,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:()=>({...Xf,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})=>({...Xf,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:()=>({...Xf,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:Xe,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...Xf})}];function tp(e){let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field));if(t.length!==1||t[0].field!==`eventPathExact`)return null;let n=Zf(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function np(e){if(tp(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>Zf(e.value));return t.length>0&&t.every(e=>/^(dir|directory|backends):\//.test(e))}function rp(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=tp(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`?qf:e.b||`<filename>`].filter(Boolean).join(`/`)}}function ip(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=Hf.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:Zf(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${Vf.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${Vf.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[Uf(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=$f(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:$f(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:$f(r),...s,...i?{tags:$f(i)}:{}}),n.kind===`unlink`&&r&&o.push({action:`unlink`,paths:$f(r),...s}),n.kind===`tag`&&r&&o.push({action:`tag`,tags:$f(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&&!np(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`?Kf:n.storeName===`dated`?qf: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&&tp(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=$f(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:$f(i)}:{},...n.dlTags.trim()?{tags:$f(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||Qf(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 ap(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`&&Bf.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(Hf.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||tp(y)===null)||t.recursive===!0&&tp(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===Kf||e===qf?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===Kf?`title`:e===qf?`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(!Jf.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 op=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function sp(e,t=zf){let n=e.when,r=Xd(e).map(e=>Bf.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${op(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 cp(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 lp(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===Kf?`, named by title`:e.key===qf?`, 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=Jf.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=cp(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=cp(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function up(e){return(e.then||[]).map(lp).join(` · `)||`(no actions)`}function dp(e){return Zd(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function fp(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 pp(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 mp(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function hp(e){if(e.kind===`document`&&e.rule)return{...ap(e.rule)||Xf,id:null};if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...Xf,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{...Xf,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:np(r)}]}}return{...Xf,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 gp=`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,Y.jsxs)(`label`,{className:U(`flex min-w-0 flex-col gap-1.5`,r),children:[(0,Y.jsx)(`span`,{className:`text-sm font-medium`,children:e}),n,t&&(0,Y.jsx)(`span`,{className:`text-xs leading-relaxed text-muted-foreground`,children:t})]})}function _p({checked:e,onChange:t,label:n,hint:r,disabled:i}){return(0,Y.jsxs)(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:i,onClick:()=>t(!e),className:U(`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,Y.jsx)(`span`,{className:U(`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,Y.jsx)(`span`,{className:U(`h-4 w-4 rounded-full bg-background shadow transition-transform`,e&&`translate-x-4`)})}),(0,Y.jsxs)(`span`,{className:`min-w-0`,children:[(0,Y.jsx)(`span`,{className:`block text-sm font-medium`,children:n}),r&&(0,Y.jsx)(`span`,{className:`block text-xs leading-relaxed text-muted-foreground`,children:r})]})]})}function vp({value:e,options:t,onChange:n}){return(0,Y.jsx)(`div`,{className:`inline-flex h-10 rounded-md border bg-background p-1`,children:t.map(t=>(0,Y.jsx)(`button`,{type:`button`,onClick:()=>n(t.value),className:U(`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 yp({active:e,onClick:t,children:n,title:r}){return(0,Y.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:U(`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 bp({step:e,title:t,hint:n}){return(0,Y.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Y.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,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h3`,{className:`text-base font-semibold leading-7`,children:t}),n&&(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:n})]})]})}function xp({icon:e,tone:t,size:n=`md`}){return(0,Y.jsx)(`span`,{className:U(`inline-flex shrink-0 items-center justify-center rounded-xl`,n===`lg`?`h-12 w-12`:`h-10 w-10`,t),children:(0,Y.jsx)(e,{className:n===`lg`?`h-6 w-6`:`h-5 w-5`})})}function Sp({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:i,onPrefillConsumed:a,createOnly:o=!1,onCreated:s,onCancel:c}){let{showToast:l}=Ct(),[u,d]=(0,q.useState)([]),[f,p]=(0,q.useState)({}),m=e=>{cf(e,{limit:500}).then(e=>p(fp(e))).catch(()=>p({}))},[h,_]=(0,q.useState)(!0),[v,y]=(0,q.useState)(null),[b,x]=(0,q.useState)(!1),[S,C]=(0,q.useState)(!1),[w,T]=(0,q.useState)([]),[D,O]=(0,q.useState)([]),[j,ee]=(0,q.useState)([]),[M,N]=(0,q.useState)(``),P=(0,q.useRef)(null),[F,I]=(0,q.useState)(e);e!==F&&(I(e),_(!0)),(0,q.useEffect)(()=>{nf(e).then(e=>d(e)).finally(()=>_(!1)),m(e)},[e]);let[L,te]=(0,q.useState)(null);i!==L&&(te(i),i&&(y(hp(i)),x(!1))),(0,q.useEffect)(()=>{i&&a?.()},[i,a]),(0,q.useEffect)(()=>{Pf(e).then(e=>T(e.map(e=>e.path))).catch(()=>T([]))},[e]),(0,q.useEffect)(()=>{let t=!1;return Nl(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,q.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=mp(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,q.useState)(zf);(0,q.useEffect)(()=>{vf(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 rf(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=ip(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 bf(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,q.useState)(null),de=async t=>{ue(t);try{let n=await hf(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 hf(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:mp(D)})),x(!1),requestAnimationFrame(()=>P.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},me=e=>{let n=ap(e);n?(y(n),x(!1),requestAnimationFrame(()=>P.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[ge,_e]=(0,q.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=Qd(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,Y.jsxs)(K,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>_e({target:e,index:t}),children:[(0,Y.jsx)(g,{className:`h-4 w-4 sm:mr-1.5`}),(0,Y.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),xe=np(v?.conditions||[]),Se=!!v?.conditions.some(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&e.value.trim()),B=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,Y.jsxs)(`select`,{className:gp,value:e,onChange:e=>t(e.target.value),children:[(0,Y.jsx)(`option`,{value:``,children:n}),D.map(e=>(0,Y.jsx)(`option`,{value:e.address,children:B(e)},e.address)),e&&!D.some(t=>t.address===e)&&(0,Y.jsx)(`option`,{value:e,children:e})]}):(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),we=u.filter(dp),Ee=u.filter(e=>!dp(e)),De=({rule:e})=>{let t=e.enabled!==!1,r=ap(e)!==null,i=f[e.id],a=Gf(e.then?.[0]?.action||`link`),o=Zd(e);return(0,Y.jsxs)(`div`,{className:U(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,Y.jsx)(xp,{icon:a.icon,tone:a.tone}),(0,Y.jsxs)(`div`,{className:`rule-card-content min-w-0 space-y-1.5`,children:[(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,Y.jsx)(`h3`,{className:`text-base font-semibold leading-6`,children:e.description||e.id}),e.approval===!0&&(0,Y.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,Y.jsx)(`span`,{className:`rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground`,children:`incl. automation-created`}),!r&&(0,Y.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,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:sp(e,re)}),(0,Y.jsxs)(`p`,{className:`flex items-start gap-1.5 text-sm`,children:[(0,Y.jsx)(Te,{className:`mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground`}),(0,Y.jsx)(`span`,{children:up(e)})]}),o.length>0&&(0,Y.jsx)(`p`,{className:`truncate font-mono text-xs text-muted-foreground`,title:o.join(` | `),children:o.join(` | `)}),(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i?(0,Y.jsxs)(`button`,{type:`button`,className:U(`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,` `,pp(i.last.ts)]}):`not run yet`})]}),(0,Y.jsxs)(`div`,{className:`rule-card-actions`,children:[(0,Y.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:U(`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,Y.jsx)(`span`,{className:U(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,Y.jsxs)(K,{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,Y.jsx)(lt,{className:`h-4 w-4 animate-spin`}):(0,Y.jsx)(A,{className:`h-4 w-4`}),(0,Y.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Apply`})]}),(0,Y.jsxs)(K,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>me(e),children:[r?(0,Y.jsx)(k,{className:`h-4 w-4`}):(0,Y.jsx)(he,{className:`h-4 w-4`}),(0,Y.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,Y.jsx)(K,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>se(e.id),children:(0,Y.jsx)(pe,{className:`h-4 w-4`})})]})]})},Oe=(0,Y.jsxs)(`div`,{className:`space-y-3`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Y.jsx)(`h3`,{className:`text-base font-semibold`,children:`What should happen automatically?`}),b&&(0,Y.jsxs)(K,{size:`sm`,variant:`ghost`,onClick:()=>x(!1),children:[(0,Y.jsx)(E,{className:`mr-1 h-4 w-4`}),` Close`]})]}),(0,Y.jsx)(`div`,{className:`grid min-w-0 grid-cols-[repeat(auto-fill,minmax(min(100%,17rem),1fr))] gap-3`,children:ep.map(e=>(0,Y.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,Y.jsx)(xp,{icon:e.icon,tone:e.tone,size:`lg`}),(0,Y.jsxs)(`span`,{className:`min-w-0`,children:[(0,Y.jsx)(`span`,{className:`block text-base font-semibold leading-6`,children:e.title}),(0,Y.jsx)(`span`,{className:`mt-1 block break-words text-sm leading-relaxed text-muted-foreground`,children:e.blurb})]})]},e.id))})]});return(0,Y.jsxs)(`div`,{className:`rule-builder min-w-0 space-y-5`,children:[!o&&(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 flex-[1_1_20rem]`,children:[(0,Y.jsx)(`h2`,{className:`text-lg font-semibold`,children:`Rules`}),(0,Y.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`Rules run automatically as items arrive or get filed — no code needed. Stored in`,` `,(0,Y.jsx)(`span`,{className:`font-mono`,children:`rules.json`}),` in the workspace git.`]})]}),(0,Y.jsxs)(`div`,{className:`flex shrink-0 gap-2`,children:[t&&(0,Y.jsxs)(K,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,Y.jsx)(he,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,Y.jsxs)(K,{onClick:()=>{y(null),x(!0)},disabled:b,children:[(0,Y.jsx)(Re,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),b&&!v&&Oe,v&&(0,Y.jsxs)(`div`,{ref:P,className:`scroll-mt-4 space-y-6 rounded-xl border bg-card p-4 sm:p-6`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Y.jsx)(`h3`,{className:`text-lg font-semibold`,children:v.id?`Edit rule`:`New rule`}),(0,Y.jsxs)(K,{variant:`ghost`,size:`sm`,onClick:()=>y(null),children:[(0,Y.jsx)(E,{className:`mr-1 h-4 w-4`}),` Cancel`]})]}),(0,Y.jsx)($,{label:`Name`,hint:`Shown in the list and the run log.`,children:(0,Y.jsx)(W,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:v.description,onChange:e=>z(`description`,e.target.value)})}),(0,Y.jsxs)(`section`,{className:`space-y-4`,children:[(0,Y.jsx)(bp,{step:1,title:`When…`,hint:`What the rule reacts to. All conditions must match; repeat a condition for either/or.`}),(0,Y.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-[minmax(0,220px)_1fr]`,children:[(0,Y.jsx)($,{label:`Item`,children:(0,Y.jsxs)(`select`,{className:gp,value:v.schema,onChange:e=>z(`schema`,e.target.value),children:[re.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value)),v.schema&&!re.some(e=>e.value===v.schema)&&(0,Y.jsx)(`option`,{value:v.schema,children:v.schema.replace(/^data\/schema\//,``)})]})}),(0,Y.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,Y.jsxs)(`span`,{className:`text-sm font-medium`,children:[`Event `,(0,Y.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(any of)`})]}),(0,Y.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Bf.map(e=>{let t=v.events.includes(e.value);return(0,Y.jsx)(yp,{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,Y.jsx)(`div`,{className:`space-y-2`,children:v.conditions.map((e,t)=>{let n=Vf.find(t=>t.key===e.field);return(0,Y.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,Y.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=>Uf(t.field)===Uf(e.field))?`or`:`and`}),(0,Y.jsx)(`select`,{className:gp,value:e.field,onChange:e=>z(`conditions`,v.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:Vf.map(e=>(0,Y.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,Y.jsxs)(`div`,{className:`order-4 col-span-3 flex gap-2 sm:order-3 sm:col-span-1`,children:[(0,Y.jsx)(W,{className:U(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,Y.jsx)(K,{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,Y.jsx)(E,{className:`h-4 w-4`})})]},t)})}),(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Y.jsxs)(K,{size:`sm`,variant:`outline`,onClick:()=>z(`conditions`,[...v.conditions,{field:v.schema===`email`?`from`:`path`,value:``}]),children:[(0,Y.jsx)(Re,{className:`mr-1 h-4 w-4`}),` Add condition`]}),(0,Y.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,Y.jsx)(`span`,{className:`font-mono`,children:`|`}),`, e.g. `,(0,Y.jsx)(`span`,{className:`font-mono`,children:`image/* | video/*`}),`.`]})]})]}),(0,Y.jsxs)(`section`,{className:`space-y-4`,children:[(0,Y.jsx)(bp,{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=Gf(t.kind),c=n=>(0,Y.jsxs)(`div`,{className:`space-y-3 rounded-lg border border-dashed p-3`,children:[(0,Y.jsxs)(`p`,{className:`text-sm font-medium`,children:[`What to do with the `,n]}),(0,Y.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Y.jsx)($,{label:`Save as a note at`,hint:`Context path by default, dir:/path for the directory tree.`,children:(0,Y.jsx)(Rf,{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,Y.jsx)($,{label:`Note title`,children:(0,Y.jsx)(W,{className:Q,placeholder:`Summary: {{doc.data.subject}}`,value:t.noteTitle,onChange:e=>r({noteTitle:e.target.value})})}),(0,Y.jsx)($,{label:`Save as a file at`,hint:`Relative path under the workspace home folder or in the data blob store.`,children:(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`logs/agent.log (optional)`,value:t.filePath,onChange:e=>r({filePath:e.target.value})})}),t.filePath.trim()&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)($,{label:`File lives in`,children:(0,Y.jsxs)(`select`,{className:gp,value:t.fileBackend,onChange:e=>r({fileBackend:e.target.value}),children:[(0,Y.jsx)(`option`,{value:`home`,children:`the workspace home folder`}),(0,Y.jsx)(`option`,{value:`data`,children:`the data blob store`})]})}),(0,Y.jsx)($,{label:`Also file the saved file under`,hint:`Index it as a document at this tree path.`,children:(0,Y.jsx)(Rf,{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,Y.jsx)(_p,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send me a notification with the result`})]}),l=tp(v.conditions),u=t.kind===`store`&&t.a&&(!t.recursive||o)?rp(t,v.conditions,i):null,d=t.kind===`extractAttachments`&&t.a?Mf(t.a,t.storeFolder,t.attachmentPath):null;return(0,Y.jsxs)(`div`,{className:`space-y-4 rounded-xl border bg-background p-4`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Y.jsx)(xp,{icon:s.icon,tone:s.tone}),(0,Y.jsx)(`select`,{className:U(gp,`flex-1 font-medium`),value:t.kind,onChange:e=>r(Z(e.target.value)),children:Wf.map(e=>(0,Y.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,Y.jsx)(K,{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,Y.jsx)(E,{className:`h-4 w-4`})})]}),(t.kind===`link`||t.kind===`unlink`)&&(0,Y.jsxs)(`div`,{className:`space-y-3`,children:[(0,Y.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,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(W,{className:U(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,Y.jsx)($,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,Y.jsx)(_p,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:Se?`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:!Se})]}),t.kind===`moveMessage`&&(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.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,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`INBOX/Accounting/{{YYYY}}/Expenses`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,Y.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,Y.jsx)($,{label:`Tags`,hint:`Comma-separated.`,children:(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`urgent, follow-up`,value:t.a,onChange:e=>r({a:e.target.value})})}),t.kind===`store`&&(0,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Y.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,Y.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,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),be(`storeFolder`,n,`Browse storage backends`)]})}),(0,Y.jsx)($,{label:`File name`,children:(0,Y.jsx)(`select`,{className:gp,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:Yf.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),(0,Y.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,Y.jsx)(vp,{value:t.storeMode,onChange:e=>r({storeMode:e}),options:[{value:`copy`,label:`Copy`},{value:`move`,label:`Move`}]})}),t.storeMode===`move`&&(0,Y.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,Y.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,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,Y.jsx)(_p,{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,Y.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,Y.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,Y.jsxs)(`span`,{className:`break-all font-mono`,children:[u.root,`/`]})]}),t.recursive&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,Y.jsxs)(`span`,{className:`break-all font-mono`,children:[u.recreated||`(root)`,`/`]})]}),(0,Y.jsx)(`p`,{className:`break-all font-mono`,children:u.result})]}),(0,Y.jsxs)(`details`,{className:`group rounded-lg border`,children:[(0,Y.jsxs)(`summary`,{className:`flex cursor-pointer select-none items-center gap-2 px-3 py-2 text-sm font-medium`,children:[(0,Y.jsx)(ce,{className:`h-4 w-4 transition-transform group-open:rotate-180`}),` More options`]}),(0,Y.jsxs)(`div`,{className:`grid gap-4 border-t p-3 sm:grid-cols-2`,children:[t.storeMode===`copy`&&(0,Y.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,Y.jsx)($,{label:`If the name is already taken`,children:(0,Y.jsxs)(`select`,{className:gp,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,Y.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,Y.jsx)(`option`,{value:`error`,children:`skip the file`}),(0,Y.jsx)(`option`,{value:`overwrite`,children:`overwrite the existing file`})]})})]})]}),(0,Y.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,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Y.jsx)($,{label:`Attachment types`,hint:`MIME types, comma-separated. application/pdf for PDFs, image/* for images, or * for all.`,children:(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`application/pdf`,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,Y.jsx)($,{label:`Attachment filename contains`,hint:`Optional: invoice, faktura, or another literal filename fragment. Every selected attachment must also match its type.`,children:(0,Y.jsx)(W,{className:Q,placeholder:`Any matching filename`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})}),(0,Y.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,Y.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,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),be(`storeFolder`,n,`Browse storage backends`)]})}),(0,Y.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,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`No subfolders`,value:t.attachmentPath,onChange:e=>r({attachmentPath:e.target.value})})}),(0,Y.jsx)($,{label:`If the attachment name is already taken`,children:(0,Y.jsxs)(`select`,{className:gp,value:t.storeConflict,onChange:e=>r({storeConflict:e.target.value}),children:[(0,Y.jsx)(`option`,{value:`rename`,children:`add -1, -2, … to the name`}),(0,Y.jsx)(`option`,{value:`error`,children:`skip the file and report the conflict`})]})})]}),!a&&(0,Y.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,Y.jsxs)(`div`,{className:`space-y-1.5 rounded-lg bg-muted/60 px-3 py-3 text-sm`,"aria-live":`polite`,children:[(0,Y.jsx)(`p`,{className:`font-medium`,children:`Destination preview`}),(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Example email dated `,d.date,`. Each email supplies its own date.`]}),(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Root folder: `,(0,Y.jsxs)(`span`,{className:`break-all font-mono`,children:[d.root,`/`]})]}),(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Path added beneath it: `,(0,Y.jsx)(`span`,{className:`break-all font-mono`,children:d.added?`${d.added}/`:`(none)`})]}),(0,Y.jsx)(`p`,{className:`break-all font-mono`,children:d.result})]}),(0,Y.jsx)(_p,{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,Y.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,Y.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,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Y.jsx)($,{label:`Download`,hint:Jf.find(e=>e.value===t.dlKind)?.hint,children:(0,Y.jsx)(`select`,{className:gp,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:Jf.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value))})}),t.dlKind===`website`?(0,Y.jsx)($,{label:`Mirror depth`,hint:`How many link hops to follow on the same site (1–5).`,children:(0,Y.jsx)(W,{type:`number`,min:1,max:5,className:U(Q,`sm:max-w-32`),value:t.dlDepth,onChange:e=>r({dlDepth:e.target.value})})}):(0,Y.jsx)(`div`,{className:`hidden sm:block`}),(0,Y.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,Y.jsx)($,{label:`Folder on that backend`,hint:`Relative to the backend root.`,children:(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),be(`storeFolder`,n,`Browse storage backends`)]})}),(0,Y.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,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),be(`action`,n)]})}),(0,Y.jsx)($,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,Y.jsx)(W,{className:U(Q,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,Y.jsx)(_p,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:Se?`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:!Se}),(0,Y.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,Y.jsx)(`span`,{className:`font-mono`,children:`yt-dlp`}),`, pages and websites `,(0,Y.jsx)(`span`,{className:`font-mono`,children:`wget`}),` on the server.`]})]}),t.kind===`unstore`&&(0,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Y.jsx)($,{label:`Delete the file from`,children:Ce(t.a,e=>r({a:e}),`pick a backend…`,`workspace:data`)}),(0,Y.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,Y.jsx)(_p,{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,Y.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,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsx)($,{label:`Files to send`,children:(0,Y.jsxs)(`select`,{className:gp,value:t.sendSource,onChange:e=>r({sendSource:e.target.value}),children:[(0,Y.jsx)(`option`,{value:`document`,children:`The file that triggered this rule`}),(0,Y.jsx)(`option`,{value:`attachments`,children:`Matching attachments from the email`}),(0,Y.jsx)(`option`,{value:`download`,children:`Files from an earlier Download action`})]})}),t.sendSource===`attachments`&&(0,Y.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Y.jsx)($,{label:`Attachment types`,hint:`application/pdf for invoices; * for all files.`,children:(0,Y.jsx)(W,{className:Q,value:t.attachmentMime,onChange:e=>r({attachmentMime:e.target.value})})}),(0,Y.jsx)($,{label:`Attachment filename contains`,hint:`Optional literal filename fragment.`,children:(0,Y.jsx)(W,{className:Q,placeholder:`invoice`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})})]}),t.sendSource===`attachments`&&(0,Y.jsx)(_p,{checked:t.includeInline,onChange:e=>r({includeInline:e}),label:`Include inline attachments`,hint:`Signature images are excluded by default.`}),(0,Y.jsx)($,{label:`Sending account`,hint:`Enable sending for the account in Connected services.`,children:(0,Y.jsxs)(`select`,{className:gp,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,Y.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,Y.jsxs)(`option`,{value:`${t.sendDriver}:${t.a}`,disabled:!0,children:[t.sendDriver,`: `,t.a,` (unavailable)`]}),j.map(e=>(0,Y.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,Y.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:M}),(0,Y.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,Y.jsx)(W,{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,Y.jsx)($,{label:`Email subject`,hint:`{{file.name}} inserts the attachment filename.`,children:(0,Y.jsx)(W,{className:Q,value:t.sendSubject,onChange:e=>r({sendSubject:e.target.value})})}),(0,Y.jsx)($,{label:t.sendDriver===`imap`?`Email body (optional)`:`Message / caption (optional)`,hint:`Templates: {{file.name}}, {{doc.data.subject}}, {{doc.data.title}}.`,children:(0,Y.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,Y.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,Y.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,Y.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,Y.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,Y.jsx)(W,{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,Y.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,Y.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,Y.jsxs)(`div`,{className:`space-y-3`,children:[(0,Y.jsx)($,{label:`Agent`,hint:`The agent's slug.`,children:(0,Y.jsx)(W,{className:U(Q,`font-mono sm:max-w-xs`),placeholder:`assistant`,value:t.a,onChange:e=>r({a:e.target.value})})}),(0,Y.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,Y.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,Y.jsxs)(`div`,{className:`space-y-3`,children:[(0,Y.jsx)($,{label:`Script`,hint:`From the Scripts section of this workspace.`,children:w.length?(0,Y.jsxs)(`select`,{className:U(gp,`font-mono sm:max-w-md`),value:t.a,onChange:e=>r({a:e.target.value}),children:[(0,Y.jsx)(`option`,{value:``,children:`pick a script…`}),w.map(e=>(0,Y.jsx)(`option`,{value:`scripts/${e}`,children:e},e))]}):(0,Y.jsx)(W,{className:U(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,Y.jsxs)(K,{size:`sm`,variant:`outline`,onClick:()=>z(`actions`,[...v.actions,Z(`tag`)]),children:[(0,Y.jsx)(Re,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,Y.jsxs)(`section`,{className:`space-y-3`,children:[(0,Y.jsx)(bp,{step:3,title:`Options`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Y.jsx)(_p,{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,Y.jsx)(_p,{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,Y.jsxs)(`div`,{className:`flex flex-wrap gap-2 border-t pt-4`,children:[(0,Y.jsxs)(K,{className:`h-10 px-5`,onClick:oe,disabled:S||h,children:[S?(0,Y.jsx)(lt,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,Y.jsx)(ne,{className:`mr-1.5 h-4 w-4`}),` `,v.id?`Save changes`:`Create rule`]}),(0,Y.jsx)(K,{className:`h-10`,variant:`outline`,onClick:()=>{y(null),c?.()},children:`Cancel`})]})]}),ge&&(0,Y.jsx)(Yl,{onClose:()=>_e(null),children:(0,Y.jsx)(Sl,{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,Y.jsx)(`p`,{className:`rounded-xl border p-6 text-center text-sm text-muted-foreground`,children:`Loading…`}):u.length===0?!b&&!v&&(0,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{className:`rounded-xl border border-dashed p-6 text-center`,children:[(0,Y.jsx)(`p`,{className:`text-base font-medium`,children:`No rules yet`}),(0,Y.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,Y.jsxs)(`div`,{className:`space-y-6`,children:[we.length>0&&(0,Y.jsxs)(`section`,{className:`space-y-3`,children:[(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-2 gap-y-1 text-sm text-muted-foreground`,children:[(0,Y.jsxs)(`h3`,{className:`flex items-center gap-2 font-semibold uppercase tracking-wide`,children:[(0,Y.jsx)(Qe,{className:`h-4 w-4 shrink-0`}),` Folder & storage rules`]}),(0,Y.jsx)(`p`,{children:`Right-click a folder in the tree to add one`})]}),(0,Y.jsx)(`div`,{className:`space-y-3`,children:we.map(e=>(0,Y.jsx)(De,{rule:e},e.id))})]}),Ee.length>0&&(0,Y.jsxs)(`section`,{className:`space-y-3`,children:[we.length>0&&(0,Y.jsxs)(`h3`,{className:`flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground`,children:[(0,Y.jsx)(Xe,{className:`h-4 w-4`}),` Other rules`]}),(0,Y.jsx)(`div`,{className:`space-y-3`,children:Ee.map(e=>(0,Y.jsx)(De,{rule:e},e.id))})]})]}))]})}function Cp({workspaceId:e,document:t,onClose:n}){let[r,i]=(0,q.useState)(null),[a,o]=(0,q.useState)(``),[s,c]=(0,q.useState)(``);hc(n),(0,q.useEffect)(()=>{let n=!1;return(async()=>{if(!Ef(await Tt(e)))throw Error(`Only workspace administrators can create rules.`);let r=await Sn(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,q.useMemo)(()=>r?Af(r):[],[r]),u=l.find(e=>e.id===s)||l[0],d=(0,q.useMemo)(()=>u?{kind:`document`,rule:u.rule}:null,[u]);return(0,Y.jsx)(jf,{label:`Create rule`,onClose:n,children:(0,Y.jsxs)(`div`,{className:`p-5`,children:[(0,Y.jsxs)(`div`,{className:`mb-4 flex items-start justify-between gap-3`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`h2`,{id:`document-rule-title`,className:`text-lg font-semibold`,children:`Create rule`}),(0,Y.jsx)(`p`,{className:`truncate text-sm text-muted-foreground`,children:Gt(t).title})]}),(0,Y.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`rounded-md p-2 hover:bg-accent`,children:(0,Y.jsx)(E,{className:`h-4 w-4`})})]}),a?(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:a}):r?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`label`,{className:`mb-4 block space-y-2 text-sm font-medium`,children:[(0,Y.jsx)(`span`,{children:`Start with`}),(0,Y.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,Y.jsx)(`option`,{value:e.id,children:e.label},e.id))})]}),(0,Y.jsx)(Sp,{workspaceId:e,prefill:d,createOnly:!0,onCreated:n,onCancel:n})]}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading document…`})]})})}function wp(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 Tp(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 Ep(e,t,n,r){let i=new Set(r?n:[]);for(let n of t)Tp(e,n.bounds)&&i.add(n.id);return i}var Dp=`[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 Op(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=wp(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(Ep(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(Dp))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 kp({scope:e,selected:t,onSelectionChange:n,onContextMenu:r,children:i}){let a=(0,q.useRef)(null),o=(0,q.useRef)({selected:t,onSelectionChange:n});return(0,q.useLayoutEffect)(()=>{o.current={selected:t,onSelectionChange:n}},[t,n]),(0,q.useLayoutEffect)(()=>{if(a.current)return Op(a.current,{getSelection:()=>o.current.selected,onSelectionChange:e=>o.current.onSelectionChange(e)})},[e]),(0,Y.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 Ap(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 jp({workspaceId:e,ids:t,onClose:n,modal:r=!1}){let{showProgress:i}=Ct();hc(n,r);let[a]=(0,q.useState)(()=>{try{return Ap(e)}catch{return``}}),[o,s]=(0,q.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,q.useState)(!1),[u,d]=(0,q.useState)(``),f=(0,q.useRef)(!1),p=(0,q.useRef)(!1);(0,q.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 fn(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`:Jl,y=(0,Y.jsx)(Y.Fragment,{children:o?(0,Y.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,Y.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Copy to workspace`}),(0,Y.jsxs)(`p`,{className:`mt-3 break-words text-sm`,children:[o.target.workspaceName,`: `,o.paths.join(`, `)]}),(0,Y.jsxs)(`p`,{role:`status`,className:`mt-3 text-sm`,children:[o.index,` of `,o.ids.length,` copied`,_?`.`:c?`…`:` — paused.`]}),u&&(0,Y.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-destructive`,children:u}),(0,Y.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,Y.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,Y.jsxs)(`div`,{className:`mt-auto flex flex-wrap justify-end gap-2 pt-4`,children:[!_&&!c&&(0,Y.jsx)(K,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(a)}catch{}s(null),d(``)},children:`Discard remaining`}),!_&&!c&&(0,Y.jsx)(K,{onClick:()=>void h(o),children:`Resume copy`}),(0,Y.jsx)(K,{variant:_?`default`:`outline`,onClick:g,children:_?`Done`:c?`Pause & close`:`Close`})]})]}):(0,Y.jsx)(Sl,{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,Y.jsx)(jf,{label:`Copy to workspace`,onClose:g,children:y}):(0,Y.jsx)(Yl,{onClose:g,children:y})}function Mp(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...Gn(e.data?.tags??[]),...Gn(t)])]}:{},...n?{geo:n}:{}}}function Np(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:Mp(e,t,n),...r===void 0?{}:{comment:r.trim()}}}function Pp({workspaceId:e,documentIds:t,onClose:n}){let[r,i]=(0,q.useState)([]),[a,o]=(0,q.useState)(null),[s,c]=(0,q.useState)(`keep`),[l,u]=(0,q.useState)(``),d=(r.length>0||!!a||s!==`keep`)&&(s!==`replace`||l.trim().length>0),[f,p]=(0,q.useState)(t),[m,h]=(0,q.useState)(!1),[g,_]=(0,q.useState)(``);return hc(n,!m),(0,fo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-scrim p-4`,children:(0,Y.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,Y.jsxs)(`h2`,{id:`bulk-edit-title`,className:`font-semibold`,children:[`Bulk Edit · `,f.length,` documents`]}),(0,Y.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,Y.jsxs)(`fieldset`,{disabled:m,className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`span`,{className:`text-sm font-medium`,children:`Add tags`}),(0,Y.jsx)(tu,{tags:r,onChange:i,suggestions:[]})]}),(0,Y.jsx)(du,{value:a,onChange:o,idPrefix:`bulk-geo`}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`bulk-comment-mode`,className:`text-sm font-medium`,children:`Comment`}),(0,Y.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,Y.jsx)(`option`,{value:`keep`,children:`Keep existing comments`}),(0,Y.jsx)(`option`,{value:`replace`,children:`Replace comments`}),(0,Y.jsx)(`option`,{value:`clear`,children:`Clear comments`})]}),s===`replace`&&(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`label`,{htmlFor:`bulk-comment`,className:`sr-only`,children:`New comment for all selected documents`}),(0,Y.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,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This replaces the comment on every selected document.`})]}),s===`clear`&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`This removes the comment from every selected document.`})]})]}),g&&(0,Y.jsx)(`p`,{role:`alert`,className:`text-sm text-destructive`,children:g}),(0,Y.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Y.jsx)(K,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,Y.jsx)(K,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await Sn(e,n);await Mn(e,Np(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 Fp=e=>`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`;function Ip(e,t,n,r){return typeof e.sourcePath==`string`&&!!t&&e.sourceWorkspaceId===t&&!!n&&e.sourceTreeName===n&&Fp(e.sourcePath)===Fp(r)}function Lp({onClose:e,onConfirm:t,fixedWorkspaceName:n,saving:r=!1,sizeClassName:i}){let[a,o]=(0,q.useState)(n?`browse`:`workspace`),[s,c]=(0,q.useState)([]),[l,u]=(0,q.useState)(!n),[d,f]=(0,q.useState)(n??null),[p,m]=(0,q.useState)(`context`),[h,g]=(0,q.useState)(new Set),[_,v]=(0,q.useState)(n);return n!==_&&(v(n),n||u(!0)),(0,q.useEffect)(()=>{n||Kt().then(c).catch(()=>c([])).finally(()=>u(!1))},[n]),(0,Y.jsxs)(`div`,{className:U(`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,Y.jsxs)(`div`,{className:`flex h-12 shrink-0 items-center justify-between border-b px-4`,children:[(0,Y.jsxs)(`span`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,Y.jsx)(Ye,{className:`h-4 w-4`}),a===`workspace`?`Add existing documents…`:`Pick documents…`]}),(0,Y.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,Y.jsx)(E,{className:`h-4 w-4`})})]}),(0,Y.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,Y.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,Y.jsx)(`div`,{className:`flex min-w-0 flex-col overflow-y-auto p-2`,children:(0,Y.jsx)(bl,{workspaces:s,loading:l,onPick:e=>{f(e),g(new Set),o(`browse`)}})}),(0,Y.jsxs)(`div`,{className:`flex min-w-0 flex-col overflow-hidden`,children:[(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:[!n&&(0,Y.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,Y.jsx)(_t,{className:`h-4 w-4 rotate-180`})}),[`context`,`directory`].map(e=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>{m(e),g(new Set)},className:U(`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:[fl[e],pl[e]]},e))]}),d&&(0,Y.jsx)(xl,{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,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between border-t px-4 py-3`,children:[(0,Y.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[h.size,` document`,h.size===1?``:`s`,` selected`]}),(0,Y.jsx)(K,{size:`sm`,onClick:async()=>{!d||h.size===0||r||await t(Array.from(h),{workspaceName:d,treeName:p===`directory`?`directory`:On,treeType:p})},disabled:h.size===0||r,children:r?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(_o,{className:`mr-1.5 h-3.5 w-3.5`}),`Adding…`]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Ye,{className:`mr-1 h-3.5 w-3.5`}),`Add`]})})]})]})}function Rp(e){let{id:t,...n}=e;return n}var zp=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`div`,{className:`relative w-full overflow-auto`,children:(0,Y.jsx)(`table`,{ref:n,className:U(`w-full caption-bottom text-sm`,e),...t})}));zp.displayName=`Table`;var Bp=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`thead`,{ref:n,className:U(`[&_tr]:border-b`,e),...t}));Bp.displayName=`TableHeader`;var Vp=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`tbody`,{ref:n,className:U(`[&_tr:last-child]:border-0`,e),...t}));Vp.displayName=`TableBody`;var Hp=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`tfoot`,{ref:n,className:U(`border-t bg-muted/50 font-medium [&>tr]:last:border-b-0`,e),...t}));Hp.displayName=`TableFooter`;var Up=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`tr`,{ref:n,className:U(`border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted`,e),...t}));Up.displayName=`TableRow`;var Wp=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`th`,{ref:n,className:U(`h-12 px-2 md:px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0`,e),...t}));Wp.displayName=`TableHead`;var Gp=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`td`,{ref:n,className:U(`p-2 md:p-4 align-middle [&:has([role=checkbox])]:pr-0`,e),...t}));Gp.displayName=`TableCell`;var Kp=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`caption`,{ref:n,className:U(`mt-4 text-sm text-muted-foreground`,e),...t}));Kp.displayName=`TableCaption`;var qp=({label:e,sortKey:t,sort:n,onSort:r,className:i})=>{let a=n.key===t;return(0,Y.jsx)(Wp,{"aria-sort":a?n.dir===`asc`?`ascending`:`descending`:`none`,className:U(`cursor-pointer select-none hover:text-foreground transition-colors`,i),onClick:()=>r(t),children:(0,Y.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,a?n.dir===`asc`?(0,Y.jsx)(V,{className:`h-3.5 w-3.5`}):(0,Y.jsx)(De,{className:`h-3.5 w-3.5`}):(0,Y.jsx)(x,{className:`h-3.5 w-3.5 opacity-40`})]})})};qp.displayName=`SortableTableHead`;function Jp(e,t,n={key:null,dir:`asc`}){let[r,i]=q.useState(n);return{sorted:q.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:q.useCallback(e=>{i(t=>t.key===e?{key:e,dir:t.dir===`asc`?`desc`:`asc`}:{key:e,dir:`asc`})},[])}}var Yp=`canvas:documentOpenMode`;function Xp(){try{return localStorage.getItem(Yp)===`modal`?`modal`:`side`}catch{return`side`}}var Zp=Xp(),Qp=new Set;function $p(){return Zp}function em(e){try{localStorage.setItem(Yp,e)}catch{}Zp=e;for(let e of Qp)e()}function tm(e){Qp.add(e);let t=t=>{(t.key===Yp||t.key===null)&&(Zp=Xp(),e())};return window.addEventListener(`storage`,t),()=>{Qp.delete(e),window.removeEventListener(`storage`,t)}}function nm(){return(0,q.useSyncExternalStore)(tm,$p,()=>`side`)}function rm(e){let t=nm(),n=(0,q.useContext)(Qu),{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,q.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Y.jsx)(im,{...e})}function im({document:e,isOpen:t,onClose:n,workspaceId:r,initialTab:i,initialEdit:a}){let[o,s]=(0,q.useState)(!1),c=tr(),{document:l,refresh:u}=Od(r,e);if(hc(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,fo.createPortal)((0,Y.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:U(`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,Y.jsxs)(`div`,{className:U(`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,Y.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between p-4 pb-2`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`h2`,{className:`truncate text-lg font-bold`,children:Gt(l).title}),(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`ID: `,l.id,` · `,l.schema]})]}),(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1`,children:[(()=>{let e=At(l);return e?(0,Y.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,Y.jsx)(Ae,{className:`h-4 w-4`})}):null})(),(0,Y.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,Y.jsx)(ve,{className:`h-4 w-4`}):(0,Y.jsx)(Ke,{className:`h-4 w-4`})}),(0,Y.jsx)(`button`,{onClick:n,className:`rounded-sm p-2 hover:bg-muted`,title:`Close`,children:`✕`})]})]}),(0,Y.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,Y.jsx)(rs.Provider,{value:()=>s(e=>!e),children:(0,Y.jsx)(Dd,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var am={sortBy:`content`,order:`desc`};function om(e){return e?.sortBy===`crud:deleted`?{...am}:{sortBy:e?.sortBy??am.sortBy,order:e?.order??am.order}}var sm={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:{...am}};function cm(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function lm(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 um(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function dm(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=um(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 fm(e,t,n=[]){return{features:e.features,filters:[...dm(e.timeline),...cm(e.geo),...lm(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 pm=am,mm={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function hm(e){return mm[e]??e}function gm(e){let[t,n]=(0,q.useState)([]);return(0,q.useEffect)(()=>{let t=!1;return _n(e).then(e=>{t||n(e)}).catch(()=>{t||n([])}),()=>{t=!0}},[e]),(0,q.useMemo)(()=>[...new Set([`alphabetical`,`type`,`crud:created`,`crud:updated`,`content`,...t.filter(e=>e!==`crud:deleted`)])].map(e=>({value:e,label:hm(e)})),[t])}function _m({workspaceId:e,value:t,onChange:n}){let r=gm(e);return(0,Y.jsxs)(`div`,{className:`canvas-no-drag flex items-center gap-1`,children:[(0,Y.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,Y.jsx)(`option`,{value:t.sortBy,children:hm(t.sortBy)}),r.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value))]}),(0,Y.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,Y.jsx)(Se,{className:`h-3.5 w-3.5`}):(0,Y.jsx)(ke,{className:`h-3.5 w-3.5`})})]})}function vm(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 ym={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},bm=e=>e*1e6;function xm(){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 Sm(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Cm(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=Sm(e);return r.setDate(r.getDate()-n),r}var wm=864e5;function Tm(e){let t=xm(),n=Sm(e),r=Cm(e,t);return{today:n.getTime(),yesterday:n.getTime()-wm,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*wm,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function Em(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:bm(ym.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:bm(ym.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:bm(ym.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:bm(ym.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:bm(ym.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:bm(ym.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:bm(ym.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:bm(ym.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:bm(ym.year)+i}}function Dm(e,t,n=`desc`,r=new Date){let i=Tm(r),a=new Map;for(let n of e){let e=Em(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 Om(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 km(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function Am(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 jm=(e,t)=>`${yt.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Mm(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await G.get(`${jm(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 Nm(e,t,n){return Fm(e,t,n,`restore`)}function Pm(e,t,n){return Fm(e,t,n,`discard`)}async function Fm(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await G.post(`${jm(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{dn(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 Im(e,t){let n=Om(`backends`,t);if(!n?.backend)return;let{items:r}=await Mm(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 Nm(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 Lm(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 Rm(e,t){let n=Om(`backends`,t);if(!n?.backend)return;let{items:r}=await Mm(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!Lm(n.backend,i))return;let a=await Pm(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 zm(){let{showProgress:e}=Ct();return(0,q.useCallback)(async(t,n,r,i)=>{let a=e({title:t,description:n});try{let e=await i();if(e===!1)throw Error(`The operation could not be completed.`);return a.done({title:r,description:n}),e}catch(e){throw a.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`}),e}},[e])}var Bm=new Map;function Vm(e,t,n,r,i){let a=JSON.stringify([t,n,r]),o=Bm.get(a);if(o)return o;let s=(async()=>{let a=e({title:`Resyncing…`,description:r});try{for(await pn(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 Bm.set(a,s),s.finally(()=>{Bm.get(a)===s&&Bm.delete(a)}).catch(()=>{}),s}var Hm=[`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`],Um=new Map;function Wm(e,t,n){dn(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 Gm(e,t){let n=Um.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=Hm.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)dn(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return go.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)dn(e,t);a.forEach(([e,t])=>go.off(e,t))}},Um.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),Um.delete(e))}}function Km({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=zm(),{showProgress:a}=Ct(),o=n||`context`,c=o===`directory`,l=(0,q.useCallback)((e=150)=>{r&&setTimeout(r,e),t&&setTimeout(()=>window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:t}})),e)},[r,t]),u=(0,q.useCallback)(async(n,r=!0)=>{let i;if(e)i=await or(e,n,r);else if(t)i=await mn(t,n,r,o);else return!1;let a=Wc(n);if(i&&a)try{e?await er(e,n,a):t&&await kt(t,n,a,o)}catch{}return l(),i},[e,t,o,l]),d=(0,q.useCallback)(async(n,r=!1,a=!1,s=!1)=>i(s?`Destroying…`:a?`Purging…`:`Removing…`,n,s?`Destroyed`:a?`Purged`:`Removed`,async()=>{try{return e?await $n(e,n,r):t?await Et(t,n,r,o,a,s):!1}finally{l()}}),[e,t,o,l,i]),f=(0,q.useCallback)(async(n,r)=>{let i;if(e){let t=n.split(`/`);t[t.length-1]=r,i=await Qn(e,n,t.join(`/`),!1)}else if(t)i=await kt(t,n,{name:r},o);else return!1;return l(),i},[e,t,o,l]),p=(0,q.useCallback)(async(n,r,a=!1,s=o,c=o,u={})=>i(`Moving…`,`${n} → ${r}`,`Moved`,async()=>{let i;if(e)i=await Qn(e,n,r,a,u);else if(t)i=await Fn(t,n,r,a,s,c,u);else return!1;return l(),i}),[e,t,o,l,i]),m=(0,q.useCallback)(async n=>{let r;if(e)r=await nr(e,n);else if(t)r=await Ft(t,n,o);else return null;return l(),r},[e,t,o,l]),h=(0,q.useCallback)(async n=>{let r;if(e)r=await Zn(e,n);else if(t)r=await Cn(t,n,o);else return null;return l(),r},[e,t,o,l]),g=(0,q.useCallback)(async(n,r,a=!1,s=o,c=o)=>i(`Copying…`,`${n} → ${r}`,`Copied`,async()=>{let i;if(e)i=await ir(e,n,r,a);else if(t)i=await un(t,n,r,a,s,c);else return!1;return l(),i}),[e,t,o,l,i]),_=(0,q.useCallback)(async(n,r)=>e?await er(e,n,r):t?await kt(t,n,r,o):!1,[e,t,o]),v=(0,q.useCallback)(async(n,r)=>{let i;if(e)i=await sr(e,n,r);else if(t)i=await Vt(t,n,r,o);else return null;return l(),i},[e,t,o,l]),y=(0,q.useCallback)(async(n,r)=>{let i;if(e)i=await rr(e,n,r);else if(t)i=await xn(t,n,r,o);else return null;return l(),i},[e,t,o,l]),b=(0,q.useCallback)(async e=>{if(!t)return!1;let n=await jt(t,e,t,o);return l(300),n},[t,o,l]),x=(0,q.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,q.useCallback)(async e=>{if(!t)return!1;let n=await Dt(t,e,o);return l(),n},[t,o,l]),C=(0,q.useCallback)(async e=>{if(!t)return!1;let n=await an(t).catch(()=>[]),r=Dn(e,n);return r?(await Vm(a,t,r.driver,r.address),l(300),!0):!1},[t,l,a]),w=(0,q.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,q.useCallback)(async(e,n)=>{if(!t)return!1;let r=await an(t).catch(()=>[]),i=on(e,r);return!i||!i.key?!1:(await ln(t,i.driver,i.address,i.key,n),l(200),!0)},[t,l]),E=(0,q.useCallback)(async e=>t?i(`Deleting folder…`,e,`Folder deleted`,async()=>{let n=await an(t),r=kn(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await Rt(t,r.driver,r.address,r.key),!0}finally{l(200)}}):!1,[t,l,i]),D=(0,q.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:()=>{Wm(t,o),l()}})},[t,o,l]),O=(0,q.useCallback)(async(e,n)=>{if(!t)return;let r=await s(()=>Promise.resolve().then(()=>Jm),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await cn(t,n,e,o,Pn(o))).length!==e.length)throw Error(`Some documents could not be imported`);return Wm(t,o),l(),!0});else{let e=[];for(let r=0;;){let i=await hn(t,n,[],{treeName:o,treeType:Pn(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 qm({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let d=Ii(),f=Km({workspaceId:n,treeName:r}),p=r===`backends`,m=p?on(i):null,[g,_]=(0,q.useState)([]);(0,q.useEffect)(()=>{if(!p)return;let e=!1;return an(n).then(t=>{e||_(t)}).catch(()=>{}),()=>{e=!0}},[n,p]);let v=p?kn(i,g):null,y=i.split(`/`).filter(Boolean).pop()||i,[b,x]=(0,q.useState)(void 0);(0,q.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,Y.jsxs)(`button`,{type:`button`,className:U(`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,Y.jsx)(`div`,{className:`my-1 h-px bg-border`}),T=e=>{let t=p?(()=>{let t=Qd(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:ef(i)};d(`/workspaces/${n}/settings/hooks?${$d(t).toString()}`)},E=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},D=Om(r,i);return D?(0,Y.jsxs)(gc,{x:e,y:t,onClose:a,className:`min-w-44 rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,Y.jsx)(pe,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),D.backend&&C((0,Y.jsx)(mt,{className:`h-3 w-3`}),`Restore original paths`,()=>Im(n,i)),D.backend&&C((0,Y.jsx)(pe,{className:`h-3 w-3`}),`Empty Trash`,()=>Rm(n,i),!0)]}):(0,Y.jsxs)(gc,{x:e,y:t,onClose:a,className:`min-w-[11rem] rounded-md border bg-popover p-1 shadow-elevation-3`,children:[C((0,Y.jsx)(me,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&C((0,Y.jsx)(ut,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),w,p?m&&(0,Y.jsxs)(Y.Fragment,{children:[C((0,Y.jsx)(Re,{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,Y.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,Y.jsx)(F,{className:`w-3 h-3`}),`Create storage rule…`,()=>T(`store`))]}):(0,Y.jsxs)(Y.Fragment,{children:[C((0,Y.jsx)(Re,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=E(`New folder name:`);e&&await f.onInsertPath(`${i===`/`?``:i}/${e}`)}),C((0,Y.jsx)(L,{className:`w-3 h-3`}),`Rename`,async()=>{let e=E(`New name:`,y);e&&await f.onRenamePath(i,e)}),C((0,Y.jsx)(F,{className:`w-3 h-3`}),`Create rule…`,()=>T(`store`)),C((0,Y.jsx)(Me,{className:`w-3 h-3`}),`Create download rule…`,()=>T(`download`))]}),b!==void 0&&C(b?(0,Y.jsx)(h,{className:`w-3 h-3`}):(0,Y.jsx)(M,{className:`w-3 h-3`}),b?`Unpin`:`Pin`,async()=>{b?await Nn(n,b.id):await Nt(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),w,f.onImportDocuments&&C((0,Y.jsx)(Re,{className:`w-3 h-3`}),`Import documents…`,()=>f.onImportDocuments(i)),f.onExportDocuments&&C((0,Y.jsx)(Me,{className:`w-3 h-3`}),`Export documents…`,()=>f.onExportDocuments(i)),C((0,Y.jsx)(u,{className:`w-3 h-3`}),`Copy path`,()=>navigator.clipboard?.writeText(i)),!p&&l&&c&&c.length>0&&C((0,Y.jsx)(ee,{className:`w-3 h-3`}),`Paste ${c.length} document(s)`,()=>l(i,c)),p?v&&(0,Y.jsxs)(Y.Fragment,{children:[w,C((0,Y.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,Y.jsxs)(Y.Fragment,{children:[w,C((0,Y.jsx)(pe,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await f.onRemovePath(i,!0)},!0)]})]})}var Jm=t({DocumentList:()=>bh,default:()=>bh,showDocumentExport:()=>Sh,showDocumentImport:()=>xh});function Ym({isOpen:e,onClose:t,documents:n,selectedDocuments:r}){let[i,a]=(0,q.useState)(`idle`);if(!e)return null;let o=()=>{a(`idle`),t()},s=r.size>0?n.filter(e=>r.has(e.id)):n,c=s.map(Rp),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,Y.jsx)(jf,{label:`Export Documents`,onClose:o,children:(0,Y.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col p-4 sm:p-6`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Export Documents`}),(0,Y.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Exporting `,s.length,` document`,s.length===1?``:`s`,i===`copied`&&(0,Y.jsx)(`span`,{className:`text-success ml-2`,children:`✓ Copied to clipboard!`}),i===`error`&&(0,Y.jsx)(`span`,{className:`text-destructive ml-2`,children:`✗ Failed to copy`})]})]}),(0,Y.jsx)(`button`,{onClick:o,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Y.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:(0,Y.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 mb-2`,children:[(0,Y.jsx)(`h3`,{className:`font-semibold`,children:`JSON Data (Press Ctrl+A to select all, Ctrl+C to copy)`}),(0,Y.jsxs)(K,{onClick:d,size:`sm`,className:`flex items-center gap-2`,children:[(0,Y.jsx)(u,{className:`h-4 w-4`}),`Copy to Clipboard`]})]}),(0,Y.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,Y.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-end gap-2`,children:[(0,Y.jsx)(K,{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,Y.jsx)(K,{onClick:o,children:`Close`})]})]})})}function Xm({isOpen:e,onClose:t,onImport:n}){let[r,i]=(0,q.useState)(``),[a,o]=(0,q.useState)(!1),[s,c]=(0,q.useState)(null);if(!e)return null;let l=async()=>{if(c(null),!r.trim()){c(`Please enter JSON data`);return}try{let e=JSON.parse(r),a=Array.isArray(e)?e:[e];for(let e of a)if(!e||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,fo.createPortal)((0,Y.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,Y.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,Y.jsxs)(`div`,{className:`p-6`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between mb-6`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`h2`,{className:`text-2xl font-bold`,children:`Import Documents`}),(0,Y.jsx)(`p`,{className:`text-muted-foreground`,children:`Paste JSON data or choose a document export file`})]}),(0,Y.jsx)(`button`,{onClick:u,className:`p-2 hover:bg-muted rounded-sm`,title:`Close`,children:`✕`})]}),(0,Y.jsxs)(`div`,{className:`space-y-4`,children:[(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`label`,{className:`block text-sm font-medium mb-2`,children:`JSON Data (single document or array of documents)`}),(0,Y.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,Y.jsx)(`div`,{className:`text-sm text-destructive bg-destructive/10 p-3 rounded-lg border`,children:s}),(0,Y.jsxs)(`div`,{className:`text-xs text-muted-foreground`,children:[(0,Y.jsxs)(`p`,{children:[(0,Y.jsx)(`strong`,{children:`Format:`}),` Each document must have "schema", "schemaVersion", "data", and "metadata" fields.`]}),(0,Y.jsxs)(`p`,{children:[(0,Y.jsx)(`strong`,{children:`Example schemas:`}),` "data/schema/tab", "data/schema/file", etc.`]})]})]}),(0,Y.jsxs)(`label`,{className:`mt-4 block text-sm`,children:[`Import JSON file`,(0,Y.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,Y.jsxs)(`div`,{className:`mt-8 pt-4 border-t flex justify-between`,children:[(0,Y.jsx)(K,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,Y.jsx)(K,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function Zm({document:e}){let{replicating:t,label:n}=Ht(e);return t?(0,Y.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,Y.jsx)(lt,{className:`h-3 w-3 animate-spin`}),n]}):null}function Qm(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Tc(e.currentTarget,`inside`)}function $m({documentId:e,onOpenActions:t,className:n}){return t?(0,Y.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,Y.jsx)(Pe,{className:`h-4 w-4`})}):null}function eh(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function th({document:e}){let t=At(e);return t?(0,Y.jsx)(`a`,{href:t,target:`_blank`,rel:`noopener noreferrer`,title:`Open original in browser`,"aria-label":`Open original in browser`,className:`shrink-0 rounded p-1 text-muted-foreground hover:text-foreground`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:(0,Y.jsx)(Ae,{className:`h-3.5 w-3.5`})}):null}function nh({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=ed(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=wf(),[u,d]=(0,q.useState)(!1),{replicating:f}=Ht(e),p=Gt(e),m=ih(e),h=m||oh(e),{blobUrl:g}=ls(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),_=t=>{o?.(t,e.id)},v=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),y=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),b=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||d(!0)},x=e=>{e.shiftKey&&e.preventDefault()},S=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(Up,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>eh(n,()=>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:b,onMouseDown:x,...l,onContextMenu:S,draggable:!0,onDragStart:_,children:[(0,Y.jsx)(Gp,{className:`w-10`,onClick:e=>e.stopPropagation(),children:(0,Y.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,Y.jsx)(Gp,{className:`w-12`,children:g?(0,Y.jsx)(`img`,{src:g,alt:``,className:`h-8 w-8 rounded-md border object-cover`}):(0,Y.jsx)(ll,{document:e,chip:!0})}),(0,Y.jsx)(Gp,{className:`font-medium w-full max-w-0 md:w-auto md:max-w-xs`,children:(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(`span`,{className:`truncate`,title:p.title,children:p.title}),(0,Y.jsx)(th,{document:e}),(0,Y.jsx)(Zm,{document:e})]}),p.subtitle&&(0,Y.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,Y.jsx)(Gp,{className:`hidden md:table-cell`,children:(0,Y.jsx)(`span`,{className:`px-2 py-1 text-xs bg-muted rounded border`,children:p.schemaLabel})}),(0,Y.jsx)(Gp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,Y.jsx)(Gp,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:y&&(0,Y.jsx)(`span`,{className:`font-mono`,title:`${y.algo} checksum`,children:y.hash})}),(0,Y.jsx)(Gp,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,Y.jsx)(Gp,{className:`w-12 text-right`,children:(0,Y.jsx)($m,{documentId:e.id,onOpenActions:a})})]}),(0,Y.jsx)(rm,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function rh({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=ed(),c=s.alwaysOn&&s.entry?.workspaceId===n&&s.entry?.document.id===e.id,l=wf(),[u,d]=(0,q.useState)(!1),f=e.schema===`data/schema/tab`,{replicating:p}=Ht(e),m=Gt(e),h=ih(e),g=ah(e),_=h||oh(e)||g,{blobUrl:v,loading:y}=ls(n??``,e.id,512,{enabled:_,blobFallback:h,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||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,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"data-reading":c||void 0,"aria-selected":!!t,onKeyDown:n=>eh(n,()=>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,Y.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[_&&(0,Y.jsxs)(`div`,{className:`relative h-32 w-40 max-w-[40%] sm:h-40 sm:w-56 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:[v?(0,Y.jsx)(`img`,{src:v,alt:m.title,loading:`lazy`,className:`h-full w-full object-cover`}):g&&n&&!y?(0,Y.jsx)(sh,{workspaceId:n,documentId:e.id,fallback:(0,Y.jsx)(ll,{document:e})}):y?(0,Y.jsx)(`div`,{className:`h-full w-full animate-pulse bg-muted/60`}):(0,Y.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Y.jsx)(ll,{document:e})}),g&&(0,Y.jsx)(j,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`})]}),(0,Y.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-2 mb-2 overflow-hidden`,children:[(0,Y.jsx)(ll,{document:e,chip:!0}),(0,Y.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:m.title,children:m.title}),(0,Y.jsx)(th,{document:e}),(0,Y.jsx)(`span`,{className:`ml-auto px-2 py-0.5 text-xs bg-muted text-muted-foreground rounded border flex-shrink-0`,children:m.schemaLabel}),(0,Y.jsx)(Zm,{document:e})]}),m.subtitle&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:m.subtitle,children:m.subtitle}),m.preview&&(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:m.preview}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-4 text-xs text-muted-foreground overflow-hidden`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`ID:`}),(0,Y.jsx)(`span`,{className:`font-mono truncate max-w-[60px]`,title:`ID: ${e.id}`,children:e.id})]}),S&&(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(D,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{className:`font-mono`,title:`${S.algo} checksum`,children:S.hash})]}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(z,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{title:`Created: ${x(e.createdAt)}`,children:x(e.createdAt)})]})]})]}),(0,Y.jsx)($m,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,Y.jsx)(rm,{document:e,isOpen:u,onClose:()=>d(!1),workspaceId:n})]})}function ih(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function ah(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function oh(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function sh({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Bn(e,t),[a,o]=(0,q.useState)(!1);return i||a?(0,Y.jsx)(Y.Fragment,{children:n}):r?(0,Y.jsxs)(`div`,{className:`relative h-full w-full`,children:[(0,Y.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-full w-full object-cover`}),(0,Y.jsx)(`span`,{className:`pointer-events-none absolute bottom-2 right-2 rounded-sm bg-scrim p-1 text-scrim-foreground`,children:(0,Y.jsx)(j,{className:`h-3.5 w-3.5`})})]}):(0,Y.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function ch({document:e,workspaceId:t,markdown:n}){let r=(0,q.useRef)(null),[i,a]=(0,q.useState)(()=>typeof IntersectionObserver>`u`);(0,q.useEffect)(()=>{let e=r.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(a(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let{text:o,loading:s,error:c}=Hn(t,e.id,{mode:`text`,enabled:i,maxTextLength:8e3});return(0,Y.jsx)(`div`,{ref:r,className:`relative h-48 w-full overflow-hidden bg-card text-card-foreground`,children:o!=null&&!c?(0,Y.jsxs)(`div`,{className:`pointer-events-none p-3 pt-7 text-xs leading-relaxed`,"aria-hidden":`true`,children:[o.length===0?(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Empty file`}):n?(0,Y.jsx)(vs,{content:o,preview:!0,className:`text-xs [&_pre]:whitespace-pre-wrap [&_pre]:break-words [&_table]:table-fixed [&_table]:w-full`}):(0,Y.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono`,children:o}),(0,Y.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-card to-transparent`})]}):(0,Y.jsxs)(`div`,{className:`flex h-full items-center justify-center`,children:[(0,Y.jsx)(ll,{document:e,size:10,chip:!0}),i&&s&&(0,Y.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function lh({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let[c,l]=(0,q.useState)(null),u=e.metadata?.dimensions,d=c??(u?.width&&u?.height?Math.max(.2,Math.min(5,u.width/u.height)):1),f=ed(),p=f.alwaysOn&&f.entry?.workspaceId===n&&f.entry?.document.id===e.id,m=wf(),[h,g]=(0,q.useState)(!1),_=ih(e),v=ah(e),y=_||oh(e)||v,b=Gt(e),x=Bt(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||Pt(e)),S=e.schema===`data/schema/file`&&(x===`markdown`||x===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,C=!y&&e.schema!==`data/schema/file`&&!!(b.preview||b.subtitle),{replicating:w}=Ht(e),{blobUrl:T,loading:E}=ls(n??``,e.id,768,{enabled:y,blobFallback:_,version:e.checksumArray?.[0]??null}),D=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||g(!0)},O=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,style:{flexGrow:d,flexBasis:`${d*220}px`,"--tile-ratio":d},"data-reading":p||void 0,"aria-selected":!!t,onKeyDown:n=>eh(n,()=>g(!0),()=>r?.(e.id,!t,!0)),className:`document-tile 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 ${w?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:D,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...m,onContextMenu:O,draggable:!0,onDragStart:t=>s?.(t,e.id),title:b.title,children:[(0,Y.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,Y.jsxs)(`div`,{className:`document-tile-media relative w-full bg-muted/40 ${y&&T||C||S&&n||v&&n?``:`aspect-square`}`,children:[y&&E&&(0,Y.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),y&&T?(0,Y.jsx)(`img`,{src:T,alt:b.title,loading:`lazy`,className:`block h-auto w-full`,onLoad:e=>{let t=e.currentTarget;t.naturalHeight&&l(t.naturalWidth/t.naturalHeight)}}):v&&n&&!E?(0,Y.jsx)(sh,{workspaceId:n,documentId:e.id,fallback:(0,Y.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,Y.jsx)(ll,{document:e,size:10,chip:!0})})}):S&&n?(0,Y.jsx)(ch,{document:e,workspaceId:n,markdown:x===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):C?(0,Y.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,Y.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Y.jsx)(ll,{document:e}),(0,Y.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:b.schemaLabel}),(0,Y.jsx)(th,{document:e})]}),(0,Y.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:b.title}),b.subtitle&&(0,Y.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:b.subtitle}),(0,Y.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:b.preview})]}):(0,Y.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Y.jsx)(ll,{document:e,size:10,chip:!0})}),v&&T&&(0,Y.jsx)(j,{className:`pointer-events-none absolute bottom-2 right-2 h-5 w-5 rounded bg-scrim text-scrim-foreground`}),(0,Y.jsxs)(`div`,{className:`absolute right-2 top-2 flex gap-1 reveal-on-hover`,children:[i&&(0,Y.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,Y.jsx)(le,{className:`h-3.5 w-3.5`})}),o&&(0,Y.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,Y.jsx)(Pe,{className:`h-3.5 w-3.5`})})]})]}),!C&&(0,Y.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t bg-card px-2 py-1.5`,children:[(0,Y.jsx)(`span`,{className:`truncate text-xs font-medium`,title:b.title,children:b.title}),(0,Y.jsx)(th,{document:e})]})]}),(0,Y.jsx)(rm,{document:e,isOpen:h,onClose:()=>g(!1),workspaceId:n})]})}function uh(e,t,n,r,i){let[a,o]=(0,q.useState)(!1),s=e=>Array.from(e.dataTransfer.types).includes(`application/json`);return{over:a,onDragOver:e=>{!t||!s(e)||(e.preventDefault(),e.dataTransfer.dropEffect=`link`,a||o(!0))},onDragLeave:()=>o(!1),onDrop:async a=>{if(o(!1),!t||!s(a))return;a.preventDefault(),a.stopPropagation();let c=null;try{c=JSON.parse(a.dataTransfer.getData(`application/json`))}catch{c=null}if(!(c?.type!==`document`||!Array.isArray(c.documentIds)||c.documentIds.length===0)&&!Ip(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function dh(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function fh({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,Y.jsx)(ht,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,Y.jsx)(de,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var ph=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function mh({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=uh(e,r,i,a,o);return(0,Y.jsxs)(`button`,{type:`button`,title:ph(e),onClick:()=>t?.(e.path),onContextMenu:t=>dh(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,Y.jsxs)(`span`,{className:`relative shrink-0`,children:[(0,Y.jsx)(fh,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,Y.jsx)(ht,{className:`hidden h-4 w-4 group-hover:block`}):(0,Y.jsx)(me,{className:`hidden h-4 w-4 group-hover:block`,style:e.color?{color:e.color}:void 0})]}),(0,Y.jsx)(`span`,{className:`truncate`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Y.jsx)(`span`,{className:`shrink-0 text-[11px] tabular-nums text-muted-foreground`,children:e.childCount})]})}function hh({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=uh(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,Y.jsxs)(`button`,{type:`button`,title:ph(e),onClick:()=>t?.(e.path),onContextMenu:t=>dh(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,Y.jsx)(`span`,{className:`relative flex h-14 w-14 items-center justify-center`,children:e.isParent?(0,Y.jsx)(ht,{className:`h-10 w-10`,strokeWidth:1.5}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(de,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,Y.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,Y.jsx)(`span`,{className:`w-full truncate text-center font-medium`,children:e.isParent?`..`:e.label||e.name}),!e.isParent&&!!e.childCount&&(0,Y.jsxs)(`span`,{className:`text-[11px] tabular-nums text-muted-foreground`,children:[e.childCount,` subfolder`,e.childCount===1?``:`s`]})]})}function gh({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,Y.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,Y.jsx)(hh,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function _h({folders:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){return e.length===0?null:(0,Y.jsx)(`div`,{className:`mb-3 flex flex-wrap gap-2 pr-2`,onContextMenu:e=>e.stopPropagation(),children:e.map(e=>(0,Y.jsx)(mh,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function vh({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=uh(e,r,i,a,o);return(0,Y.jsxs)(Up,{"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=>dh(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:ph(e),children:[(0,Y.jsx)(Gp,{className:`w-10`}),(0,Y.jsx)(Gp,{className:`w-12`,children:(0,Y.jsx)(fh,{folder:e})}),(0,Y.jsx)(Gp,{className:`w-full max-w-0 md:w-auto md:max-w-none`,children:(0,Y.jsx)(`span`,{className:`block truncate font-medium`,children:e.isParent?`..`:e.label||e.name})}),(0,Y.jsx)(Gp,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,Y.jsx)(Gp,{className:`hidden lg:table-cell`}),(0,Y.jsx)(Gp,{className:`hidden lg:table-cell`}),(0,Y.jsx)(Gp,{className:`hidden sm:table-cell text-xs text-muted-foreground`,children:!e.isParent&&e.childCount?`${e.childCount} subfolder${e.childCount===1?``:`s`}`:``}),(0,Y.jsx)(Gp,{className:`w-12 md:w-auto`})]})}function yh({label:e,count:t,collapsed:n,allSelected:r,someSelected:i,onToggle:a,onSelectAll:o}){return(0,Y.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,Y.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,Y.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,Y.jsx)(_t,{className:`h-3.5 w-3.5 shrink-0 transition-transform ${n?``:`rotate-90`}`}),(0,Y.jsx)(`span`,{className:`truncate text-xs font-semibold uppercase tracking-wide`,children:e}),(0,Y.jsx)(`span`,{className:`shrink-0 text-xs font-normal tabular-nums opacity-70`,children:t})]}),(0,Y.jsx)(`div`,{className:`h-px flex-1 bg-border`})]})}function bh({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=Eo(),[xe,Se]=(0,q.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?xe:D,Te=(0,q.useCallback)(e=>{Se(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[Ee,De]=(0,q.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),Oe=(0,q.useCallback)(()=>{De(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[ke,Pe]=(0,q.useState)(new Set),Fe=(0,q.useCallback)(e=>{Pe(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[V,H]=(0,q.useState)(new Set),[Ie,Le]=(0,q.useState)(null),[ze,Ve]=(0,q.useState)(null),He=tr(),Ge=!!(He&&s),Ke=(0,q.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,q.useState)(!1),[Ze,Qe]=(0,q.useState)(null),[$e,et]=(0,q.useState)(!1),[tt,it]=(0,q.useState)(null),[at,ot]=(0,q.useState)(!1),st=(0,q.useRef)(!1),ct=(0,q.useRef)(!1),lt=o===`backends`&&z===`path`?Qd(a):null;(0,q.useEffect)(()=>()=>{st.current=!0},[]);let[ft,mt]=(0,q.useState)(!1),[ht,gt]=(0,q.useState)(null),[vt,U]=(0,q.useState)(!1),[yt,W]=(0,q.useState)(null),G=Xn()==null&&!!s,[bt,xt]=(0,q.useState)(null),[St,Tt]=(0,q.useState)(null),Et=!!(_e&&S),Dt=!!s,{showSuccessToast:Ot,showErrorToast:kt}=wt(),{showProgress:At}=Ct(),jt=ed(),Mt=s?e=>jt.open(e,s):void 0,Nt=z===`workspace`,Ft=Nt?void 0:f,It=Nt?void 0:h,[Lt,Rt]=(0,q.useState)(!1),[zt,Bt]=(0,q.useState)(!1),[Vt,Ht]=(0,q.useState)(``),Ut=t??Vt,Wt=t!==void 0,[Kt,qt]=(0,q.useState)(!1),Jt=ae.length>0,Yt=(0,q.useRef)(null),Xt=(0,q.useCallback)(()=>{Ht(``),Yt.current&&(Yt.current.value=``)},[]);(0,q.useEffect)(()=>{if(!A||window.matchMedia(`(max-width: 767px)`).matches)return;let e=Yt.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 Zt=JSON.stringify([s,o,a]),[Qt,$t]=(0,q.useState)(Zt);Zt!==Qt&&($t(Zt),H(new Set),Qe(null),Ve(null),Le(null)),(0,q.useEffect)(()=>{w?.(Array.from(V))},[V,w]);let en=(0,q.useCallback)(()=>{if(!oe)return;let e=Ut.trim();e&&(oe(e),Xt())},[oe,Ut,Xt]),tn=(0,q.useCallback)(()=>{Xt(),R&&ae.length>0&&R(-1)},[R,ae.length,Xt]),nn=(0,q.useCallback)((e,t)=>{let n;V.has(t)&&V.size>1?n=Array.from(V):(n=[t],H(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]),rn=(0,q.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(),qt(!1),!Ip(n,s,o,a)&&(await S(a,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),H(new Set)))},[a,o,s,S]),an=(0,q.useCallback)(e=>{S&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,qt(!0))},[S]),on=(0,q.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||qt(!1)},[]),sn=(0,q.useMemo)(()=>({keys:[{name:`data.title`,weight:.4},{name:`data.name`,weight:.4},{name:`locations.url`,weight:.4},{name:`data.url`,weight:.3},{name:`data.content`,weight:.2},{name:`data.description`,weight:.2}],threshold:.4,location:0,distance:100,minMatchCharLength:1,includeScore:!0,includeMatches:!0,ignoreLocation:!0}),[]),cn=(0,q.useMemo)(()=>r.length===0?null:new dr(r,sn),[r,sn]),ln=(0,q.useDeferredValue)(Ut),un=(0,q.useMemo)(()=>{if(!ln.trim())return r;let{text:e,ids:t,invalid:n}=Sf(ln);if(n)return[];let i=e&&cn?cn.search(e).map(e=>e.item):r;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[r,ln,cn]),dn=(0,q.useMemo)(()=>{if(!ve||ve.length===0||ln.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,ln,ce?.order]),fn=dn.length>0,[pn,mn]=(0,q.useState)(null),hn=(0,q.useMemo)(()=>s&&o&&ye?(e,t)=>mn({x:t.clientX,y:t.clientY,path:e}):void 0,[s,o,ye]),_n={folders:dn,onOpen:ye,onMenu:hn,onPasteDocuments:S,contextPath:a,treeName:o,workspaceId:s},{sorted:vn,sort:bn,toggleSort:xn}=Jp(un,(0,q.useMemo)(()=>({title:e=>Gt(e).title?.toLowerCase()??``,schema:e=>Gt(e).schemaLabel??``,type:yn,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),Sn=(0,q.useCallback)(e=>vm(e,ce?.sortBy),[ce?.sortBy]),Cn=(0,q.useMemo)(()=>Dm(un,Sn,ce?.order===`asc`?`asc`:`desc`),[un,Sn,ce?.order]),wn=Ee&&!gn(ce?.sortBy)&&Cn.length>1,Tn=(0,q.useCallback)((e,t)=>{H(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),En=(0,q.useMemo)(()=>(B===`table`?vn:wn?Cn.filter(e=>!ke.has(e.key)).flatMap(e=>e.items):un).map(e=>e.id),[B,vn,wn,Cn,ke,un]),Dn=(0,q.useRef)(null),On=JSON.stringify([s,a,o,N]),kn=(0,q.useCallback)(e=>{Dn.current=null,H(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),Mn=(0,q.useCallback)((e,t,n,r=!1)=>{let i=Dn.current,a=i?.scope===On&&En.includes(i.id)?i.id:null;(!r||a===null)&&(Dn.current={scope:On,id:e}),H(i=>{if(r)return Tf(En,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[On,En]),Nn=(0,q.useCallback)((e,t)=>{let n;V.has(e)?n=Array.from(V):(n=[e],H(new Set([e]))),Le({anchor:t,ids:n})},[V]),Pn=(0,q.useCallback)((e,t)=>{Nn(t,Tc(e))},[Nn]),Fn=(0,q.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),Nn(t,Qm(e)))},[Nn]),In=(0,q.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){Je(!0);try{for(let n of t)await An(s,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;Ot(`Created ${n} relation${n===1?``:`s`}`),wl(),Ve(null)}catch(e){kt(e instanceof Error?e.message:`Failed to create relations`)}finally{Je(!1)}}},[s,Ot,kt]),Ln=(0,q.useCallback)(async(e,t,n)=>{if(S){for(let r of e)await S(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});H(new Set)}},[S]),Rn=(0,q.useCallback)(async(e,t,n)=>{if(!s||!Ze||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:`${Ze.ids.length} document(s) · ${e.join(`, `)}`});try{let a=r=>jn(s,r,{to:e,mode:t,keepDocument:n.keepDocument,...t===`delete`&<?{deleteFrom:{backend:lt.backend,folder:lt.rel}}:{},folder:n.folder,filename:n.filename,onConflict:n.onConflict}),o=t===`delete`?await Id(Ze.ids,a,{shouldStop:()=>st.current,onProgress:(t,n)=>{it({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(Ze.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}. ${ql(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),H(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),it(null)}},[s,Ze,lt,r,At]),zn=(0,q.useCallback)(()=>{V.size===un.length?H(new Set):H(new Set(un.map(e=>e.id)))},[V.size,un]),Bn=(0,q.useCallback)(async e=>{try{await navigator.clipboard.writeText(e)}catch{let t=window.document.createElement(`textarea`);t.value=e,window.document.body.appendChild(t),t.select(),window.document.execCommand(`copy`),window.document.body.removeChild(t)}},[]),Vn=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=()=>H(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:ut,run:()=>Tt({document:i})}),l(G&&{id:`edit`,group:`open`,label:`Edit`,icon:k,run:()=>Tt({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:Ue,run:()=>Bn(String(i.id))}),l(i&&G&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:Xe,run:()=>xt(i)}),l(Et&&{id:`link-to`,group:`organize`,label:`Link to…${n}`,icon:Ne,run:()=>Ve(e)}),l(Ge&&{id:`add-related`,group:`organize`,label:`Add related document…${n}`,icon:Re,run:t=>Ke(e,t?.shiftKey)}),l(G&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${n}`,icon:k,run:()=>W(e)}),l(G&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:u,run:t=>{U(!!t?.shiftKey),gt(e)}}),l({id:`export`,group:`organize`,label:`Export…${n}`,icon:Me,run:()=>Rt(!0)}),l(o!==`backends`&&(Ft||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&&Ft?Ft(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:Be,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},Hn=()=>{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(un.length>0&&{id:`select-all`,group:`select`,label:Ut?`Select all matches (${un.length})`:`Select all on this page`,icon:Ce,shortcut:`Mod+A`,run:()=>H(new Set(un.map(e=>e.id)))}),t(V.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:rt,run:()=>H(new Set)}),t(S&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:Ye,hint:`Browse and add existing documents to this folder`,run:()=>mt(!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:()=>{H(new Set),Rt(!0)}}),t(re&&d>0&&{id:`purge`,group:`purge`,label:`Purge all (${d})`,icon:pe,destructive:!0,disabled:ie||!!Ut,hint:Ut?`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},Un=!!(de&&ce&&s),Wn=Ie?Ie.ids?Vn(Ie.ids):Hn():[],Gn=Ie?.ids?.length===1?r.find(e=>e.id===Ie.ids[0]):void 0,Kn=Gn?(0,Y.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Y.jsx)(ll,{document:Gn,chip:!0}),(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Gt(Gn).title}),(0,Y.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Gn.id,` · `,Gn.schema]})]})]}):(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Ie?.ids?`${Ie.ids.length} documents`:`This folder`}),qn=e=>{Le({anchor:Tc(e.currentTarget),ids:V.size>0?Array.from(V):null})},Jn=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),H(new Set),Le({anchor:Qm(e),ids:null}))},Yn=e=>{if(e.defaultPrevented||xc(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Cc(e)){e.preventDefault(),t?Nn(Number(t.dataset.documentId),Tc(t,`inside`)):Le({anchor:Tc(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&&Mn(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&V.size>0){e.preventDefault(),H(new Set);return}Sc(e,[...Vn(Array.from(V)),...Hn()])},Zn=(0,q.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]),Qn=e=>wn?Cn.map(t=>{let n=ke.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!V.has(t),0);return(0,Y.jsxs)(`section`,{className:`group mb-4`,children:[(0,Y.jsx)(yh,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>Fe(t.key),onSelectAll:e=>Tn(r,e)}),!n&&e(t.items)]},t.key)}):e(un);return i?(0,Y.jsx)(Pd,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:[],loading:!0,children:(0,Y.jsx)(`div`,{className:`flex-1 flex items-center justify-center`,children:(0,Y.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Y.jsx)(`div`,{className:`animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto`}),(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading documents...`})]})})}):(0,Y.jsx)(Pd,{enabled:e,workspaceId:s,scope:JSON.stringify([s,o,a]),documents:B===`table`?vn:un,loading:!1,children:(0,Y.jsxs)(`div`,{tabIndex:-1,onKeyDown:Yn,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${Kt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:an,onDragLeave:on,onDrop:rn,children:[(0,Y.jsxs)(`div`,{className:`border-b pb-3 mb-4 flex-shrink-0`,children:[(0,Y.jsxs)(`div`,{className:`min-w-0 space-y-0.5`,children:[(0,Y.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,Y.jsx)(`h3`,{className:`font-semibold text-sm text-muted-foreground`,children:`Documents`}),(0,Y.jsx)(`p`,{className:`shrink-0 text-sm font-medium`,children:Ut?`${un.length} of ${r.length}`:`${d.toLocaleString()} document${d===1?``:`s`}`})]}),(0,Y.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs text-muted-foreground`,children:[(0,Y.jsxs)(`p`,{hidden:Wt,className:`min-w-0 truncate`,children:[`Context: `,(0,Y.jsx)(`span`,{className:`font-mono`,children:a}),j&&M&&j!==M&&(0,Y.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,Y.jsxs)(`p`,{className:`shrink-0`,children:[V.size>0&&(0,Y.jsxs)(`span`,{className:`text-info`,children:[V.size,` selected`]}),V.size>0&&(Ut||d>P)&&(0,Y.jsx)(`span`,{className:`mx-1`,children:`·`}),Ut?`on this page`:d>P?`Showing ${Math.min((N-1)*P+1,d)}–${Math.min(N*P,d)}`:null]})]})]}),!Wt&&(0,Y.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Y.jsxs)(`div`,{className:`relative flex flex-wrap items-center gap-2`,children:[!Wt&&fe&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 rounded-md border border-input overflow-hidden text-xs font-medium`,children:[(0,Y.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,Y.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,Y.jsx)(se,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!Wt&&(0,Y.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,Y.jsx)(pt,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,Y.jsx)(`input`,{ref:Yt,type:`text`,placeholder:oe?Jt?`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(),en())},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`}),(Ut||Jt)&&(0,Y.jsx)(`button`,{onClick:tn,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,Y.jsx)(E,{className:`h-4 w-4`})})]}),!Wt&&oe&&Ut.trim()&&!ae.includes(Ut.trim())&&(0,Y.jsxs)(K,{size:`sm`,variant:`default`,onClick:en,className:`shrink-0`,title:Jt?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,Y.jsx)(pt,{className:`h-3.5 w-3.5 mr-1`}),Jt?`Refine`:`Search server`]})]}),!Wt&&Jt&&(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-1.5 text-xs`,children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Server search:`}),ae.map((e,t)=>(0,Y.jsxs)(`span`,{className:`flex items-center gap-1`,children:[t>0&&(0,Y.jsx)(`span`,{className:`text-muted-foreground/70 font-medium uppercase text-[10px]`,children:`then`}),(0,Y.jsxs)(`span`,{className:`flex items-center gap-1 px-2 py-0.5 rounded bg-muted text-foreground border`,children:[(0,Y.jsxs)(`span`,{className:`font-mono`,children:[`"`,e,`"`]}),R&&(0,Y.jsx)(`button`,{onClick:()=>R(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,Y.jsx)(E,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),R&&ae.length>1&&(0,Y.jsx)(`button`,{onClick:()=>R(-1),className:`ml-1 text-muted-foreground hover:text-foreground underline`,title:`Clear all queries`,children:`clear all`})]})]}),(0,Y.jsx)(`div`,{className:`document-toolbar mt-3`,children:(0,Y.jsxs)(`div`,{className:`document-toolbar-row`,children:[(0,Y.jsxs)(`div`,{className:`document-toolbar-controls`,children:[(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,role:`group`,"aria-label":`Document layout`,children:[A&&(0,Y.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,dt,`Tile view`],[`card`,je,`Card view`]].map(([e,t,n])=>(0,Y.jsx)(`button`,{type:`button`,onClick:()=>Te(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,Y.jsx)(t,{className:`h-4 w-4`})},e))}),A&&B!==`table`&&!gn(ce?.sortBy)&&(0,Y.jsx)(`button`,{type:`button`,onClick:Oe,title:Ee?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":Ee,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${Ee?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Y.jsx)(_,{className:`h-4 w-4`})})]}),L&&d>0&&(0,Y.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5`,children:[(0,Y.jsx)(`span`,{className:`document-toolbar-label`,children:`Show:`}),(0,Y.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,Y.jsx)(`option`,{value:25,children:`25`}),(0,Y.jsx)(`option`,{value:50,children:`50`}),(0,Y.jsx)(`option`,{value:100,children:`100`}),(0,Y.jsx)(`option`,{value:200,children:`200`})]}),(0,Y.jsx)(`span`,{className:`document-toolbar-label`,children:`per page`})]})]}),(0,Y.jsxs)(`div`,{className:`document-toolbar-secondary`,children:[Un&&(0,Y.jsxs)(`div`,{className:`document-toolbar-sort flex min-w-0 items-center gap-1.5`,children:[(0,Y.jsx)(`span`,{className:`document-toolbar-label`,children:`Sort`}),(0,Y.jsx)(_m,{workspaceId:s,value:ce,onChange:de})]}),(0,Y.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(r.length>0||C||S)&&(0,Y.jsxs)(`div`,{className:`contents`,children:[(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:qn,"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 (${yc(`Shift+F10`)} or right-click)`,children:[(0,Y.jsx)(We,{className:`h-4 w-4`}),(0,Y.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,V.size>0?` (${V.size} selected)`:``]})]}),V.size>0&&(0,Y.jsxs)(K,{variant:`ghost`,size:`sm`,onClick:()=>H(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,Y.jsx)(E,{className:`h-3.5 w-3.5`}),(0,Y.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),T&&T.length>0&&S&&(0,Y.jsxs)(K,{variant:`outline`,size:`sm`,onClick:()=>S(a,T),className:`flex items-center gap-1.5`,title:`Paste into this folder (${yc(`Mod+V`)})`,children:[(0,Y.jsx)(ee,{className:`h-4 w-4`}),`Paste (`,T.length,`)`]})]}),me&&ge&&(0,Y.jsx)(K,{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,Y.jsx)(ne,{className:`h-3.5 w-3.5`})}),n]})]})]})}),L&&d>P&&(0,Y.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,Y.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,Y.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,Y.jsx)(K,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>L(1),disabled:N===1,className:`p-1 touch-target`,children:(0,Y.jsx)(I,{className:`h-4 w-4`})}),(0,Y.jsx)(K,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>L(N-1),disabled:N===1,className:`p-1 touch-target`,children:(0,Y.jsx)(l,{className:`h-4 w-4`})}),(0,Y.jsxs)(`span`,{className:`whitespace-nowrap px-3 py-1 text-sm font-medium max-sm:px-1 max-sm:text-xs`,children:[(0,Y.jsx)(`span`,{className:`max-sm:sr-only`,children:`Page `}),N,(0,Y.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,Y.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(d/P)]}),(0,Y.jsx)(K,{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,Y.jsx)(_t,{className:`h-4 w-4`})}),(0,Y.jsx)(K,{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,Y.jsx)(O,{className:`h-4 w-4`})})]})]})]}),(0,Y.jsx)(kp,{scope:JSON.stringify([On,B,En]),selected:V,onSelectionChange:kn,onContextMenu:Jn,children:un.length===0&&!fn?(0,Y.jsx)(`div`,{className:`min-h-full flex items-center justify-center`,children:(0,Y.jsxs)(`div`,{className:`text-center space-y-2`,children:[(0,Y.jsx)(nt,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:Ut?`No documents match your search`:`No documents found in this context`}),(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:Ut?(0,Y.jsxs)(Y.Fragment,{children:[`Search: `,(0,Y.jsxs)(`span`,{className:`font-mono`,children:[`"`,Ut,`"`]})]}):(0,Y.jsxs)(Y.Fragment,{children:[`Path: `,(0,Y.jsx)(`span`,{className:`font-mono`,children:a})]})}),!Wt&&Ut&&(0,Y.jsx)(`button`,{onClick:Xt,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!Ut&&T&&T.length>0&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,yc(`Mod+V`),` to paste `,T.length,` document(s)`]})]})}):B===`tile`?(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(gh,{..._n}),un.length===0&&(0,Y.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Qn(e=>(0,Y.jsx)(`div`,{className:`document-tiles pr-2`,"data-tile-style":be,children:e.map(e=>(0,Y.jsx)(lh,{document:e,isSelected:V.has(e.id),workspaceId:s,onSelect:Mn,onOpenToSide:Mt,onRightClick:Fn,onOpenActions:Pn,onDragStart:nn},e.id))}))]}):B===`table`?(0,Y.jsx)(`div`,{children:(0,Y.jsxs)(zp,{children:[(0,Y.jsx)(Bp,{children:(0,Y.jsxs)(Up,{children:[(0,Y.jsx)(Wp,{className:`w-10`,children:(0,Y.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:un.length>0&&V.size===un.length,ref:e=>{e&&(e.indeterminate=V.size>0&&V.size<un.length)},onChange:zn,title:`Select all on this page`})}),(0,Y.jsx)(qp,{label:(0,Y.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:bn,onSort:xn,className:`w-12`}),(0,Y.jsx)(qp,{label:`Title`,sortKey:`title`,sort:bn,onSort:xn,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,Y.jsx)(qp,{label:`Schema`,sortKey:`schema`,sort:bn,onSort:xn,className:`hidden md:table-cell`}),(0,Y.jsx)(qp,{label:`ID`,sortKey:`id`,sort:bn,onSort:xn,className:`hidden lg:table-cell`}),(0,Y.jsx)(Wp,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,Y.jsx)(qp,{label:`Created`,sortKey:`created`,sort:bn,onSort:xn,className:`hidden sm:table-cell`}),(0,Y.jsx)(Wp,{className:`w-12 md:w-auto`,children:(0,Y.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,Y.jsxs)(Vp,{children:[dn.map(e=>(0,Y.jsx)(vh,{folder:e,onOpen:ye,onMenu:hn,onPasteDocuments:S,contextPath:a,treeName:o,workspaceId:s},e.path)),vn.map(e=>(0,Y.jsx)(nh,{document:e,isSelected:V.has(e.id),workspaceId:s,onSelect:Mn,onOpenToSide:Mt,onRightClick:Fn,onOpenActions:Pn,onDragStart:nn},e.id))]})]})}):(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(_h,{..._n}),un.length===0&&(0,Y.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Qn(e=>(0,Y.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,Y.jsx)(`div`,{children:(0,Y.jsx)(rh,{document:e,isSelected:V.has(e.id),workspaceId:s,onSelect:Mn,onOpenToSide:Mt,onRightClick:Fn,onOpenActions:Pn,onDragStart:nn})},e.id))}))]})}),Ie&&(0,Y.jsx)(Ac,{anchor:Ie.anchor,items:Wn,onClose:()=>Le(null),label:Ie.ids?`Document actions`:`Folder actions`,header:Kn}),(0,Y.jsx)(Ym,{isOpen:Lt,onClose:()=>Rt(!1),documents:r,selectedDocuments:V}),(0,Y.jsx)(Xm,{isOpen:zt,onClose:()=>Bt(!1),onImport:Zn}),ht&&s&&(0,Y.jsx)(jp,{modal:vt,workspaceId:s,ids:ht,onClose:()=>gt(null)}),ze&&_e&&(0,Y.jsx)(jf,{label:`Link to`,onClose:()=>Ve(null),children:(0,Y.jsx)(Sl,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:ze.length,fixedWorkspaceName:s,tabs:[`context`,`directory`,`relations`],saving:qe,relationExcludeIds:new Set(ze),onConfirm:(e,t)=>Ln(e,ze,t),onConfirmRelation:e=>In(e,ze),onClose:()=>Ve(null)})}),Ze&&s&&(0,fo.createPortal)((0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker flex items-center justify-center bg-scrim p-4 max-md:p-2`,children:(0,Y.jsx)(eu,{workspaceId:s,documentCount:Ze.ids.length,initialMode:Ze.mode,defaultFilename:Ze.ids.length===1?Pt(r.find(e=>e.id===Ze.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:Rn,onClose:()=>{$e||Qe(null)}})}),window.document.body),ft&&S&&(0,fo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:`fixed inset-0 z-picker-scrim bg-scrim animate-fade-in md:hidden`,onClick:()=>mt(!1),"aria-hidden":!0}),(0,Y.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,Y.jsx)(Lp,{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),mt(!1)},onClose:()=>mt(!1)})})]}),window.document.body),bt&&s&&(0,Y.jsx)(Cp,{workspaceId:s,document:bt,onClose:()=>xt(null)},`${s}:${bt.id}`),yt&&s&&(0,Y.jsx)(Pp,{workspaceId:s,documentIds:yt,onClose:()=>W(null)}),(0,Y.jsx)(rm,{document:St?.document??null,isOpen:!!St,onClose:()=>Tt(null),workspaceId:s,initialEdit:St?.edit}),pn&&s&&o&&ye&&(0,Y.jsx)(qm,{x:pn.x,y:pn.y,workspaceName:s,treeName:o,path:pn.path,onClose:()=>mn(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 xh(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,mo.createRoot)(t);n.render((0,Y.jsx)(Xm,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function Sh(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,mo.createRoot)(t);n.render((0,Y.jsx)(Ym,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{ef as $,la as $n,ul as $t,zp as A,Rs as An,Qu as At,Rf as B,Po as Bn,Jl as Bt,um as C,Us as Cn,wd as Ct,nm as D,zs as Dn,nd as Dt,em as E,Ns as En,sd as Et,Up as F,ns as Fn,Ru as Ft,jf as G,go as Gn,Rl as Gt,Ff as H,wo as Hn,Gl as Ht,Lp as I,qo as In,ku as It,lf as J,Qa as Jn,Ol as Jt,Ef as K,po as Kn,Al as Kt,Ip as L,Jo as Ln,wu as Lt,Gp as M,As as Mn,Yu as Mt,Wp as N,vs as Nn,Zu as Nt,Jp as O,Is as On,td as Ot,Bp as P,ls as Pn,Uu as Pt,of as Q,Si as Qn,dl as Qt,Pp as R,Uo as Rn,cu as Rt,lm as S,Ws as Sn,Dd as St,rm as T,Vs as Tn,xd as Tt,Pf as U,Eo as Un,Wl as Ut,Lf as V,vo as Vn,Yl as Vt,If as W,_o as Wn,Il as Wt,hf as X,Ci as Xn,wl as Xt,xf as Y,$a as Yn,Tl as Yt,df as Z,ca as Zn,Sl as Zt,sm as _,xc as _n,pf as _t,Vm as a,Fc as an,Dr as ar,sf as at,dm as b,hc as bn,Nd as bt,Rm as c,Rc as cn,Ii as cr,Kd as ct,Im as d,Uc as dn,af as dt,ll as en,ua as er,Vd as et,Om as f,Mc as fn,cf as ft,pm as g,Ac as gn,Bd as gt,_m as h,Nc as hn,gf as ht,Gm as i,Qc as in,pa as ir,vf as it,Vp as j,Bs as jn,ed as jt,qp as k,Ls as kn,rd as kt,Mm as l,Lc as ln,Bi as lr,Gd as lt,Am as m,Wc as mn,$d as mt,Km as n,el as nn,fa as nr,ff as nt,Lm as o,Pc as on,wr as or,Yd as ot,km as p,Gc as pn,_f as pt,wf as q,hr as qn,kl as qt,Wm as r,$c as rn,Cr as rr,zd as rt,Pm as s,Ic as sn,Ni as sr,mf as st,bh as t,Yc as tn,wi as tr,yf as tt,Nm as u,Hc as un,ao as ur,Rd as ut,am as v,bc as vn,Jd as vt,om as w,Gs as wn,Cd as wt,cm as x,Hs as xn,Ad as xt,fm as y,gc as yn,Qd as yt,Sp as z,Mo as zn,tu as zt};
|