@augmentd-labs/canvas-web 2.26.6 → 2.26.7
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/{SketchEditor-CWpixOog.js → SketchEditor-CRJF-Jp4.js} +1 -1
- package/dist/assets/document-list-jSeA3hbj.js +19 -0
- package/dist/assets/document-list-uxlmEpEr.css +1 -0
- package/dist/assets/{index-DLTBUV0v.css → index-DCiNIpsg.css} +1 -1
- package/dist/assets/index-DeZi1CDA.js +40 -0
- package/dist/assets/sha256-65KIjGvZ.js +1 -0
- package/dist/assets/useAddTarget-Bprwjjdn.js +1 -0
- package/dist/index.html +6 -3
- package/dist/sw.js +1 -1
- package/package.json +2 -2
- package/dist/assets/index-D6IkQaIy.js +0 -55
- package/dist/assets/sha256-Cs35JyRg.js +0 -1
|
@@ -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-BF5NzQ6H.js","assets/text-documents-F17vHvLW.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,En as d,Er as f,Et as p,Ft as m,Gn as h,Gr as g,Gt as _,Hn as v,Hr as y,Ir as b,It as x,J as S,Jr as C,Kr as w,L as T,Ln as E,Lr as D,Lt as O,Mr as k,Nt as ee,Or as A,Pt as te,Q as j,Qr as M,Rn as ne,Rr as re,Rt as N,Sr as P,St as ie,Tr as ae,Tt as oe,U as se,Un as ce,Ut as le,Vn as F,Vr as ue,Vt as de,W as fe,Wn as pe,Wr as me,Wt as I,X as L,Xn as he,Xr as ge,Y as _e,Yn as R,Yt as ve,Z as ye,Zt as be,_i as xe,ai as Se,an as z,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 B,ii as Fe,in as Ie,ir as Le,jn as Re,jt as ze,kn as Be,li as Ve,ln as He,lr as Ue,mn as We,mr as Ge,ni as Ke,nn as qe,nr as Je,nt as Ye,or as Xe,ot as Ze,pt as Qe,qn as $e,qr as et,qt as tt,rn as nt,rr as rt,rt as it,sr as at,st as ot,tr as st,tt as ct,ui as lt,un as ut,ur as dt,vn as ft,vr as pt,vt as mt,wt as ht,xr as gt,yr as _t,zr as vt,zt as yt}from"./ui-NWo4bzrd.js";import{t as V}from"./utils-2pl1SbIp.js";import{_ as bt,b as H,u as U,v as xt,x as W,y as St}from"./alert-dialog-CDKOX-MP.js";import{t as Ct}from"./socket-hM4c-ZSl.js";import{l as wt,s as Tt}from"./blobs-B3DY8Rsp.js";import{$ as Et,$t as Dt,A as Ot,At as kt,En as At,Fn as jt,Ft as Mt,Gn as Nt,Ht as Pt,In as Ft,It,J as Lt,Jn as Rt,Jt as zt,K as Bt,Kn as Vt,Lt as Ht,On as G,Ot as Ut,P as Wt,Pn as Gt,Pt as Kt,Rn as qt,Tt as Jt,Un as Yt,Vn as Xt,W as Zt,X as Qt,Y as $t,Yt as en,a as tn,bn as nn,bt as rn,c as an,d as on,dt as sn,en as cn,g as K,gt as ln,h as un,hn as dn,ht as fn,it as pn,jn as mn,jt as hn,k as gn,kn as _n,l as vn,mn as yn,nt as bn,pn as xn,q as Sn,qn as Cn,r as wn,s as Tn,t as En,u as Dn,v as On,vn as kn,wn as An,xn as jn,yn as Mn,zt as Nn}from"./workspace-BYMC2sfI.js";import{_ as Pn,a as Fn,c as In,d as Ln,f as Rn,g as zn,i as Bn,n as Vn,o as Hn,p as Un,r as Wn,s as Gn,t as Kn,v as qn,y as Jn}from"./text-documents-F17vHvLW.js";import{n as Yn}from"./map-BxCwdK0d.js";import{t as Xn}from"./search-COMZIxA7.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";var q=e(r(),1),ur=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,dr=/^[\\/]{2}/;function fr(e,t){return t+e.replace(/\\/g,`/`)}var pr=(e=>(e.Pop=`POP`,e.Push=`PUSH`,e.Replace=`REPLACE`,e))(pr||{}),mr=`popstate`;function hr(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function gr(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return br(``,{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:xr(t)}return Cr(t,n,null,e)}function J(e,t){if(e===!1||e==null)throw Error(t)}function _r(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function vr(){return Math.random().toString(36).substring(2,10)}function yr(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 br(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?Sr(t):t,state:n,key:t&&t.key||r||vr(),mask:i}}function xr({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 Sr(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 Cr(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=hr(e)?e:br(h.location,e,t);n&&n(r,e),l=u()+1;let d=yr(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=hr(e)?e:br(h.location,e,t);n&&n(r,e),l=u();let i=yr(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 wr(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(mr,d),c=e,()=>{i.removeEventListener(mr,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 wr(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:xr(t);return i=i.replace(/ $/,`%20`),!n&&dr.test(i)&&(i=r+i),new URL(i,r)}function Tr(e,t,n=`/`){return Er(e,t,n,!1)}function Er(e,t,n,r,i){let a=Gr((typeof t==`string`?Sr(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Dr(e),s=null,c=Wr(a);for(let e=0;s==null&&e<o.length;++e)s=Br(o[e],c,r);return s}function Dr(e){let t=Or(e);return Ar(t),t}function Or(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=$r([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}".`),Or(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:Rr(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Ur(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 kr(e.path))a(e,t,!0,n)}),t}function kr(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=kr(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 Ar(e){e.sort((e,t)=>e.score===t.score?zr(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var jr=/^:[\w-]+$/,Mr=3,Nr=2,Pr=1,Fr=10,Ir=-2,Lr=e=>e===`*`;function Rr(e,t){let n=e.split(`/`),r=n.length;return n.some(Lr)&&(r+=Ir),t&&(r+=Nr),n.filter(e=>!Lr(e)).reduce((e,t)=>e+(jr.test(t)?Mr:t===``?Pr:Fr),r)}function zr(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 Br(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?Hr(u,l,s.matcher,s.compiledParams):Vr(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=Vr({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:$r([a,d.pathname]),pathnameBase:ti($r([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=$r([a,d.pathnameBase]))}return o}function Vr(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Ur(e.path,e.caseSensitive,e.end);return Hr(e,t,n,r)}function Hr(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 Ur(e,t=!1,n=!0){_r(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 Wr(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return _r(!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 Gr(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 Kr(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?Sr(e):e,a;return n?(n=Qr(n),a=n.startsWith(`/`)?qr(n.substring(1),`/`):qr(n,t)):a=t,{pathname:a,search:ni(r),hash:ri(i)}}function qr(e,t){let n=ei(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Jr(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 Yr(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Xr(e){let t=Yr(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function Zr(e,t,n,r=!1){let i;typeof e==`string`?i=Sr(e):(i={...e},J(!i.pathname||!i.pathname.includes(`?`),Jr(`?`,`pathname`,`search`,i)),J(!i.pathname||!i.pathname.includes(`#`),Jr(`#`,`pathname`,`hash`,i)),J(!i.search||!i.search.includes(`#`),Jr(`#`,`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=Kr(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Qr=e=>e.replace(/[\\/]{2,}/g,`/`),$r=e=>Qr(e.join(`/`)),ei=e=>e.replace(/\/+$/,``),ti=e=>ei(e).replace(/^\/*/,`/`),ni=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,ri=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,ii=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 ai(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function oi(e){return $r(e.map(e=>e.route.path).filter(Boolean))||`/`}var si=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function ci(e,t){let n=e;if(typeof n!=`string`||!ur.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(si)try{let e=new URL(window.location.href),r=dr.test(n)?new URL(fr(n,e.protocol)):new URL(n),a=Gr(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{_r(!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 li=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(li);var ui=[`GET`,...li];new Set(ui);var di=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function fi(e){try{return di.includes(new URL(e).protocol)}catch{return!1}}var pi=q.createContext(null);pi.displayName=`DataRouter`;var mi=q.createContext(null);mi.displayName=`DataRouterState`;var hi=q.createContext(!1);function gi(){return q.useContext(hi)}var _i=q.createContext({isTransitioning:!1});_i.displayName=`ViewTransition`;var vi=q.createContext(new Map);vi.displayName=`Fetchers`;var yi=q.createContext(null);yi.displayName=`Await`;var bi=q.createContext(null);bi.displayName=`Navigation`;var xi=q.createContext(null);xi.displayName=`Location`;var Si=q.createContext({outlet:null,matches:[],isDataRoute:!1});Si.displayName=`Route`;var Ci=q.createContext(null);Ci.displayName=`RouteError`;var wi=`REACT_ROUTER_ERROR`,Ti=`REDIRECT`,Ei=`ROUTE_ERROR_RESPONSE`;function Di(e){if(e.startsWith(`${wi}:${Ti}:{`))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 Oi(e){if(e.startsWith(`${wi}:${Ei}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new ii(t.status,t.statusText,t.data)}catch{}}function ki(e,{relative:t}={}){J(Ai(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=q.useContext(bi),{hash:i,pathname:a,search:o}=zi(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:$r([n,a])),r.createHref({pathname:s,search:o,hash:i})}function Ai(){return q.useContext(xi)!=null}function ji(){return J(Ai(),`useLocation() may be used only in the context of a <Router> component.`),q.useContext(xi).location}var Mi=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Ni(e){q.useContext(bi).static||q.useLayoutEffect(e)}function Pi(){let{isDataRoute:e}=q.useContext(Si);return e?na():Fi()}function Fi(){J(Ai(),`useNavigate() may be used only in the context of a <Router> component.`);let e=q.useContext(pi),{basename:t,navigator:n}=q.useContext(bi),{matches:r}=q.useContext(Si),{pathname:i}=ji(),a=JSON.stringify(Xr(r)),o=q.useRef(!1);return Ni(()=>{o.current=!0}),q.useCallback((r,s={})=>{if(_r(o.current,Mi),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=Zr(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:$r([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var Ii=q.createContext(null);function Li(e){let t=q.useContext(Si).outlet;return q.useMemo(()=>t&&q.createElement(Ii.Provider,{value:e},t),[t,e])}function Ri(){let{matches:e}=q.useContext(Si);return e[e.length-1]?.params??{}}function zi(e,{relative:t}={}){let{matches:n}=q.useContext(Si),{pathname:r}=ji(),i=JSON.stringify(Xr(n));return q.useMemo(()=>Zr(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function Bi(e,t){return Vi(e,t)}function Vi(e,t,n){J(Ai(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=q.useContext(bi),{matches:i}=q.useContext(Si),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||``;ia(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=ji(),d;if(t){let e=typeof t==`string`?Sr(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})):Tr(e,{pathname:p});_r(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),_r(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=Ji(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:$r([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:$r([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(xi.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function Hi(){let e=ta(),t=ai(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 Ui=q.createElement(Hi,null),Wi=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=Oi(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:q.createElement(Si.Provider,{value:this.props.routeContext},q.createElement(Ci.Provider,{value:e,children:this.props.component}));return this.context?q.createElement(Ki,{error:e},t):t}};Wi.contextType=hi;var Gi=new WeakMap;function Ki({children:e,error:t}){let{basename:n}=q.useContext(bi);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=Di(t.digest);if(e){let r=Gi.get(t);if(r)throw r;let i=ci(e.location,n),a=i.absoluteURL||i.to;if(fi(a))throw Error(`Invalid redirect location`);if(si&&!Gi.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 Gi.set(t,n),n}}return q.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function qi({routeContext:e,match:t,children:n}){let r=q.useContext(pi);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),q.createElement(Si.Provider,{value:e},n)}function Ji(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:oi(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||Ui,o&&(s<0&&c===0?(ia(`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(qi,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?q.createElement(Wi,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Yi(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Xi(e){let t=q.useContext(pi);return J(t,Yi(e)),t}function Zi(e){let t=q.useContext(mi);return J(t,Yi(e)),t}function Qi(e){let t=q.useContext(Si);return J(t,Yi(e)),t}function $i(e){let t=Qi(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 ea(){return $i(`useRouteId`)}function ta(){let e=q.useContext(Ci),t=Zi(`useRouteError`),n=$i(`useRouteError`);return e===void 0?t.errors?.[n]:e}function na(){let{router:e}=Xi(`useNavigate`),t=$i(`useNavigate`),n=q.useRef(!1);return Ni(()=>{n.current=!0}),q.useCallback(async(r,i={})=>{_r(n.current,Mi),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var ra={};function ia(e,t,n){!t&&!ra[e]&&(ra[e]=!0,_r(!1,n))}q.memo(aa);function aa({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return Vi(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function oa({to:e,replace:t,state:n,relative:r}){J(Ai(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i}=q.useContext(bi);_r(!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(Si),{pathname:o}=ji(),s=Pi(),c=Zr(e,Xr(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 sa(e){return Li(e.context)}function ca(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 la({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){J(!Ai(),`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=Sr(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=q.useMemo(()=>{let e=Gr(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 _r(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(bi.Provider,{value:c},q.createElement(xi.Provider,{children:t,value:h}))}function ua({children:e,location:t}){return Bi(da(e),t)}q.Component;function da(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,da(e.props.children,i));return}J(e.type===ca,`[${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=da(e.props.children,i)),n.push(a)}),n}var fa=`get`,pa=`application/x-www-form-urlencoded`;function ma(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function ha(e){return ma(e)&&e.tagName.toLowerCase()===`button`}function ga(e){return ma(e)&&e.tagName.toLowerCase()===`form`}function _a(e){return ma(e)&&e.tagName.toLowerCase()===`input`}function va(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function ya(e,t){return e.button===0&&(!t||t===`_self`)&&!va(e)}function ba(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 xa(e,t){let n=ba(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Sa=null;function Ca(){if(Sa===null)try{new FormData(document.createElement(`form`),0),Sa=!1}catch{Sa=!0}return Sa}var wa=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Ta(e){return e!=null&&!wa.has(e)?(_r(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${pa}"`),null):e}function Ea(e,t){let n,r,i,a,o;if(ga(e)){let o=e.getAttribute(`action`);r=o?Gr(o,t):null,n=e.getAttribute(`method`)||fa,i=Ta(e.getAttribute(`enctype`))||pa,a=new FormData(e)}else if(ha(e)||_a(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?Gr(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||fa,i=Ta(e.getAttribute(`formenctype`))||Ta(o.getAttribute(`enctype`))||pa,a=new FormData(o,e),!Ca()){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(ma(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=fa,r=null,i=pa,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 Da(e,t){if(e===!1||e==null)throw Error(t)}function Oa(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&&Gr(i.pathname,t)===`/`?`${ei(t)}/_root.${r}`:`${ei(i.pathname)}.${r}`,i}async function ka(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 Aa(e){return e!=null&&typeof e.page==`string`}function ja(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 Ma(e,t,n){return La((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await ka(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(ja).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function Na(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 Pa(e,t,{includeHydrateFallback:n}={}){return Fa(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 Fa(e){return[...new Set(e)]}function Ia(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function La(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!Aa(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(Ia(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function Ra(){let e=q.useContext(pi);return Da(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function za(){let e=q.useContext(mi);return Da(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var Ba=q.createContext(void 0);Ba.displayName=`FrameworkContext`;function Va(){let e=q.useContext(Ba);return Da(e,`You must render this element inside a <HydratedRouter> element`),e}function Ha(e,t){let n=q.useContext(Ba),[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:Ua(s,p),onBlur:Ua(c,m),onMouseEnter:Ua(l,p),onMouseLeave:Ua(u,m),onTouchStart:Ua(d,p)}]:[a,f,{}]:[!1,f,{}]}function Ua(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Wa({page:e,...t}){let n=gi(),{nonce:r}=Va(),{router:i}=Ra(),a=q.useMemo(()=>Tr(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?q.createElement(Ka,{page:e,matches:a,...t}):q.createElement(qa,{page:e,matches:a,...t})):null}function Ga(e){let{manifest:t,routeModules:n}=Va(),[r,i]=q.useState([]);return q.useEffect(()=>{let r=!1;return Ma(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Ka({page:e,matches:t,...n}){let r=ji(),{future:i}=Va(),{basename:a}=Ra(),o=q.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=Oa(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 qa({page:e,matches:t,...n}){let r=ji(),{future:i,manifest:a,routeModules:o}=Va(),{basename:s}=Ra(),{loaderData:c,matches:l}=za(),u=q.useMemo(()=>Na(e,t,l,a,r,`data`),[e,t,l,a,r]),d=q.useMemo(()=>Na(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=Oa(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(()=>Pa(d,a),[d,a]),m=Ga(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 Ja(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}q.Component;var Ya=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Ya&&(window.__reactRouterVersion=`7.18.2`)}catch{}function Xa({basename:e,children:t,useTransitions:n,window:r}){let i=q.useRef();i.current??=gr({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(la,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var Za=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(bi),v=typeof l==`string`&&ur.test(l),y=ci(l,h);l=y.to;let b=ki(l,{relative:r}),x=ji(),S=null;if(o){let e=Zr(o,[],x.mask?x.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:$r([h,e.pathname])),S=g.createHref(e)}let[C,w,T]=Ha(n,p),E=no(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:Ja(m,w),target:c,"data-discover":!v&&t===`render`?`true`:void 0});return C&&!v?q.createElement(q.Fragment,null,k,q.createElement(Wa,{page:b})):k});Za.displayName=`Link`;var Qa=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=zi(a,{relative:c.relative}),d=ji(),f=q.useContext(mi),{navigator:p,basename:m}=q.useContext(bi),h=f!=null&&co(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=Gr(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(Za,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Qa.displayName=`NavLink`;var $a=q.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=fa,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=q.useContext(bi),g=oo(),_=so(s,{relative:l}),v=o.toLowerCase()===`get`?`get`:`post`,y=typeof s==`string`&&ur.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})});$a.displayName=`Form`;function eo(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function to(e){let t=q.useContext(pi);return J(t,eo(e)),t}function no(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=Pi(),d=ji(),f=zi(e,{relative:o});return q.useCallback(p=>{if(ya(p,t)){p.preventDefault();let t=n===void 0?xr(d)===xr(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 ro(e){_r(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(ba(e)),n=q.useRef(!1),r=ji(),i=q.useMemo(()=>xa(r.search,n.current?null:t.current),[r.search]),a=Pi();return[i,q.useCallback((e,t)=>{let r=ba(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var io=0,ao=()=>`__${String(++io)}__`;function oo(){let{router:e}=to(`useSubmit`),{basename:t}=q.useContext(bi),n=ea(),r=e.fetch,i=e.navigate;return q.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=Ea(e,t);if(a.navigate===!1){let e=a.fetcherKey||ao();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 so(e,{relative:t}={}){let{basename:n}=q.useContext(bi),r=q.useContext(Si);J(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...zi(e||`.`,{relative:t})},o=ji();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:$r([n,a.pathname])),xr(a)}function co(e,{relative:t}={}){let n=q.useContext(_i);J(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=to(`useViewTransitionState`),i=zi(e,{relative:t});if(!n.isTransitioning)return!1;let a=Gr(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Gr(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Vr(i.pathname,o)!=null||Vr(i.pathname,a)!=null}var lo=e(o(),1),Y=n(),uo=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(xe,{ref:n,className:V(`text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70`,e),...t}));uo.displayName=xe.displayName;var fo=a();function po(){let e=localStorage.getItem(`authToken`);return!e||e===`canvas-server-token`?null:e}var mo=new class{socket=null;connected=!1;authToken=null;handlers=new Map;socketWrappers=new Map;desiredSubscriptions=new Set;baseUrl;connectionId=``;constructor(){this.baseUrl=St,this.connectionId=`socket-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}connect(e){let t=e||po();!t||t===`canvas-server-token`||this.socket&&this.authToken===t||(this.cleanupSocket(),this.authToken=t,this.socket=Ct(this.baseUrl,{transports:[`websocket`],autoConnect:!1,reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:3e4,randomizationFactor:.5,timeout:1e4,forceNew:!0,extraHeaders:{Authorization:`Bearer ${t}`,"X-Connection-ID":this.connectionId},auth:{token:t}}),this.setupDefaultHandlers(),this.registerHandlers(),this.socket.connect())}cleanupSocket(){this.socket?.removeAllListeners(),this.socket?.disconnect(),this.socket=null,this.connected=!1,this.socketWrappers.clear()}setupDefaultHandlers(){this.socket&&(this.socket.on(`connect`,()=>{this.connected=!0;for(let e of this.desiredSubscriptions)this.socket?.emit(`subscribe`,{channel:e})}),this.socket.on(`disconnect`,()=>{this.connected=!1}),this.socket.on(`connect_error`,()=>{this.connected=!1}))}registerHandlers(){this.socket&&this.handlers.forEach((e,t)=>{e.forEach(e=>{this.attach(t,e)})})}attach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e);if(n||(n=new Map,this.socketWrappers.set(e,n)),n.has(t))return;let r=(...e)=>t(...e);n.set(t,r),this.socket.on(e,r)}detach(e,t){if(!this.socket)return;let n=this.socketWrappers.get(e),r=n?.get(t);r&&(this.socket.off(e,r),n?.delete(t),n&&n.size===0&&this.socketWrappers.delete(e))}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);let n=this.handlers.get(e);return n.has(t)?()=>this.off(e,t):(n.add(t),this.socket&&this.attach(e,t),()=>this.off(e,t))}off(e,t){let n=this.handlers.get(e);n&&n.has(t)&&(n.delete(t),n.size===0&&this.handlers.delete(e),this.detach(e,t))}request(e,t,n=1e4){return new Promise((r,i)=>{if(!this.socket||!this.connected){i(Error(`Socket not connected`));return}let a=!1,o=setTimeout(()=>{a||(a=!0,i(Error(`Socket request timed out: ${e}`)))},n);try{this.socket.emit(e,t??{},t=>{a||(a=!0,clearTimeout(o),t?.status===`error`?i(Error(t.message||`${e} failed`)):r(t?.payload??t))})}catch(e){a=!0,clearTimeout(o),i(e instanceof Error?e:Error(String(e)))}})}emit(e,...t){if(e===`subscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.add(e)}else if(e===`unsubscribe`){let e=t?.[0]?.channel;typeof e==`string`&&e&&this.desiredSubscriptions.delete(e)}if(this.socket&&this.connected)try{this.socket.emit(e,...t)}catch(t){console.error(`Error emitting event ${e}:`,t),this.reconnect()}else this.connect()}disconnect(){this.cleanupSocket(),this.authToken=null,this.desiredSubscriptions.clear()}isConnected(){return this.connected}retryNow(){this.connected||(this.cleanupSocket(),this.connect())}reconnect(){this.connect()}};function ho({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`})]})}async function go(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 _o(e){return`/workspaces/${e}/hooks`}async function vo(e){return await U.get(_o(e))||[]}async function yo(e,t){return(await U.get(`${_o(e)}/${t}`))?.content??``}async function bo(e,t,n){await U.put(`${_o(e)}/${t}`,{content:n})}async function xo(e,t){await U.delete(`${_o(e)}/${t}`)}var So=[`example-`,`disabled-`,`_`];function Co(e){let t=e.lastIndexOf(`/`);return{dir:t===-1?``:e.slice(0,t+1),base:t===-1?e:e.slice(t+1)}}function wo(e){return So.find(t=>e.startsWith(t))??null}function To(e){return wo(Co(e).base)===null}function Eo(e){return Co(e).base.startsWith(`example-`)}function Do(e){let{dir:t,base:n}=Co(e),r=wo(n);return t+(r?n.slice(r.length):`disabled-${n}`)}async function Oo(e,t,n){if(To(t)===n)return t;let r=Do(t);return await bo(e,r,await yo(e,t)),await xo(e,t),r}function ko(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 Ao(e){let t=e.when?.event;return Array.isArray(t)?t.map(String):t?[String(t)]:[]}function jo(e){let t=e.when?.eventPathExact??e.when?.pathExact??e.when?.path;return Array.isArray(t)?t.map(String):typeof t==`string`?[t]:[]}function Mo(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 No(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 Po(e){return String(e||``).replace(/^[a-z]+:/i,``).split(`/`).filter(Boolean).join(`/`)}var Fo=`rules.json`;async function Io(e){try{let t=await yo(e,Fo),n=JSON.parse(t||`{}`);return Array.isArray(n.rules)?n.rules:[]}catch{return[]}}async function Lo(e,t){await bo(e,Fo,JSON.stringify({$schema:`canvas.hook-rules/v1`,rules:t},null,2)+`
|
|
5
|
+
`)}async function Ro(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 U.get(`${_o(e)}/pending${r?`?${r}`:``}`)||[]}async function zo(e,t){return await U.post(`${_o(e)}/pending/decisions`,t)}async function Bo(e,t){return await U.get(`${_o(e)}/runs/${encodeURIComponent(t)}`)}async function Vo(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 U.get(`${_o(e)}/runs${r?`?${r}`:``}`)||[]}var Ho=1e4,Uo=`canvas.hooks.backfillLimit`;function Wo(e){let t=Math.floor(Number(e));return!Number.isFinite(t)||t<1?100:Math.min(t,Ho)}function Go(){try{let e=localStorage.getItem(Uo);return e?Wo(e):100}catch{return 100}}function Ko(e){let t=Wo(e);try{localStorage.setItem(Uo,String(t))}catch{}return t}function qo(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 Jo(e,t){return await U.post(`${_o(e)}/backfill`,t)}async function Yo(e,t){return await U.post(`${_o(e)}/run`,t)}async function Xo(e,t){return await U.post(`${_o(e)}/runs/${t}/replay`,{})}async function Zo(e){return await U.get(`${_o(e)}/meta`)}async function Qo(e,t){return await U.post(`${_o(e)}/generate`,t)}async function $o(e,t){let n=await yo(e,Fo),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 bo(e,Fo,JSON.stringify(o,null,2)+`
|
|
6
|
+
`)}var es=$o;function ts(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 ns(e,t){return e.slice(0,3).map(e=>{let n=t.get(e.id),r=e.reason===`not-found`?`Source missing from the storage index. Resync the source backend and retry.`:e.reason===`not found`?`Document no longer exists in this workspace. Refresh the list and select it again.`:e.reason;return`${n?`${n} (ID ${e.id})`:`Document ${e.id}`}: ${r}`}).join(`
|
|
7
|
+
`)+(e.length>3?`\n…and ${e.length-3} more failed file${e.length===4?``:`s`}.`:``)}function rs(){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 is(){let[e]=(0,q.useState)(rs);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 as(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 os(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 ss=e=>typeof e==`string`?e:``,cs=e=>e&&typeof e==`object`?e:{},ls=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\r/g,`\\r`).replace(/\n/g,`\\n`).replace(/\t/g,`\\t`);function us(e){let t=e.data||{},n=e.schema===`data/schema/message/email`,r=!n&&e.schema.startsWith(`data/schema/message`),i=ss(t.platform),a=ss(cs(t.channel).id)||ss(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=ss(cs(t.from).address)||ss(t.from);e&&s(`sender`,`Mail from ${e}`,{from:{equals:e}}),t.subject&&s(`subject`,`Subject matches regex`,{subject:{regex:ls(t.subject)}})}else if(r){let e=ss(cs(t.sender).id)||ss(cs(t.sender).username)||ss(cs(t.sender).name)||ss(t.sender),n=ss(cs(t.sender).name)||ss(cs(t.sender).username)||e;e&&s(`sender`,`Messages from ${n}`,{...c,sender:{equals:e}})}let l=ss(t.body)||ss(t.text)||ss(t.content)||ss(t.bodyHtml)||ss(t.bodyPreview);if((n||r||l)&&s(`body`,n?`Email body matches regex`:`Text matches regex`,{...c,body:{regex:ls(l.slice(0,160))}}),r){let n=ss(t.threadId)||([`slack`,`teams`].includes(i)?ss(cs(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:ls(t.url)}}),s(`schema`,`All items of this type`,{}),o}var ds=[];function fs(e){if(e.key!==`Escape`||e.isComposing||e.defaultPrevented)return;let t=ds[ds.length-1];t&&(e.preventDefault(),t())}function ps(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 ds.push(e),ds.length===1&&window.addEventListener(`keydown`,fs),()=>{let t=ds.indexOf(e);t>=0&&ds.splice(t,1),ds.length===0&&window.removeEventListener(`keydown`,fs)}},[r])}function ms({label:e,onClose:t,children:n}){return ps(t),(0,lo.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 hs(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 gs(e){return`/workspaces/${e}/scripts`}async function _s(e){return await U.get(gs(e))||[]}async function vs(e,t){return(await U.get(`${gs(e)}/${t}`))?.content??``}async function ys(e,t,n){await U.put(`${gs(e)}/${t}`,{content:n})}async function bs(e,t){await U.delete(`${gs(e)}/${t}`)}var xs=e=>`${bt.workspaces}/${encodeURIComponent(e)}/messages`,Ss=e=>U.get(`${xs(e)}/accounts`),Cs=(e,t)=>U.get(`${xs(e)}/reply-target/${t}`),ws=(e,t)=>U.post(`${xs(e)}/send`,t),Ts=(e,t)=>U.get(`${xs(e)}/whatsapp/${encodeURIComponent(t)}/connection`),Es=(e,t)=>U.get(`${xs(e)}/outbox/${encodeURIComponent(t)}`),Ds=(e,t)=>U.delete(`${xs(e)}/whatsapp/${encodeURIComponent(t)}/connection`),Os=(e,t)=>U.get(`${xs(e)}/thread/${t}`),ks=`h-full w-[380px] max-w-[90vw] max-md:w-full`;function As({onClose:e,children:t}){return(0,lo.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)}function js({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 ps(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,lo.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:V(`fixed z-menu max-h-viewport-modal overflow-y-auto`,r,`bg-popover text-popover-foreground`),children:i})]}),document.body)}var Ms=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),Ns={Delete:`Del`,Backspace:`⌫`,Enter:`↵`,ArrowUp:`↑`,ArrowDown:`↓`};function Ps(e){let t=e.split(`+`),n=t.pop()||``,r=Ns[n]||(n.length===1?n.toUpperCase():n);if(Ms){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 Fs(e,t){let n=t.split(`+`),r=n.pop()||``;return(Ms?e.metaKey:e.ctrlKey)!==n.includes(`Mod`)||e.shiftKey!==n.includes(`Shift`)||e.altKey!==n.includes(`Alt`)||Ms&&e.ctrlKey!==n.includes(`Ctrl`)?!1:r.length===1?e.key.toLowerCase()===r.toLowerCase():e.key===r}function Is(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 Ls(e,t){if(e.defaultPrevented||e.nativeEvent.isComposing||Is(e.target))return!1;let n=t.find(t=>t.shortcut&&!t.disabled&&Fs(e,t.shortcut));return n?(e.preventDefault(),e.stopPropagation(),n.run({shiftKey:e.shiftKey}),!0):!1}function Rs(e){return e.key===`ContextMenu`||e.key===`F10`&&e.shiftKey}function zs(){return typeof window<`u`&&window.matchMedia(`(max-width: 767px)`).matches}function Bs(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 Vs(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 Hs(e,t,n){t(),setTimeout(()=>{e.run({shiftKey:n})},0)}function Us({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)(js,{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:Vs(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||Hs(e,n,t.shiftKey)},className:V(`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:Ps(e.shortcut)})]},e.id)})]},`${e[0].group??``}:${t}`))})})}function Ws({items:e,onClose:t,header:n}){ps(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,lo.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)(T,{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:[Vs(e).map((e,n)=>(0,Y.jsxs)(`div`,{className:V(`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=>Hs(e,t,n.shiftKey),className:V(r,e.destructive&&`border-destructive/30 text-destructive`,e.disabled&&`opacity-50`),children:[n&&(0,Y.jsx)(n,{className:V(`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 Gs({anchor:e,items:t,onClose:n,label:r,header:i}){return t.length===0?null:zs()?(0,Y.jsx)(Ws,{items:t,onClose:n,header:i??(r&&(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:r}))}):(0,Y.jsx)(Us,{anchor:e,items:t,onClose:n,label:r})}var Ks=null;function qs(){return Ks||=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(()=>(Ks=null,[])),Ks}async function Js(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 Ys=`ph:folder-fill`,Xs=`ph:squares-four-fill`,Zs=`ph:stack-fill`,Qs=[`#ef4444`,`#f97316`,`#f59e0b`,`#eab308`,`#84cc16`,`#22c55e`,`#14b8a6`,`#06b6d4`,`#3b82f6`,`#6366f1`,`#8b5cf6`,`#a855f7`,`#ec4899`,`#f43f5e`,`#64748b`,`#78716c`],$s={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`}},ec={"workspace:home":{icon:`ph:house-fill`,color:`#3b82f6`},"workspace:data":{icon:`ph:database-fill`,color:`#14b8a6`}},tc={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`}},nc={icon:`ph:hard-drive-fill`,color:`#64748b`};function rc(e){let t=e.config?.ui??{},n=e.address&&ec[e.address]||e.driver&&tc[e.driver]||nc;return{icon:typeof t.icon==`string`?t.icon:n.icon??nc.icon,color:typeof t.color==`string`?t.color:n.color??nc.color}}function ic(e){let t=e.metadata?.ui??{},n=$s[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 ac(e){let t=$s[(e.split(`/`).filter(Boolean).pop()??``).trim().toLowerCase()];return t?{metadata:oc(void 0,t)}:null}function oc(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 sc=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,cc=()=>({h:sc(0,360),s:sc(42,98),l:sc(40,90)}),lc=(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)}`},uc=()=>{let{h:e,s:t,l:n}=cc();return lc(e,t,n)},dc=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)},fc=(e,t=.82)=>{let n=dc(e);return n===null||n>t},pc=e=>e&&!fc(e)?e:void 0,mc=e=>{if(!e)return`text-muted-foreground/70`;let t=dc(e);return t!==null&&t>.5?`text-black/45`:`text-white/80`},hc=e=>{let t=dc(e);return t!==null&&(t+.05)/.05>=1.05/(t+.05)?`text-black`:`text-white`},gc=[{color:`text-data-1`,chip:`bg-data-1/15`},{color:`text-data-2`,chip:`bg-data-2/15`},{color:`text-data-3`,chip:`bg-data-3/15`},{color:`text-data-4`,chip:`bg-data-4/15`},{color:`text-data-5`,chip:`bg-data-5/15`},{color:`text-data-6`,chip:`bg-data-6/15`},{color:`text-data-7`,chip:`bg-data-7/15`},{color:`text-data-8`,chip:`bg-data-8/15`},{color:`text-data-9`,chip:`bg-data-9/15`},{color:`text-data-10`,chip:`bg-data-10/15`},{color:`text-data-11`,chip:`bg-data-11/15`},{color:`text-data-12`,chip:`bg-data-12/15`}];function X(e,t){return{Icon:e,...gc[t-1]}}var _c={tab:X(F,7),link:X(F,7),email:X(z,3),note:X(ct,3),task:X(Ce,5),message:X(be,6),identity:X(se,2),contact:X(se,2),device:X(tt,10),application:X(le,11),dotfile:X(B,4),document:X(Le,9)},vc=[{test:/^image\//,spec:X(Be,5)},{test:/^video\//,spec:X(Je,11)},{test:/^audio\//,spec:X(I,10)},{test:/pdf$/,spec:X(Le,1)},{test:/zip|tar|gzip|7z|rar|compressed/,spec:X(Ue,12)},{test:/json|javascript|typescript|xml|html|css|x-sh|python/,spec:X(Ee,6)},{test:/^text\//,spec:X(Le,12)}],yc=X(rt,6),bc=X(rt,9);function xc(e){let t=(e.schema||``).split(`/`).pop()||``;if(t===`file`){let t=String(e.metadata?.contentType||``).toLowerCase();return vc.find(({test:e})=>e.test(t))?.spec||yc}return _c[t]||bc}var Sc={3.5:`h-3.5 w-3.5`,4:`h-4 w-4`,5:`h-5 w-5`,10:`h-10 w-10`};function Cc(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 wc({document:e,size:t=4,chip:n=!1,className:r}){let i=xc(e),a=e.schema===`data/schema/tab`?Cc(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:V(Sc[t],`rounded-xs object-contain`,!n&&`shrink-0`,!n&&r)}):(0,Y.jsx)(i.Icon,{className:V(Sc[t],i.color,!n&&`shrink-0`,!n&&r)});return n?(0,Y.jsx)(`span`,{className:V(`inline-flex shrink-0 items-center justify-center rounded-md`,t>=10?`p-3`:`p-1`,i.chip,r),children:l}):l}function Tc({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:V(`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=V(`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:V(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 Ec(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 Dc={context:(0,Y.jsx)(v,{className:`h-3.5 w-3.5`}),directory:(0,Y.jsx)(h,{className:`h-3.5 w-3.5`}),backends:(0,Y.jsx)(ne,{className:`h-3.5 w-3.5`}),relations:(0,Y.jsx)(Qe,{className:`h-3.5 w-3.5`})},Oc={context:`Context tree`,directory:`Directory tree`,backends:`Backends tree`,relations:`Relations`};function kc(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function Ac(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 jc(e,t,n){let r=kc(t,e.name);return r.toLowerCase().includes(n)||(e.label||``).toLowerCase().includes(n)?!0:e.children?.some(e=>jc(e,r,n))??!1}var Mc=200;function Nc({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)(P,{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 Pc({node:e,parentPath:t,query:n,selected:r,onToggle:a,onActivate:o,onRowMenu:s,createParent:c,onCreateConfirm:l,onCreateCancel:u,creating:d}){let f=kc(t,e.name),p=!!e.children?.length,[m,h]=(0,q.useState)(!1),{handlers:g,guardClick:_}=Ac(f,s);if(n&&!jc(e,t,n))return null;let v=c===f,y=m||n.length>0||v,b=r.has(f),x=e.type===`canvas`,S=ic(e);return(0,Y.jsxs)(`div`,{children:[(0,Y.jsxs)(`div`,{className:V(`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:V(`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)(ue,{className:`w-4 h-4`}):(0,Y.jsx)(vt,{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:pc(S.color),className:V(`shrink-0`,!pc(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)(Nc,{busy:d,onConfirm:e=>{h(!0),l(f,e)},onCancel:u}),y&&e.children?.map(e=>(0,Y.jsx)(Pc,{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 Fc({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=pc(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:V(`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)(vt,{className:`h-4 w-4 shrink-0 text-muted-foreground`})]},e.id||e.name)})})}function Ic({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,E]=(0,q.useState)(``),[D,O]=(0,q.useState)(t),k=n?t:D,ee=e=>{p(`/`),c(`folder`),C(``),E(``),a?.(`/`),n?n(e):O(e)},[A,te]=(0,q.useState)(k);k!==A&&(te(k),p(`/`),c(`folder`)),(0,q.useEffect)(()=>{let e=setTimeout(()=>E(S.trim()),300);return()=>clearTimeout(e)},[S]),(0,q.useEffect)(()=>{let t=!1;async function n(){_(!0);try{let n=await Bt(e,k);t||h(n)}catch{t||h(null)}finally{t||_(!1)}}return n(),()=>{t=!0}},[e,k]),(0,q.useEffect)(()=>{if(s!==`documents`)return;let t=!1,n=k===`directory`?`directory`:En,r=k===`context`?`context`:`directory`;async function i(){x(!0);try{let i=w?await pn(e,f,[],{treeName:n,treeType:r,q:w,limit:Mc}):await Sn(e,f,n,{limit:Mc});t||y(i.payload||[])}catch{t||y([])}finally{t||x(!1)}}return i(),()=>{t=!0}},[e,k,f,s,w]);let j=e=>{p(e),a?.(e)},M=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:()=>ee(e),className:V(`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 ${Oc[e].toLowerCase()}`,children:[Dc[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)(vt,{className:`h-3.5 w-3.5`})]})]}),(0,Y.jsx)(Tc,{items:Ec(f,e),onNavigate:j,label:`Folder path`}),(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(mt,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,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:V(`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:()=>j(`/`),onDoubleClick:()=>{j(`/`),c(`documents`)},title:`/`,children:[(0,Y.jsx)(ue,{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)(Pc,{node:e,parentPath:`/`,query:d,selected:new Set([f]),onToggle:j,onActivate:e=>{j(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)(vt,{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)(Tc,{items:Ec(f,e),onNavigate:j,label:`Document folder path`})]}),(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(mt,{className:`pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,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)(T,{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…`}):M.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.`}):M.map(e=>{let t=Gt(e),n=r.has(e.id);return(0,Y.jsxs)(`div`,{onClick:()=>i(e.id),className:V(`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)(wc,{document:e,size:3.5}),(0,Y.jsx)(`span`,{className:`flex-1 truncate`,children:t.title})]},e.id)})})]})}function Lc({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,E]=(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),ee=g?.length?g:[...wn],[A,j]=(0,q.useState)(ee[0]??`references`),[M,ne]=(0,q.useState)(`out`),[re,N]=(0,q.useState)(new Set),[P,ie]=(0,q.useState)(null),[ae,oe]=(0,q.useState)(`context`),[se,ce]=(0,q.useState)(!1),le=O===`pins`?ae:O;(0,q.useEffect)(()=>{if(!w)return;let e=!1;return Ut(w).then(t=>{e||ie(t)}).catch(()=>{e||ce(!0)}),()=>{e=!0}},[w]);let F=O===`relations`,[de,fe]=(0,q.useState)(null),[pe,me]=(0,q.useState)(!1),[I,L]=(0,q.useState)(new Set),[he,ge]=(0,q.useState)(``),_e=he.trim().toLowerCase(),{showErrorToast:ve}=Tt(),[ye,be]=(0,q.useState)(null),[xe,Se]=(0,q.useState)(null),[z,Ce]=(0,q.useState)(!1);ps(e,!o&&!z);let we=Ac(`/`,e=>be(e)),Te=e=>!o&&(O===`backends`?p?.canCreate(e)===!0:O!==`pins`&&O!==`relations`),Ee=async(e,t)=>{let n=t.trim().replace(/^\/+|\/+$/g,``);if(!(!n||!w||z||!Te(e))){Ce(!0);try{let t=`${e===`/`?``:e}/${n}`,r=O===`context`?En:O;O===`backends`?await p.create(e,n):await fn(w,t,!0,r),ln(w,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:w,treeName:r,cacheInvalidated:!0}}));let i=await Bt(w,O);fe(i),L(e=>a?new Set([...e,t]):new Set([t])),ge(``),Se(null)}catch(e){ve(e instanceof Error?e.message:`Failed to create folder`)}finally{Ce(!1)}}},[De,Oe]=(0,q.useState)(r);r!==De&&(Oe(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||me(!0);try{let n=await Bt(w,O);!e&&r===t&&fe(n)}catch{!e&&r===t&&!n&&fe(null)}finally{!e&&r===t&&me(!1)}}let r=e=>{let t=e.detail;t?.workspaceName&&t.workspaceName!==w||t?.treeName&&t.treeName!==O||(t?.cacheInvalidated||ln(w,O),n(!0))};return window.addEventListener(`workspace:tree:refresh`,r),n(),()=>{e=!0,window.removeEventListener(`workspace:tree:refresh`,r)}},[w,O]);let ke=e=>{e!==w&&(ie(null),ce(!1)),k(D),E(e),L(new Set),N(new Set),y(`tree`)},Ae=e=>{N(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},je=e=>{if(!a){L(new Set([e]));return}L(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},Me=F?re.size>0&&!!m:I.size>0,Pe=async()=>{if(!(!w||o||!Me)){if(F){await m?.({predicate:A,direction:M,targetIds:Array.from(re)},{workspaceName:h??w});return}await t(Array.from(I),{workspaceName:w,treeName:le===`context`?En:le,treeType:le===`context`?`context`:`directory`})}},B=n??1;return o&&s?(0,Y.jsx)(`div`,{className:V(`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:V(`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…`:F?`Relate ${B} document${B===1?``:`s`} to…`:`Link ${B} document${B===1?``:`s`} to…`)]}),(0,Y.jsx)(`button`,{type:`button`,onClick:e,disabled:o||z,className:`text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40`,"aria-label":`Close`,children:(0,Y.jsx)(T,{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)(Fc,{workspaces:b,loading:S,onPick:ke})}),(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:z,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)(vt,{className:`h-4 w-4 rotate-180`})}),(l.includes(`context`)||l.includes(`directory`))&&(0,Y.jsxs)(`button`,{type:`button`,disabled:z,onClick:()=>{k(`pins`),L(new Set),Se(null)},className:V(`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)(te,{className:`h-3.5 w-3.5`}),`Pins`]}),l.map(e=>(0,Y.jsxs)(`button`,{type:`button`,disabled:z,onClick:()=>{k(e),L(new Set),Se(null)},className:V(`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:[Dc[e],Oc[e]]},e))]}),!F&&(0,Y.jsx)(`div`,{className:`shrink-0 border-b p-2`,children:(0,Y.jsxs)(`div`,{className:`relative`,children:[(0,Y.jsx)(mt,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground`}),(0,Y.jsx)(`input`,{type:`text`,placeholder:`Search paths…`,value:he,onChange:e=>ge(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`})]})}),F&&(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:A,onChange:e=>j(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:ee.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 ${B===1?`document`:`documents`} you started from ${A} the picked one(s)`},{dir:`in`,label:`Picked → this`,hint:`the picked document(s) ${A} the ${B===1?`one`:`ones`} you started from`}].map(({dir:e,label:t,hint:n})=>(0,Y.jsx)(`button`,{type:`button`,title:n,onClick:()=>ne(e),className:V(`flex-1 rounded-md border px-2 py-1.5 text-xs transition-colors`,M===e?`border-primary bg-primary text-primary-foreground`:`border-input hover:bg-accent`),children:t},e))})]}),!F&&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:[!I.size&&(0,Y.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Selected folders appear here`}),Array.from(I).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:()=>je(e),className:`shrink-0 rounded-full hover:bg-primary-foreground/20`,"aria-label":`Remove ${e}`,children:(0,Y.jsx)(T,{className:`h-3 w-3`})})]},e))]}),F&&(h??w)&&(0,Y.jsx)(Ic,{workspaceName:h??w,treeTab:`context`,selectedDocIds:re,onToggleDoc:Ae,excludeDocumentIds:_}),O===`pins`&&(0,Y.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto p-3 space-y-2`,children:[!P&&!se&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading pins…`}),se&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Could not load pins. You can still browse the trees.`}),!se&&P?.length===0&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No pinned paths yet. Choose a path from a tree.`}),P?.filter(e=>e.resolvable!==!1&&l.includes(e.tree===`context`?`context`:e.tree)&&`${e.label??e.name??``} ${e.path}`.toLowerCase().includes(_e)).map(e=>{let t=e.tree===`context`?`context`:e.tree;return(0,Y.jsxs)(`button`,{type:`button`,"aria-pressed":ae===t&&I.has(e.path),className:V(`w-full rounded-md border p-3 text-left text-sm hover:bg-muted`,ae===t&&I.has(e.path)&&`border-primary bg-primary/10`),onClick:()=>{ae===t?je(e.path):(oe(t),L(new Set([e.path])))},children:[(0,Y.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,Y.jsx)(te,{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:V(`min-h-0 flex-1 space-y-1.5 overflow-y-auto p-3`,(F||O===`pins`)&&`hidden`),children:pe?(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:V(`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`,I.has(`/`)?`bg-primary/[0.08] hover:bg-primary/[0.12] before:bg-primary`:`bg-card hover:bg-primary/[0.04] before:bg-transparent`),onClick:we.guardClick(()=>je(`/`)),title:`/`,...Te(`/`)?we.handlers:{},children:[(0,Y.jsx)(ue,{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:[xe===`/`&&(0,Y.jsx)(Nc,{busy:z,onConfirm:e=>Ee(`/`,e),onCancel:()=>Se(null)}),de?.children?.length?de.children.map(e=>(0,Y.jsx)(Pc,{node:e,parentPath:`/`,query:_e,selected:I,onToggle:je,onRowMenu:e=>{Te(e.path)&&be(e)},createParent:xe,onCreateConfirm:Ee,onCreateCancel:()=>Se(null),creating:z},e.id||e.name)):xe===`/`?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:F?`${re.size} document${re.size===1?``:`s`} selected`:`${I.size} path${I.size===1?``:`s`} selected`}),(0,Y.jsx)(W,{size:`sm`,onClick:Pe,disabled:!Me||o||z,children:o?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(ho,{className:`mr-1.5 h-3.5 w-3.5`}),F?`Relating…`:`Linking…`]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Ne,{className:`mr-1 h-3.5 w-3.5`}),F?`Relate`:f??`Link`]})})]}),ye&&(0,Y.jsx)(Us,{anchor:{x:ye.clientX,y:ye.clientY},onClose:()=>be(null),items:[{id:`new-folder`,label:`New folder in ${ye.path}`,icon:R,run:()=>Se(ye.path)}]})]})}function Rc({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),g=e.match(/^(.*?):\/\//)?.[0]||``,_=g?e.slice(g.length):e;return(0,Y.jsxs)(`div`,{className:V(`flex gap-2`,u),children:[f===`breadcrumbs`?(0,Y.jsx)(Tc,{items:Ec(_,g.replace(`://`,``)||r||`Workspace`),onNavigate:e=>t(g?`${g}${e.replace(/^\/+/,``)}`:e),disabled:l,className:V(`rounded border px-1`,d)}):(0,Y.jsx)(H,{id:c,value:e,onChange:e=>t(e.target.value),placeholder:s,disabled:l,className:V(`font-mono`,d)}),(0,Y.jsx)(W,{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)(h,{className:`h-4 w-4`})}),p&&(0,Y.jsx)(As,{onClose:()=>m(!1),children:(0,Y.jsx)(Lc,{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 zc=[{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`}],Bc=[{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.`}],Vc=[{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`}],Hc=new Set([`toExact`,`fromExact`,`senderExact`,`threadExact`,`channelExact`,`platformExact`]),Uc=e=>Hc.has(e)?e.replace(/Exact$/,``):e.replace(/Regex$/,``),Wc=[{key:`sendFile`,label:`Send file(s) via a channel`,icon:z,tone:`text-blue-600 dark:text-blue-400 bg-blue-500/10`},{key:`extractAttachments`,label:`Extract email attachments to a folder`,icon:z,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`moveMessage`,label:`Move the email to a mail folder`,icon:z,tone:`text-teal-600 dark:text-teal-400 bg-teal-500/10`},{key:`store`,label:`Copy/Move file(s) to a storage backend`,icon:ne,tone:`text-sky-600 dark:text-sky-400 bg-sky-500/10`},{key:`download`,label:`download what the link points at`,icon:Me,tone:`text-rose-600 dark:text-rose-400 bg-rose-500/10`},{key:`link`,label:`file it into a folder`,icon:$e,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`},{key:`unlink`,label:`remove it from a folder`,icon:$e,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`tag`,label:`add tags`,icon:j,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`},{key:`unstore`,label:`delete the file from a storage backend`,icon:_e,tone:`text-amber-600 dark:text-amber-400 bg-amber-500/10`},{key:`notify`,label:`Send me a notification`,icon:Ke,tone:`text-pink-600 dark:text-pink-400 bg-pink-500/10`},{key:`agent`,label:`ask an agent`,icon:M,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:L,tone:`text-destructive bg-destructive/10`},{key:`destroy`,label:`delete it everywhere`,icon:L,tone:`text-destructive bg-destructive/10`}],Gc=e=>Wc.find(t=>t.key===e)||Wc[1],Kc=`{{title}}{{ext}}`,qc=`{{YYYY}}/{{MM}}/{{YYYY}}{{MM}}{{DD}}_{{HH}}{{mm}}{{ss}}{{ext}}`,Jc=[{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.`}],Yc=[{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}),Xc={id:null,description:``,events:[`document.inserted`],schema:``,cascade:!1,approval:!1,conditions:[],actions:[Z(`link`)]},Zc=e=>e.split(`|`).map(e=>e.trim()).filter(Boolean);function Qc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`rule-${Math.random().toString(36).slice(2,7)}`}var $c=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),el=[{id:`send-invoices`,title:`Send invoice PDFs to accounting`,icon:z,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:()=>({...Xc,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:z,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:()=>({...Xc,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:ne,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})=>({...Xc,description:`Copy/Move file(s) to a storage backend`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``}],actions:[{...Z(`store`),a:e,recursive:!0}]})},{id:`photos`,title:`Sort photos by date`,icon:Be,tone:`text-emerald-600 dark:text-emerald-400 bg-emerald-500/10`,blurb:`Images filed into a folder are stored as Photos / 2024 / 07 / 20240714_183012.jpg — by the time the photo was taken (EXIF), not uploaded.`,build:({backend:e})=>({...Xc,description:`Sort photos by date`,schema:`file`,events:[`document.inserted`,`document.linked`],conditions:[{field:`path`,value:``},{field:`mime`,value:`image/*`}],actions:[{...Z(`store`),a:e,storeFolder:`Photos`,storeName:`dated`}]})},{id:`mirror`,title:`Mirror a storage folder`,icon:$e,tone:`text-violet-600 dark:text-violet-400 bg-violet-500/10`,blurb:`Everything that appears under a folder of a storage backend shows up 1:1 in the Directory tree.`,build:()=>({...Xc,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:z,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:()=>({...Xc,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})=>({...Xc,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:M,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:()=>({...Xc,description:`Summarize new items`,actions:[{...Z(`agent`),b:`Read document #{{doc.id}} in full with canvas_get, then summarize it in three bullet points.`,notifyReply:!0}]})},{id:`blank`,title:`Start from scratch`,icon:Ze,tone:`text-muted-foreground bg-muted`,blurb:`An empty rule: choose what it reacts to, add conditions and actions.`,build:()=>({...Xc})}];function tl(e){let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field));if(t.length!==1||t[0].field!==`eventPathExact`)return null;let n=Zc(t[0].value);return n.length===1&&/^(ctx|context):\//.test(n[0])?n[0].replace(/^(ctx|context):/,``).replace(/\/+$/,``)||`/`:null}function nl(e){if(tl(e)!==null)return!0;let t=e.filter(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)).flatMap(e=>Zc(e.value));return t.length>0&&t.every(e=>/^(dir|directory|backends):\//.test(e))}function rl(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=tl(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`?qc:e.b||`<filename>`].filter(Boolean).join(`/`)}}function il(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=Hc.has(t.field),a=e||n?t.value.trim()?[t.value]:[]:Zc(t.value);if(e&&a.length)try{new RegExp(t.value,`i`)}catch{throw Error(`Invalid regular expression for ${Vc.find(e=>e.key===t.field)?.label}: ${t.value}`)}if(!a.length)throw Error(`Enter a value for ${Vc.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[Uc(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=$c(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:$c(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:$c(r),...s,...i?{tags:$c(i)}:{}}),n.kind===`unlink`&&r&&o.push({action:`unlink`,paths:$c(r),...s}),n.kind===`tag`&&r&&o.push({action:`tag`,tags:$c(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&&!nl(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`?Kc:n.storeName===`dated`?qc: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&&tl(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=$c(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:$c(i)}:{},...n.dlTags.trim()?{tags:$c(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||Qc(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 al(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`&&Bc.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(Hc.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||tl(y)===null)||t.recursive===!0&&tl(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===Kc||e===qc?``:e,storeFolder:typeof t.folder==`string`?t.folder:``,recursive:t.recursive===!0,storeName:e?e===Kc?`title`:e===qc?`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(!Jc.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 ol=(e,t)=>t.find(t=>t.value===e)?.label?.replace(/\s\(\d+\)$/,``)||(e?String(e).replace(/^data\/schema\//,``):`any item`);function sl(e,t=zc){let n=e.when,r=Ao(e).map(e=>Bc.find(t=>t.value===e)?.label||e).join(` or `),i=[`When ${ol(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 cl(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 ll(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===Kc?`, named by title`:e.key===qc?`, 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=Jc.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=cl(e);return`ask agent "${e.slug}"${t?` (${t})`:``}`}if(e.action===`script`){let t=cl(e);return`run ${e.path}${t?` (${t})`:``}`}return e.action}function ul(e){return(e.then||[]).map(ll).join(` · `)||`(no actions)`}function dl(e){return jo(e).length>0&&(e.then||[]).length>0&&(e.then||[]).every(e=>e.action===`link`||e.action===`unlink`||e.action===`store`||e.action===`unstore`)}function fl(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 pl(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 ml(e){return e.some(e=>e.address===`workspace:home`)?`workspace:home`:e.find(e=>e.address!==`workspace:data`)?.address||e[0]?.address||``}function hl(e){if(e.kind===`document`&&e.rule)return{...al(e.rule)||Xc,id:null};if(e.kind===`download`){let t=e.path?` filed under ${e.path.replace(/^(ctx|dir):/,``)}`:``;return{...Xc,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{...Xc,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:nl(r)}]}}return{...Xc,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 gl=`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:V(`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 _l({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:V(`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:V(`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:V(`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 vl({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:V(`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 yl({active:e,onClick:t,children:n,title:r}){return(0,Y.jsx)(`button`,{type:`button`,title:r,onClick:t,"aria-pressed":e,className:V(`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 bl({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 xl({icon:e,tone:t,size:n=`md`}){return(0,Y.jsx)(`span`,{className:V(`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 Sl({workspaceId:e,onOpenJson:t,onShowRuns:n,backfillLimit:r,prefill:i,onPrefillConsumed:a,createOnly:o=!1,onCreated:s,onCancel:c}){let{showToast:l}=wt(),[u,d]=(0,q.useState)([]),[f,p]=(0,q.useState)({}),m=e=>{Vo(e,{limit:500}).then(e=>p(fl(e))).catch(()=>p({}))},[g,_]=(0,q.useState)(!0),[v,y]=(0,q.useState)(null),[b,x]=(0,q.useState)(!1),[S,C]=(0,q.useState)(!1),[w,E]=(0,q.useState)([]),[D,ee]=(0,q.useState)([]),[A,te]=(0,q.useState)([]),[j,M]=(0,q.useState)(``),ne=(0,q.useRef)(null),[re,N]=(0,q.useState)(e);e!==re&&(N(e),_(!0)),(0,q.useEffect)(()=>{Io(e).then(e=>d(e)).finally(()=>_(!1)),m(e)},[e]);let[P,ae]=(0,q.useState)(null);i!==P&&(ae(i),i&&(y(hl(i)),x(!1))),(0,q.useEffect)(()=>{i&&a?.()},[i,a]),(0,q.useEffect)(()=>{_s(e).then(e=>E(e.map(e=>e.path))).catch(()=>E([]))},[e]),(0,q.useEffect)(()=>{let t=!1;return Ss(e).then(e=>{t||(te([...new Map(e.map(e=>[`${e.driver}:${e.address}`,e])).values()]),M(``))}).catch(()=>{t||(te([]),M(`Sending accounts could not be loaded.`))}),()=>{t=!0}},[e]),(0,q.useEffect)(()=>{rn(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);ee(t);let n=ml(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(()=>ee([]))},[e]);let[oe,se]=(0,q.useState)(zc);(0,q.useEffect)(()=>{Zo(e).then(e=>{e.schemas?.length&&se([{value:``,label:`any item`},...e.schemas.map(e=>({value:e.id,label:`${e.name} (${e.count})`}))])}).catch(()=>{})},[e]);let ce=async(t,n)=>{C(!0);try{return await Lo(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)}},le=async()=>{if(!v||g||S)return;let t;try{t=il(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 $o(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 ce(n,v.id?`Rule updated`:`Rule created`)&&(y(null),s?.())},F=e=>ce(u.map(t=>t.id===e?{...t,enabled:t.enabled===!1}:t),`Rule toggled`),de=e=>{confirm(`Delete rule "${e}"?`)&&ce(u.filter(t=>t.id!==e),`Rule deleted`)},[fe,pe]=(0,q.useState)(null),me=async t=>{pe(t);try{let n=await Jo(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 Jo(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{pe(null),m(e)}},I=(e,t)=>y(n=>n&&{...n,[e]:t}),he=e=>{y(e.build({backend:ml(D)})),x(!1),requestAnimationFrame(()=>ne.current?.scrollIntoView({behavior:`smooth`,block:`start`}))},_e=e=>{let n=al(e);n?(y(n),x(!1),requestAnimationFrame(()=>ne.current?.scrollIntoView({behavior:`smooth`,block:`start`}))):t?.()},[R,ve]=(0,q.useState)(null),ye=(e,t)=>t.treeType===`context`?e:t.treeName===`directory`?`dir:${e}`:`${t.treeName}:${e}`,be=(e,t)=>{if(!R||!v||!e.length){ve(null);return}if(R.target===`storeFolder`){let t=Mo(e[0]);I(`actions`,v.actions.map((e,n)=>n===R.index?{...e,storeFolder:t?.rel||``,...t?.backend&&D.some(e=>e.address===t.backend)?{a:t.backend}:{}}:e))}else if(R.target===`condition`){let n=e.map(e=>ye(e,t)),r=t.treeType===`context`&&v.actions.some(e=>e.kind===`store`);I(`conditions`,v.conditions.map((e,t)=>t===R.index?{...e,...r?{field:`eventPathExact`}:{},value:n.join(` | `)}:e))}else{let n=e.map(e=>ye(e,t));I(`actions`,v.actions.map((e,t)=>t===R.index?e.kind===`download`?{...e,b:n.join(`, `)}:{...e,a:n.join(`, `)}:e))}ve(null)},xe=(e,t,n=`Browse…`)=>(0,Y.jsxs)(W,{type:`button`,size:`sm`,variant:`outline`,className:`h-10 shrink-0 px-3`,title:n,onClick:()=>ve({target:e,index:t}),children:[(0,Y.jsx)(h,{className:`h-4 w-4 sm:mr-1.5`}),(0,Y.jsx)(`span`,{className:`hidden sm:inline`,children:`Browse`})]}),Se=nl(v?.conditions||[]),z=!!v?.conditions.some(e=>[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&e.value.trim()),Ce=e=>`${e.address}${e.address===`workspace:data`?` — managed blob store (default)`:e.address===`workspace:home`?` — workspace home folder`:e.driver?` — ${e.driver}`:``}`,we=(e,t,n,r=`workspace:home`)=>D.length?(0,Y.jsxs)(`select`,{className:gl,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:Ce(e)},e.address)),e&&!D.some(t=>t.address===e)&&(0,Y.jsx)(`option`,{value:e,children:e})]}):(0,Y.jsx)(H,{className:V(Q,`font-mono`),placeholder:r,value:e,onChange:e=>t(e.target.value)}),Ee=u.filter(dl),De=u.filter(e=>!dl(e)),Oe=({rule:e})=>{let t=e.enabled!==!1,r=al(e)!==null,i=f[e.id],a=Gc(e.then?.[0]?.action||`link`),o=jo(e);return(0,Y.jsxs)(`div`,{className:V(`rule-card rounded-xl border bg-card p-4 transition-opacity`,!t&&`opacity-60`),children:[(0,Y.jsx)(xl,{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:sl(e,oe)}),(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:ul(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:V(`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,` `,pl(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:()=>F(e.id),className:V(`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:V(`h-5 w-5 rounded-full bg-background shadow transition-transform`,t&&`translate-x-5`)})}),(0,Y.jsxs)(W,{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:fe!==null||e.when.eventPathExact!==void 0,onClick:()=>me(e.id),children:[fe===e.id?(0,Y.jsx)(ut,{className:`h-4 w-4 animate-spin`}):(0,Y.jsx)(k,{className:`h-4 w-4`}),(0,Y.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Apply`})]}),(0,Y.jsxs)(W,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5`,title:r?`Edit rule`:`Edit as JSON`,onClick:()=>_e(e),children:[r?(0,Y.jsx)(O,{className:`h-4 w-4`}):(0,Y.jsx)(ge,{className:`h-4 w-4`}),(0,Y.jsx)(`span`,{className:`rule-card-action-label ml-1.5`,children:`Edit`})]}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,className:`h-9 px-2.5 text-destructive hover:text-destructive`,title:`Delete rule`,onClick:()=>de(e.id),children:(0,Y.jsx)(L,{className:`h-4 w-4`})})]})]})},ke=(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)(W,{size:`sm`,variant:`ghost`,onClick:()=>x(!1),children:[(0,Y.jsx)(T,{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:el.map(e=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>he(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)(xl,{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)(W,{variant:`ghost`,onClick:t,title:`Edit rules.json directly`,children:[(0,Y.jsx)(ge,{className:`mr-1.5 h-4 w-4`}),` JSON`]}),(0,Y.jsxs)(W,{onClick:()=>{y(null),x(!0)},disabled:b,children:[(0,Y.jsx)(ze,{className:`mr-1.5 h-4 w-4`}),` New rule`]})]})]}),b&&!v&&ke,v&&(0,Y.jsxs)(`div`,{ref:ne,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)(W,{variant:`ghost`,size:`sm`,onClick:()=>y(null),children:[(0,Y.jsx)(T,{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)(H,{className:`h-11 text-base`,placeholder:`Keep UI designs in Projects/Canvas/UI`,value:v.description,onChange:e=>I(`description`,e.target.value)})}),(0,Y.jsxs)(`section`,{className:`space-y-4`,children:[(0,Y.jsx)(bl,{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:gl,value:v.schema,onChange:e=>I(`schema`,e.target.value),children:[oe.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value)),v.schema&&!oe.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:Bc.map(e=>{let t=v.events.includes(e.value);return(0,Y.jsx)(yl,{active:t,title:e.hint,onClick:()=>{let n=t?v.events.filter(t=>t!==e.value):[...v.events,e.value];n.length&&I(`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=Vc.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=>Uc(t.field)===Uc(e.field))?`or`:`and`}),(0,Y.jsx)(`select`,{className:gl,value:e.field,onChange:e=>I(`conditions`,v.conditions.map((n,r)=>r===t?{...n,field:e.target.value}:n)),children:Vc.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)(H,{className:V(Q,`font-mono`),placeholder:n?.hint,value:e.value,onChange:e=>I(`conditions`,v.conditions.map((n,r)=>r===t?{...n,value:e.target.value}:n))}),[`path`,`pathExact`,`eventPathExact`].includes(e.field)&&xe(`condition`,t,`Browse the workspace trees`)]}),(0,Y.jsx)(W,{size:`sm`,variant:`ghost`,className:`order-3 h-10 w-10 p-0 text-muted-foreground sm:order-4`,title:`Remove condition`,onClick:()=>I(`conditions`,v.conditions.filter((e,n)=>n!==t)),children:(0,Y.jsx)(T,{className:`h-4 w-4`})})]},t)})}),(0,Y.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Y.jsxs)(W,{size:`sm`,variant:`outline`,onClick:()=>I(`conditions`,[...v.conditions,{field:v.schema===`email`?`from`:`path`,value:``}]),children:[(0,Y.jsx)(ze,{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)(bl,{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=>I(`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=Se&&a,s=Gc(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)(Rc,{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)(H,{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)(H,{className:V(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:gl,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)(Rc,{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)(_l,{checked:t.notifyReply,onChange:e=>r({notifyReply:e}),label:`Send me a notification with the result`})]}),l=tl(v.conditions),u=t.kind===`store`&&t.a&&(!t.recursive||o)?rl(t,v.conditions,i):null,d=t.kind===`extractAttachments`&&t.a?hs(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)(xl,{icon:s.icon,tone:s.tone}),(0,Y.jsx)(`select`,{className:V(gl,`flex-1 font-medium`),value:t.kind,onChange:e=>r(Z(e.target.value)),children:Wc.map(e=>(0,Y.jsx)(`option`,{value:e.key,children:e.label},e.key))}),(0,Y.jsx)(W,{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:()=>I(`actions`,v.actions.filter((e,t)=>t!==n)),children:(0,Y.jsx)(T,{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)(H,{className:V(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})}),xe(`action`,n)]})}),t.kind===`link`&&(0,Y.jsx)($,{label:`Tags`,hint:`Optional, comma-separated.`,children:(0,Y.jsx)(H,{className:V(Q,`font-mono`),placeholder:`custom/design, ui`,value:t.b,onChange:e=>r({b:e.target.value})})}),(0,Y.jsx)(_l,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:z?`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:!z})]}),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)(H,{className:V(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)(H,{className:V(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:we(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)(H,{className:V(Q,`font-mono`),placeholder:`Projects/Canvas/UI`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),xe(`storeFolder`,n,`Browse storage backends`)]})}),(0,Y.jsx)($,{label:`File name`,children:(0,Y.jsx)(`select`,{className:gl,value:t.storeName,onChange:e=>r({storeName:e.target.value}),children:Yc.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)(vl,{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:we(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)(H,{className:V(Q,`font-mono`),placeholder:`{{YYYY}}-{{MM}}-{{DD}} {{title}}{{ext}}`,value:t.b,onChange:e=>r({b:e.target.value})})})]}),(0,Y.jsx)(_l,{checked:t.recursive,onChange:e=>r({recursive:e}),label:l===null?`Recreate sub-folder path in destination`:`Recreate directory path in destination`,hint:a?Se?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)(ue,{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:we(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:gl,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)(H,{className:V(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)(H,{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:we(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)(H,{className:V(Q,`font-mono`),placeholder:`Accounting`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),xe(`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)(H,{className:V(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:gl,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)(_l,{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:Jc.find(e=>e.value===t.dlKind)?.hint,children:(0,Y.jsx)(`select`,{className:gl,value:t.dlKind,onChange:e=>r({dlKind:e.target.value}),children:Jc.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)(H,{type:`number`,min:1,max:5,className:V(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:we(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)(H,{className:V(Q,`font-mono`),placeholder:`Downloads`,value:t.storeFolder,onChange:e=>r({storeFolder:e.target.value})}),xe(`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)(H,{className:V(Q,`font-mono`),placeholder:`same folders as the link`,value:t.b,onChange:e=>r({b:e.target.value})}),xe(`action`,n)]})}),(0,Y.jsx)($,{label:`Tags for the download`,hint:`Optional, comma-separated.`,children:(0,Y.jsx)(H,{className:V(Q,`font-mono`),placeholder:`downloaded, custom/paper`,value:t.dlTags,onChange:e=>r({dlTags:e.target.value})})})]}),(0,Y.jsx)(_l,{checked:t.recursive,onChange:e=>r({recursive:e}),label:`Recreate sub-folder path in destination`,hint:z?`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:!z}),(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:we(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:we(t.b,e=>r({b:e}),`anywhere else`,`workspace:home (optional)`)})]}),(0,Y.jsx)(_l,{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:gl,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)(H,{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)(H,{className:Q,placeholder:`invoice`,value:t.attachmentName,onChange:e=>r({attachmentName:e.target.value})})})]}),t.sendSource===`attachments`&&(0,Y.jsx)(_l,{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:gl,value:t.a?`${t.sendDriver}:${t.a}`:``,onChange:e=>{let t=A.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&&!A.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)`]}),A.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}`))]})}),j&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,role:`status`,children:j}),(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)(H,{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)(H,{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)(H,{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)(H,{className:V(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.
|
|
8
|
+
|
|
9
|
+
Subject: {{doc.data.subject}}
|
|
10
|
+
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:V(gl,`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)(H,{className:V(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)(W,{size:`sm`,variant:`outline`,onClick:()=>I(`actions`,[...v.actions,Z(`tag`)]),children:[(0,Y.jsx)(ze,{className:`mr-1 h-4 w-4`}),` Add another action`]})]}),(0,Y.jsxs)(`section`,{className:`space-y-3`,children:[(0,Y.jsx)(bl,{step:3,title:`Options`}),(0,Y.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,Y.jsx)(_l,{checked:v.approval,onChange:e=>I(`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)(_l,{checked:v.cascade,onChange:e=>I(`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)(W,{className:`h-10 px-5`,onClick:le,disabled:S||g,children:[S?(0,Y.jsx)(ut,{className:`mr-1.5 h-4 w-4 animate-spin`}):(0,Y.jsx)(ie,{className:`mr-1.5 h-4 w-4`}),` `,v.id?`Save changes`:`Create rule`]}),(0,Y.jsx)(W,{className:`h-10`,variant:`outline`,onClick:()=>{y(null),c?.()},children:`Cancel`})]})]}),R&&(0,Y.jsx)(As,{onClose:()=>ve(null),children:(0,Y.jsx)(Lc,{sizeClassName:`h-full w-[380px] max-w-[90vw] max-md:w-full`,fixedWorkspaceName:e,multiple:R.target!==`storeFolder`&&!(R.target===`condition`&&v?.actions.some(e=>e.kind===`store`)),tabs:R.target===`condition`?[`context`,`directory`,`backends`]:R.target===`storeFolder`?[`backends`]:[`context`,`directory`],title:R.target===`condition`?`Choose source folder…`:R.target===`storeFolder`?`Store files under…`:`File into…`,confirmLabel:R.target===`storeFolder`?`Use folder`:`Use path`,onConfirm:be,onClose:()=>ve(null)})}),!o&&(g?(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…”.`})]}),ke]}):(0,Y.jsxs)(`div`,{className:`space-y-6`,children:[Ee.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)($e,{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:Ee.map(e=>(0,Y.jsx)(Oe,{rule:e},e.id))})]}),De.length>0&&(0,Y.jsxs)(`section`,{className:`space-y-3`,children:[Ee.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)(Ze,{className:`h-4 w-4`}),` Other rules`]}),(0,Y.jsx)(`div`,{className:`space-y-3`,children:De.map(e=>(0,Y.jsx)(Oe,{rule:e},e.id))})]})]}))]})}function Cl({workspaceId:e,document:t,onClose:n}){let[r,i]=(0,q.useState)(null),[a,o]=(0,q.useState)(``),[s,c]=(0,q.useState)(``);ps(n),(0,q.useEffect)(()=>{let n=!1;return(async()=>{if(!os(await Et(e)))throw Error(`Only workspace administrators can create rules.`);let r=await bn(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?us(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)(ms,{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)(T,{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)(Sl,{workspaceId:e,prefill:d,createOnly:!0,onCreated:n,onCancel:n})]}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading document…`})]})})}function wl(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 Tl(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 El(e,t,n,r){let i=new Set(r?n:[]);for(let n of t)Tl(e,n.bounds)&&i.add(n.id);return i}var Dl=`[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 Ol(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=wl(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(El(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(Dl))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 kl({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 Ol(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 Al(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 jl({workspaceId:e,ids:t,onClose:n,modal:r=!1}){let{showProgress:i}=wt();ps(n,r);let[a]=(0,q.useState)(()=>{try{return Al(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 un(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`:ks,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)(W,{variant:`ghost`,onClick:()=>{try{localStorage.removeItem(a)}catch{}s(null),d(``)},children:`Discard remaining`}),!_&&!c&&(0,Y.jsx)(W,{onClick:()=>void h(o),children:`Resume copy`}),(0,Y.jsx)(W,{variant:_?`default`:`outline`,onClick:g,children:_?`Done`:c?`Pause & close`:`Close`})]})]}):(0,Y.jsx)(Lc,{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)(ms,{label:`Copy to workspace`,onClose:g,children:y}):(0,Y.jsx)(As,{onClose:g,children:y})}function Ml({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)(T,{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))})]})]})}function Nl(e,t,n){return{...t.length?{features:[...new Set([...e.features??e.metadata?.features??[],...Jn(e.data?.tags??[]),...Jn(t)])]}:{},...n?{geo:n}:{}}}function Pl(e,t,n,r){return{id:e.id,schema:e.schema,schemaVersion:e.schemaVersion,metadata:Nl(e,t,n),...r===void 0?{}:{comment:r.trim()}}}var Fl=e(Yn(),1),Il=`#8b5cf6`,Ll=`https://nominatim.openstreetmap.org`,Rl=700,zl=e=>Math.round(e*1e6)/1e6;function Bl(){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:${Il};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 Fl.default.divIcon({html:e,className:`canvas-map-pick`,iconSize:[28,28],iconAnchor:[14,28]})}function Vl({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),[b,x]=(0,q.useState)(!1),[S,C]=(0,q.useState)(!1);(0,q.useEffect)(()=>{let e=requestAnimationFrame(()=>C(!0));return()=>cancelAnimationFrame(e)},[]),ps(n);let w=(0,q.useCallback)((e,t,n)=>{let r=i.current;if(!r)return;let o=Fl.default.latLng(e,t);a.current?a.current.setLatLng(o):(a.current=Fl.default.marker(o,{icon:Bl(),draggable:!0,autoPan:!0}).addTo(r),a.current.on(`dragend`,()=>{let e=a.current.getLatLng();c({lat:zl(e.lat),lon:zl(e.lng)})})),c({lat:zl(e),lon:zl(t),...n?{label:n}:{}})},[]);(0,q.useEffect)(()=>{let t=r.current;if(!t||i.current)return;let n=Fl.default.map(t,{center:e?[e.lat,e.lon]:[20,0],zoom:e?13:2,worldCopyJump:!0,zoomControl:!0});Fl.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(`${Ll}/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))},Rl);return()=>{clearTimeout(r),n.abort()}},[s]);let E=(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(`${Ll}/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(Fl.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,lo.createPortal)((0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{className:V(`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:V(`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)(Ie,{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)(T,{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)(mt,{className:`pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground`}),(0,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(),E())},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:b,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:b?(0,Y.jsx)(ut,{className:`h-3.5 w-3.5 animate-spin`}):(0,Y.jsx)(He,{className:`h-3.5 w-3.5`})}),(0,Y.jsxs)(`button`,{type:`button`,onClick:E,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)(ut,{className:`h-3.5 w-3.5 animate-spin`}):(0,Y.jsx)(mt,{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)(_t,{className:`h-3 w-3 shrink-0 text-muted-foreground`}),s.lat.toFixed(5),`, `,s.lon.toFixed(5),_&&(0,Y.jsx)(ut,{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)(y,{className:`h-3.5 w-3.5`}),`Use this point`]})]})]})]})]}),document.body)}var Hl={exif:`from the photo's EXIF`,device:`from the device at capture`,manual:`placed by hand`};function Ul(e){let t=`${e.lat.toFixed(5)}, ${e.lon.toFixed(5)}`,n=e.source?Hl[e.source]:null;return[t,e.accuracy==null?null:`±${e.accuracy} m`,n].filter(Boolean).join(` · `)}function Wl({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)(uo,{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)(Ie,{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?Ul(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)(nt,{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)(L,{className:`h-3.5 w-3.5`})})]})]}),r&&(0,Y.jsx)(Vl,{initial:e,onPick:e=>t({lat:e.lat,lon:e.lon,source:`manual`}),onClose:()=>i(!1)})]})}function Gl({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 ps(n,!m),(0,lo.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)(Ml,{tags:r,onChange:i,suggestions:[]})]}),(0,Y.jsx)(Wl,{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)(W,{variant:`outline`,onClick:n,disabled:m,children:`Cancel`}),(0,Y.jsx)(W,{onClick:async()=>{if(m||!d)return;h(!0),_(``);let t=[];for(let n of f)try{let t=await bn(e,n);await An(e,Pl(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 Kl=e=>`/${e}`.replace(/\/+/g,`/`).replace(/\/$/,``)||`/`;function ql(e,t,n,r){return typeof e.sourcePath==`string`&&!!t&&e.sourceWorkspaceId===t&&!!n&&e.sourceTreeName===n&&Kl(e.sourcePath)===Kl(r)}var Jl=[{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)(L,{className:`h-3.5 w-3.5`})}],Yl=[{value:`rename`,label:`Rename mine (file-1.ext)`},{value:`overwrite`,label:`Overwrite the existing file`},{value:`error`,label:`Skip the document`}],Xl=`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 Zl(e){return e.driver===`cacache`?pt:e.config?.remote===!0?f:ne}function Ql({workspaceId:e,documentCount:t,initialMode:n=`copy`,defaultFilename:r=``,onConfirm:i,onClose:a,saving:o=!1,sizeClassName:s,deleteFrom:c,progress:l,stopping:d=!1,onStop:f}){let{showErrorToast:p}=Tt(),[m,g]=(0,q.useState)(!1);ps(a,!o&&!m);let[_,v]=(0,q.useState)(n),[y,b]=(0,q.useState)(null),[x,C]=(0,q.useState)(null),[w,E]=(0,q.useState)(()=>new Set(n===`delete`&&c?[c.backend]:[])),[D,O]=(0,q.useState)(!1),[k,ee]=(0,q.useState)(``),[A,te]=(0,q.useState)(r),[j,M]=(0,q.useState)(`rename`);(0,q.useEffect)(()=>{let t=!1;return rn(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));E(e=>new Set([...e].filter(e=>n.has(e))))}).catch(e=>{t||C(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let re=_===`move`,N=e=>e.enabled===!1?`disabled`:e.config?.readOnly===!0?`read-only`:e.config?.supported===!1?`unsupported`:null,P=(0,q.useMemo)(()=>(y||[]).filter(e=>!N(e)).map(e=>e.address),[y,_]),ie=e=>{v(e),E(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)})},ae=e=>{E(t=>{if(re)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})},oe=(0,q.useMemo)(()=>(y||[]).filter(e=>w.has(e.address)&&vn(e)),[y,w]),se=_!==`delete`&&oe.length>0,ce=e=>{let t=an(e,y||[]),n=t&&y?.find(e=>e.address===t.address);return!!n&&!N(n)&&_!==`delete`&&!o},le=async(t,n)=>{let r=an(t,y||[]);if(!r||!ce(t))throw Error(`Choose a writable file backend folder`);await tn(e,r.driver,r.address,[[r.key,n].filter(Boolean).join(`/`)])},F=e=>{g(!1);let t=on(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(N(n)){p(`${n.address} is ${N(n)}`);return}if(!vn(n)){p(`${n.address} does not keep folders — objects are stored by content`);return}ee(t.key),E(e=>re?new Set([t.address]):new Set([...e,t.address]))},ue=async()=>{w.size===0||o||await i([...w],_,{keepDocument:D,folder:se?k.trim():``,filename:se&&t===1?A.trim():``,onConflict:j})},de=t,fe=de===1?``:`s`,pe=_===`delete`?`Delete ${de} document${fe} from…`:`${_===`move`?`Move`:`Copy`} ${de} document${fe} to…`,me=_===`delete`?`Delete from`:_===`move`?`Move to`:`Copy to`,I=w.size===0?me.split(` `)[0]:`${me} ${w.size} backend${w.size===1?``:`s`}`;return(0,Y.jsxs)(`div`,{className:V(`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)(ne,{className:`h-4 w-4`}),pe]}),(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)(T,{className:`h-4 w-4`})})]}),(0,Y.jsx)(`div`,{className:`flex shrink-0 items-center gap-1 border-b px-2 pt-2`,children:Jl.map(({mode:e,label:t,icon:n})=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>ie(e),disabled:o,className:V(`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=Zl(e),n=N(e),r=w.has(e.address),i=e.config?.remote===!0;return(0,Y.jsxs)(`div`,{onClick:()=>!n&&!o&&ae(e.address),className:V(`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:re?`radio`:`checkbox`,checked:r,disabled:!!n||o,onChange:()=>ae(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.`})]})]}),se&&(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 `,oe.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)(H,{id:`backend-transfer-folder`,value:k,onChange:e=>ee(e.target.value),placeholder:`/`,disabled:o,className:`h-9 font-mono text-xs`}),(0,Y.jsx)(W,{type:`button`,variant:`outline`,size:`icon`,className:`h-9 w-9 shrink-0`,onClick:()=>g(!0),disabled:o,"aria-label":`Browse backend folders`,title:`Browse…`,children:(0,Y.jsx)(h,{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)(H,{id:`backend-transfer-filename`,value:A,onChange:e=>te(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:Xl,value:j,onChange:e=>M(e.target.value),disabled:o,children:Yl.map(e=>(0,Y.jsx)(`option`,{value:e.value,children:e.label},e.value))})]})]}),_===`move`&&P.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)(W,{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)(W,{size:`sm`,variant:_===`delete`?`destructive`:`default`,onClick:ue,disabled:w.size===0||o,children:o?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(ho,{className:`mr-1.5 h-3.5 w-3.5`}),`Working…`]}):(0,Y.jsxs)(Y.Fragment,{children:[_===`delete`?(0,Y.jsx)(L,{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`}),I]})})]}),_===`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)(S,{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)(As,{onClose:()=>g(!1),children:(0,Y.jsx)(Lc,{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:ce,create:le},onConfirm:F,onClose:()=>g(!1)})})]})}function $l({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:V(`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)(Xe,{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)(T,{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)(Fc,{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)(vt,{className:`h-4 w-4 rotate-180`})}),[`context`,`directory`].map(e=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>{m(e),g(new Set)},className:V(`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:[Dc[e],Oc[e]]},e))]}),d&&(0,Y.jsx)(Ic,{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)(W,{size:`sm`,onClick:async()=>{!d||h.size===0||r||await t(Array.from(h),{workspaceName:d,treeName:p===`directory`?`directory`:En,treeType:p})},disabled:h.size===0||r,children:r?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(ho,{className:`mr-1.5 h-3.5 w-3.5`}),`Adding…`]}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(Xe,{className:`mr-1 h-3.5 w-3.5`}),`Add`]})})]})]})}var eu=(0,q.createContext)(null),tu={entry:null,open:()=>{},close:()=>{}};function nu(){return(0,q.useContext)(eu)??tu}function ru(e){let{id:t,...n}=e;return n}var iu=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`div`,{className:`relative w-full overflow-auto`,children:(0,Y.jsx)(`table`,{ref:n,className:V(`w-full caption-bottom text-sm`,e),...t})}));iu.displayName=`Table`;var au=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`thead`,{ref:n,className:V(`[&_tr]:border-b`,e),...t}));au.displayName=`TableHeader`;var ou=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`tbody`,{ref:n,className:V(`[&_tr:last-child]:border-0`,e),...t}));ou.displayName=`TableBody`;var su=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`tfoot`,{ref:n,className:V(`border-t bg-muted/50 font-medium [&>tr]:last:border-b-0`,e),...t}));su.displayName=`TableFooter`;var cu=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`tr`,{ref:n,className:V(`border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted`,e),...t}));cu.displayName=`TableRow`;var lu=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`th`,{ref:n,className:V(`h-12 px-2 md:px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0`,e),...t}));lu.displayName=`TableHead`;var uu=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`td`,{ref:n,className:V(`p-2 md:p-4 align-middle [&:has([role=checkbox])]:pr-0`,e),...t}));uu.displayName=`TableCell`;var du=q.forwardRef(({className:e,...t},n)=>(0,Y.jsx)(`caption`,{ref:n,className:V(`mt-4 text-sm text-muted-foreground`,e),...t}));du.displayName=`TableCaption`;var fu=({label:e,sortKey:t,sort:n,onSort:r,className:i})=>{let a=n.key===t;return(0,Y.jsx)(lu,{"aria-sort":a?n.dir===`asc`?`ascending`:`descending`:`none`,className:V(`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)(Fe,{className:`h-3.5 w-3.5`}):(0,Y.jsx)(De,{className:`h-3.5 w-3.5`}):(0,Y.jsx)(b,{className:`h-3.5 w-3.5 opacity-40`})]})})};fu.displayName=`SortableTableHead`;function pu(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 mu=`workspace:relations:refresh`;function hu(){window.dispatchEvent(new CustomEvent(mu))}var gu=(0,q.createContext)(null),_u=`canvas:documentOpenMode`;function vu(){try{return localStorage.getItem(_u)===`modal`?`modal`:`side`}catch{return`side`}}var yu=vu(),bu=new Set;function xu(){return yu}function Su(e){try{localStorage.setItem(_u,e)}catch{}yu=e;for(let e of bu)e()}function Cu(e){bu.add(e);let t=t=>{(t.key===_u||t.key===null)&&(yu=vu(),e())};return window.addEventListener(`storage`,t),()=>{bu.delete(e),window.removeEventListener(`storage`,t)}}function wu(){return(0,q.useSyncExternalStore)(Cu,xu,()=>`side`)}function Tu({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)(mt,{size:17})})]})}function Eu({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)(mt,{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)(T,{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 Du({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 Ou({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,E]=(0,q.useState)(!1),D=(0,q.useRef)(null),O=(0,q.useRef)(null),k=(0,q.useRef)(null),ee=(0,q.useRef)(!1),A=JSON.stringify([e,n,r,a]),[te,j]=(0,q.useState)(A);te!==A&&(j(A),C(!1)),(0,q.useEffect)(()=>{S?O.current?.focus():(D.current&&(D.current.scrollLeft=D.current.scrollWidth,E(D.current.scrollLeft>1)),ee.current&&=(k.current?.focus(),!1))},[S,A,o]);let M=()=>{ee.current=!0,C(!1),v?.(``)},ne=S?M:s??l,re=Ec(r,e).slice(1),N=(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)(Du,{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:ne,children:(0,Y.jsx)(lt,{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(),M())},children:[S&&_?(0,Y.jsx)(Tu,{inputRef:O,onSearch:_.onSearch,onDraftChange:v,clearOnSubmit:!_.localOnly,showSubmitButton:!1,label:_.queries.length?`Refine search…`:`Search documents…`}):(0,Y.jsxs)(Y.Fragment,{children:[N((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=>E(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&&N(`[${n}]`,`canvas-address-tree`,l,`Browse tree: ${n}`),N(`:/`,`canvas-address-root`,u?()=>u(`/`):void 0,`Go to tree root`),re.map((e,t)=>(0,Y.jsxs)(`span`,{className:`canvas-address-segment`,children:[t>0&&(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:`/`}),N(e.label,``,u?()=>u(e.path):void 0,e.path,!a&&t===re.length-1)]},e.path)),a&&(0,Y.jsxs)(`span`,{className:`canvas-address-segment`,children:[(0,Y.jsx)(`span`,{"aria-hidden":`true`,children:re.length?`/`:``}),N(a,``,d,a)]}),o&&N(`#${o}`,`canvas-address-section`,f,o,!0)]})]}),_&&(0,Y.jsxs)(`button`,{ref:k,type:`button`,className:`canvas-nav-button canvas-address-search`,onClick:S?M:()=>C(!0),"aria-label":S?`Close search`:`Search this canvas`,"aria-expanded":S,title:S?`Close search`:`Search this canvas`,children:[(0,Y.jsx)(mt,{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)(ot,{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)(ze,{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:M,"aria-label":`Close search`,children:(0,Y.jsx)(T,{size:16})})]}),(0,Y.jsx)(Eu,{..._})]}),!S&&_&&_.queries.length>0&&(0,Y.jsx)(`div`,{className:`px-3 pb-2`,children:(0,Y.jsx)(Eu,{queries:_.queries,onRemoveQuery:_.onRemoveQuery})})]})}function ku({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)})})}var Au=1,ju=8,Mu=320,Nu=28,Pu=2.5,Fu={scale:1,x:0,y:0};function Iu({src:e,alt:t,className:n=``,onZoomChange:r}){let i=(0,q.useRef)(null),a=(0,q.useRef)(null),[o,s]=(0,q.useState)(Fu),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(Fu)),(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(ju,Math.max(Au,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 Pu;let n=Math.max(e.clientWidth/t.offsetWidth,e.clientHeight/t.offsetHeight),r=Math.max(t.naturalWidth/t.offsetWidth,t.naturalHeight/t.offsetHeight)||ju;return Math.min(ju,Math.max(Pu,Math.min(Math.max(n,Pu),r)))},[]),b=(0,q.useCallback)((e,t)=>{o.scale>1.001?s(Fu):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<Mu&&Math.hypot(e.clientX-n.x,e.clientY-n.y)<Nu){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<=Au?s(Fu):v(Math.min(ju,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<Mu)&&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 Lu=`(max-width: 767px)`,Ru=new Map;function zu(e){let t=Ru.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},Ru.set(e,t)}return t}function Bu(){let e=zu(Lu);return(0,q.useSyncExternalStore)(e.subscribe,e.getSnapshot,()=>!1)}function Vu(){return Hu(`(max-width: 1023px)`)}function Hu(e){let t=zu(e);return(0,q.useSyncExternalStore)(t.subscribe,t.getSnapshot,()=>!1)}function Uu(){return!/android|iphone|ipad|mobile/i.test(navigator.userAgent)&&navigator.pdfViewerEnabled!==!1}var Wu=40,Gu=1600;function Ku({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,Wu),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,Gu*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>Wu})}})().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 `,Wu,` pages. Download the file for the full document.`]})]})}function qu({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]),Uu()||!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)(Ku,{blob:e,filename:n})})}function Ju(e,t,n=256,{enabled:r=!0,blobFallback:i=!0,version:a=null}={}){let{isPublic:o,fetchBlob:s,fetchThumbnail:c}=zn(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 Yu({workspaceId:e,document:t}){let{download:n}=zn(e),[r,i]=(0,q.useState)(!1),a=Ft(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 Xu=1600;function Zu({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 Qu({workspaceId:e,document:t,className:n=``}){let r=(0,q.useContext)(gu),i=Bu(),a=Hu(`(pointer: coarse)`),{blobUrl:o,error:s,loading:c}=Ju(e,t.id,Xu,{version:t.checksumArray?.[0]??null}),{fetchBlob:l}=zn(e),u=Ft(t)||`document-${t.id}`,[d,f]=(0,q.useState)(!1);return(0,Y.jsx)(Zu,{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)(Iu,{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 $u({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Un(e,t.id);return(0,Y.jsx)(Zu,{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)(Yu,{workspaceId:e,document:t})]})})}function ed({workspaceId:e,document:t,className:n=``}){let{src:r,error:i,loading:a}=Un(e,t.id),[o,s]=(0,q.useState)(!1);return(0,Y.jsx)(Zu,{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)(Yu,{workspaceId:e,document:t})]})})}function td({workspaceId:e,document:t,className:n=``}){let{blobUrl:r,blob:i,error:a,loading:o}=Rn(e,t.id,{typeHint:`application/pdf`}),s=Ft(t)||`document-${t.id}`;return(0,Y.jsx)(Zu,{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)(qu,{blob:i,blobUrl:r,filename:s,className:`min-h-0 flex-1`}),(0,Y.jsx)(`div`,{children:(0,Y.jsx)(Yu,{workspaceId:e,document:t})})]})})}var nd=(0,q.lazy)(()=>s(()=>import(`./markdown-html-XoABNf32.js`),__vite__mapDeps([2,3,4,5,6,7,8])));function rd({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)(nd,{content:e,className:t,preview:n})})}function id({workspaceId:e,document:t,className:n=``}){let{text:r,error:i,loading:a}=Rn(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 ad({workspaceId:e,document:t,className:n=``}){let r=t.schema===Yt,{text:i,error:a,loading:o}=Rn(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)(rd,{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)(rd,{content:i,className:`markdown-doc px-4 py-3`})})}function od({document:e,className:t=``}){let n=String(e.data?.url??e.data?.uri??``),r=Rt(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 sd({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(`${xt}/proxy/pdf?url=${encodeURIComponent(n)}`,{headers:e?{Authorization:`Bearer ${e}`}:{}})};return fetch(n).then(r).catch(()=>a().then(r)).then(n=>{e||(t=URL.createObjectURL(n),i({blobUrl:t,blob:n,failed:!1,loading:!1}))}).catch(()=>{e||i({blobUrl:null,blob:null,failed:!0,loading:!1})}),()=>{e=!0,t&&URL.revokeObjectURL(t)}},[n]);let{blobUrl:s,blob:c,failed:l,loading:u}=r,d=(()=>{try{let e=decodeURIComponent(new URL(n).pathname.split(`/`).filter(Boolean).pop()??``)||`document`;return/\.pdf$/i.test(e)?e:`${e}.pdf`}catch{return`document.pdf`}})();return(0,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)(qu,{blob:c,blobUrl:s,filename:d,className:`min-h-[300px] flex-1`})]})}function cd(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 ld(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function ud({document:e,className:t=``}){let n=e.data||{},r=String(n.url??n.uri??``),i=String(n.title??n.label??``)||ld(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)(F,{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)(te,{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:ld(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 dd={enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4};function fd(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 pd(){return new Promise((e,t)=>navigator.geolocation.getCurrentPosition(e,t,dd))}function md(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 hd(){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),pd().then(e=>{let t=fd(e);g.current=t,u(t),n(`granted`)}).catch(e=>{c(md(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 fd(await pd())}catch{return g.current}},[e])}}var gd=`2.1`,_d=[`pending`,`in-progress`,`completed`,`cancelled`],vd={pending:`Pending`,"in-progress":`In progress`,completed:`Completed`,cancelled:`Cancelled`};function yd(e){return String(e).padStart(2,`0`)}function bd(e){return`${e.getFullYear()}-${yd(e.getMonth()+1)}-${yd(e.getDate())}T${yd(e.getHours())}:${yd(e.getMinutes())}`}function xd(e){if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:bd(t)}function Sd(e){if(!e)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function Cd(){let e=new Date;return e.setHours(23,59,0,0),bd(e)}function wd(e){let t=Sd(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 Td(){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)(Cd()),[u,d]=(0,q.useState)([]),[f,p]=(0,q.useState)(``),[m,h]=(0,q.useState)(!1),g=hd(),_=e.trim().length>0&&!m;async function v(t){h(!0);try{let r=await g.capture(),a=f.trim(),s={schema:Nt,schemaVersion:gd,data:wd({title:e,description:n,status:i,priority:o,due:c}),...a?{comment:a}:{},metadata:{features:Jn(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 Ed(e){return e.data||{}}var Dd={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 Od(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 kd(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 Ad(e,t,n){let r=n===`completed`,i={...t.data||{},status:n,completed:r};r?i.completedAt=new Date().toISOString():delete i.completedAt,await An(e,{id:t.id,schema:t.schema,schemaVersion:t.schemaVersion,data:i}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`))}function jd({document:e,workspaceId:t,className:n=``}){let r=Ed(e),i=Pn()!=null,[a,o]=(0,q.useState)(!1),{replicating:s,label:c}=G(e),l=r.status===`completed`,u=r.status??`pending`,d=Od(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 Ad(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)(ut,{className:`h-3 w-3 animate-spin`}):l&&(0,Y.jsx)(y,{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 ${Dd[u]}`,children:vd[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)(w,{className:`h-3 w-3`}),kd(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)(rd,{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)(ut,{className:`h-3 w-3 animate-spin`}),c]})]})]})})}function Md(e,t){let{fetchBlob:n}=zn(e),r=Pn(),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 Nd(e){return e?typeof e==`string`?e:e.name&&e.address?`${e.name} <${e.address}>`:e.address||e.name||``:``}function Pd(e){return e?(Array.isArray(e)?e:[e]).map(e=>Nd(e)).filter(Boolean).join(`, `):``}function Fd(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 Id(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>
|
|
11
|
+
<meta charset="utf-8">
|
|
12
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
13
|
+
<meta http-equiv="Content-Security-Policy" content="${`default-src 'none'; img-src data:${n?` https:`:``}; style-src 'unsafe-inline'`}">
|
|
14
|
+
<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>
|
|
15
|
+
</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 Ld(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 Rd(e){return(0,Y.jsx)(zd,{...e},`${e.workspaceId}:${e.document.id}`)}function zd({workspaceId:e,document:t,className:n=``}){let{fetchBlob:r,download:i}=zn(e),a=t.data||{},o=Array.isArray(a.attachments)?a.attachments:[],{body:s,bodyHtml:c,loading:l,error:u}=Md(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 Ld(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}=Id(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:`}),` `,Nd(a.from)]}),Pd(a.to)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Pd(a.to)]}),Pd(a.cc)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Pd(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:`}),` `,Nd(a.from)]}),Pd(a.to)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`To:`}),` `,Pd(a.to)]}),Pd(a.cc)&&(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`text-muted-foreground`,children:`Cc:`}),` `,Pd(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)(W,{size:`sm`,variant:`outline`,onClick:()=>m(!p),children:[p?(0,Y.jsx)(ae,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Y.jsx)(Le,{className:`mr-1.5 h-3.5 w-3.5`}),p?`HTML`:`Plain text`]}),!p&&_>0&&(0,Y.jsxs)(W,{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)(Re,{className:`mr-1.5 h-3.5 w-3.5`}):(0,Y.jsx)(Be,{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)(Le,{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:Fd(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 Bd({attachment:e,workspaceId:t,document:n}){let{download:r}=zn(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}=Rn(t,n.id,{url:e.url,typeHint:i,enabled:!o&&!!e.url}),{src:u,error:d,loading:f}=Un(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 Vd(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)(Bd,{...e,attachment:t},t.url||n))]})}var Hd={email:z,phone:x,sms:be,chat:be,slack:be,matrix:be,web:F,url:F},Ud={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Wd=e=>Array.isArray(e)?e:[];function Gd(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 Kd({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 qd({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)(Ye,{className:`h-3 w-3 shrink-0 fill-current text-data-5`,"aria-label":`Primary`})]})}function Jd({document:e,className:t}){let n=e.data??{},r=Wd(n.identifiers),i=Wd(n.channels),a=Wd(n.organizations),o=Wd(n.links),s=Wd(n.tags),c=String(n.displayName||``).trim(),l=Cn(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:V(`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:Ud[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)(Kd,{title:`Primary email`,count:1,children:(0,Y.jsx)(qd,{icon:z,primary:!0,children:(0,Y.jsx)(`a`,{href:`mailto:${u}`,className:`hover:underline`,children:u})})}),(0,Y.jsx)(Kd,{title:`Channels`,count:i.length,children:i.map((e,t)=>{let n=String(e.kind||``).toLowerCase(),r=String(e.value||``),i=Gd(n,r),a=Hd[n]||be;return(0,Y.jsxs)(qd,{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)(Kd,{title:`Identifiers`,count:r.length,children:r.map((e,t)=>(0,Y.jsxs)(qd,{icon:st,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)(Kd,{title:`Organizations`,count:a.length,children:a.map((e,t)=>(0,Y.jsxs)(qd,{icon:et,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)(Kd,{title:`Links`,count:o.length,children:o.map((e,t)=>(0,Y.jsxs)(qd,{icon:We,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 Yd({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 Xd(e){let t=e.schema;if(t===`data/schema/note`)return ad;if(t===`data/schema/drawing`)return Qu;if(t===`data/schema/task`)return jd;if(t===`data/schema/message/email`)return Rd;if(t===`data/schema/message`)return Vd;if(t===`data/schema/identity`||t.startsWith(`data/schema/identity/`))return Jd;if(t===`data/schema/tab`||t===`data/schema/link`){let t=String(e.data?.url??e.data?.uri??``);return Rt(t)?od:cd(t)?sd:ud}if(t!==`data/schema/file`)return null;let n=String(e.metadata?.contentType||``);switch(Vt(n,Ft(e))){case`image`:return Qu;case`audio`:return $u;case`video`:return ed;case`pdf`:return td;case`markdown`:return ad;case`text`:return id;default:return Yd}}function Zd({workspaceId:e,document:t,className:n}){let r=Xd(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 Qd=new lr({html:!1});function $d(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`
|
|
16
|
+
`;case`paragraph_close`:case`heading_close`:return`
|
|
17
|
+
|
|
18
|
+
`;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(Qd.parse(e,{})).trim()}function ef(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 tf={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`};function nf({workspaceId:e,replyToDocumentId:t,mode:n=`reply`,originalSubject:r,initialAccount:i,testEmail:a=!1,onClose:o}){let s=!!t&&n===`forward`,c=a?`${ef(e)}:smtp-test:${i?.address}`:ef(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([Ss(e),t?Cs(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),ee=k?.driver===`imap`,A=k?.driver===`whatsapp`,te=!!u.images?.length,j=!!u.text.trim(),M=e=>d(t=>({...t,...e})),ne=async()=>{S(!0),E(``),w(!0);let t=ee?j?u:{...u,html:void 0}:{...u,text:A?$d(u.text):u.text,html:void 0,quote:void 0,forward:void 0};try{let n=C?await Es(e,u.requestId).catch(n=>{if(n.statusCode===404)return ws(e,t);throw n}):await ws(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)}},re=async e=>{if(P||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>(A?1:8)){E(A?`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)}}},N=u.replyAll?f?.allRecipients:f?.recipients,P=x||C||y,ie=a?`Send test email`:t?s?tf.forward:tf[u.replyAll?`replyAll`:`reply`]:`New message`,ae=t&&r?`${s?`Fwd`:`Re`}: ${r.replace(s?/^(fwd?|fw):\s*/i:/^re:\s*/i,``)}`:``;return(0,Y.jsxs)(`section`,{onPasteCapture:e=>{if(!(ee||A))return;let t=Array.from(e.clipboardData.files);t.some(e=>e.type.startsWith(`image/`))&&(e.preventDefault(),e.stopPropagation(),re(t))},className:`max-h-[70dvh] overflow-y-auto rounded-md border bg-card p-3 space-y-3`,"aria-label":t?`${ie} to message`:`New message`,children:[(0,Y.jsxs)(`div`,{className:`flex justify-between items-center`,children:[(0,Y.jsx)(`strong`,{className:`text-sm`,children:ie}),(0,Y.jsx)(W,{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:P||!!t||!!i,onChange:e=>{let t=m.find(t=>`${t.driver}:${t.address}`===e.target.value);t&&M({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.`}),ee?(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)(H,{"aria-label":`To`,disabled:P,value:u.to?.join(`, `)||``,onChange:e=>M({to:[e.target.value]})})]}),t&&!s&&!u.to?.some(e=>e.trim())&&N&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Reply to: `,N.to.join(`, `),N.cc.length?` · Cc: ${N.cc.join(`, `)}`:``]}),[`cc`,`bcc`].map(e=>(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[e===`cc`?`Cc`:`Bcc`,(0,Y.jsx)(H,{"aria-label":e===`cc`?`Cc`:`Bcc`,disabled:P,value:u[e]?.join(`, `)||``,onChange:t=>M({[e]:[t.target.value]})})]},e)),(0,Y.jsxs)(`label`,{className:`block text-xs`,children:[`Subject`,(0,Y.jsx)(H,{"aria-label":`Subject`,disabled:P,value:u.subject||``,placeholder:ae,onChange:e=>M({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:P,checked:u.replyAll||!1,onChange:e=>{let t=e.target.checked?f?.allRecipients:f?.recipients;M({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:P,checked:u.quote||!1,onChange:e=>M({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)(Ln,{format:`html`,editable:!P,value:u.html||``,placeholder:s?`Add a note (optional)…`:`Write a message…`,onChange:(e,t)=>M({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)(H,{"aria-label":`Conversation`,disabled:P,value:u.target||``,onChange:e=>M({target:e.target.value})})]}),A?(0,Y.jsx)(Ln,{format:`markdown`,editable:!P,value:u.text,placeholder:`Write a message…`,onChange:e=>M({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:P,value:u.text,onChange:e=>M({text:e.target.value}),placeholder:`Write a message…`})]}),(ee||A)&&(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:!A,disabled:P,onChange:e=>{re(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)(W,{size:`sm`,variant:`ghost`,disabled:P,onClick:()=>M({images:u.images?.filter((e,n)=>n!==t)}),children:`Remove picture`})]},t)),A&&(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)(W,{size:`sm`,disabled:x||y||!C&&(!k||!j&&!te&&!(ee&&s)||s&&!u.to?.some(e=>e.trim()))||!g,onClick:()=>void ne(),children:x?`Sending…`:C?`Check send status`:`Send`}),(0,Y.jsx)(W,{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 rf(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)(nf,{...e})})}function af({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 Os(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;Os(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(mu,i),()=>{n=!1,window.removeEventListener(`workspace:documents:refresh`,i),window.removeEventListener(mu,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)(W,{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)(W,{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)(W,{variant:`outline`,size:`sm`,onClick:()=>l({document:r,mode:e}),children:e===`replyAll`?`Reply all`:e===`forward`?`Forward`:`Reply`},e))}),p&&(0,Y.jsx)(Zd,{workspaceId:e,document:r})]},r.id)}),c&&(0,Y.jsx)(rf,{workspaceId:e,replyToDocumentId:Number(c.document.id),mode:c.mode,originalSubject:typeof c.document.data.subject==`string`?c.document.data.subject:void 0,onClose:()=>l(null)},`${c.document.id}:${c.mode}`)]})}var of=15,sf=[`Mo`,`Tu`,`We`,`Th`,`Fr`,`Sa`,`Su`];function cf(e){return String(e).padStart(2,`0`)}function lf(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 uf(e){return`${e.getFullYear()}-${cf(e.getMonth()+1)}-${cf(e.getDate())}`}function df(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r)}function ff(){let e=new Date;return e.setSeconds(0,0),e.setMinutes(Math.ceil(e.getMinutes()/of)*of),`${cf(e.getHours())}:${cf(e.getMinutes())}`}function pf(){let e=[];for(let t=0;t<1440;t+=of)e.push(`${cf(Math.floor(t/60))}:${cf(t%60)}`);return e}var mf=pf();function hf(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 gf(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 _f(e){let t=lf(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 vf({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=lf(e),f=d?_f(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:V(`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)(w,{className:V(`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)(T,{className:o?`h-2.5 w-2.5`:`h-3.5 w-3.5`})})]}),c&&(0,Y.jsx)(yf,{anchorRef:u,value:e,onChange:t,onClose:()=>l(!1)})]})}function yf({anchorRef:e,value:t,onChange:n,onClose:r}){let i=lf(t),a=i?.date??uf(new Date),o=i?.time??null,[s,c]=(0,q.useState)(()=>{let e=df(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||mf.includes(o)?mf:[...mf,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??ff();h(uf(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??ff();h(uf(t),n),c(new Date(t.getFullYear(),t.getMonth(),1))},y=uf(new Date),b=hf(s);return(0,lo.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)(vt,{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:sf.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=uf(e),n=e.getMonth()!==s.getMonth(),r=t===a&&!!i;return(0,Y.jsx)(`button`,{type:`button`,onClick:()=>g(e),"aria-pressed":r,className:V(`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:V(`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:gf(e)},e)})})]})]})]}),document.body)}var bf={1:`1: Highest`,2:`2`,3:`3: High`,4:`4`,5:`5: Medium`,6:`6`,7:`7: Low`,8:`8`,9:`9: Lowest`},xf=`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`,Sf=`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 Cf({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)(uo,{htmlFor:`${u}-title`,children:`Title`}),(0,Y.jsx)(H,{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)(uo,{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:Sf})]}),(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)(uo,{htmlFor:`${u}-due`,children:`Due`}),(0,Y.jsx)(vf,{id:`${u}-due`,value:c,onChange:l,placeholder:`No due date`})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{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:xf,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:bf[e]},e))]})]})]}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${u}-status`,children:`Status`}),(0,Y.jsx)(`select`,{id:`${u}-status`,value:i,onChange:e=>a(e.target.value),className:xf,children:_d.map(e=>(0,Y.jsx)(`option`,{value:e,children:vd[e]},e))})]})]})}var wf=`3.0`,Tf=[`person`,`organization`,`service`,`bot`],Ef={person:`Person`,organization:`Organization`,service:`Service`,bot:`Bot`},Df=[`email`,`phone`,`sms`,`chat`,`web`],Of=[`email`,`github`,`slack`,`matrix`,`gpg`,`url`];function kf(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 Af(e){let t=e?.data??{},n=t.name&&typeof t.name==`object`?t.name:{},r=e=>Array.isArray(e)?e:[],i=Cn(String(e?.schema||``),Xt);return{displayName:String(t.displayName||``),type:Tf.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 jf(e,t,n){if(!t||!e||e.mode!==`workspace`)return;let r=n.filter(e=>e.identityId);for(let n of r)try{await On(e.workspaceName,t,`member-of`,[n.identityId])}catch(e){console.error(`Failed to link organization`,n.name,e)}}function Mf(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:wf,data:kf(C),...t?{comment:t}:{},metadata:{features:Jn(_)}},r=await ar(e,[n]);return await jf(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 Nf=`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 Pf({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)(uo,{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)(ze,{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)(L,{className:`h-3.5 w-3.5`})})]},i))})]})}function Ff(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 If(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 Lf({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=If(t);return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-display-name`,children:`Display name`}),(0,Y.jsx)(H,{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)(uo,{htmlFor:`${e}-type`,children:`Type`}),(0,Y.jsx)(`select`,{id:`${e}-type`,value:i,onChange:e=>a(e.target.value),className:V(Nf,`w-full`),children:Tf.map(e=>(0,Y.jsx)(`option`,{value:e,children:Ef[e]},e))})]}),(0,Y.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`${e}-email`,children:`Primary email`}),(0,Y.jsx)(H,{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)(uo,{htmlFor:`${e}-given`,children:`Given name`}),(0,Y.jsx)(H,{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)(uo,{htmlFor:`${e}-family`,children:`Family name`}),(0,Y.jsx)(H,{id:`${e}-family`,value:u,onChange:e=>d(e.target.value),placeholder:`Doe`})]})]}),(0,Y.jsx)(Pf,{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:V(Nf,`w-24`),children:[Df.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Df.includes(e.kind)&&(0,Y.jsx)(`option`,{value:e.kind,children:e.kind})]}),(0,Y.jsx)(H,{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(Ff(f,f.indexOf(e))),className:V(`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)(Ye,{className:V(`h-3.5 w-3.5`,e.primary&&`fill-current`)})})]})}),(0,Y.jsx)(Pf,{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:V(Nf,`w-24`),children:[Of.map(e=>(0,Y.jsx)(`option`,{value:e,children:e},e)),!Of.includes(e.type)&&(0,Y.jsx)(`option`,{value:e.type,children:e.type})]}),(0,Y.jsx)(H,{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)(Pf,{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:V(Nf,`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)(H,{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)(H,{value:e.role??``,onChange:e=>t({role:e.target.value}),placeholder:`Role`,className:`w-28 shrink-0`})]})})]})}function Rf(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 zf(e){return Rf(e.schema)||Bn(e)}function Bf(e){return e===`data/schema/link`?{urlKey:`uri`,titleKey:`label`}:e===`data/schema/tab`?{urlKey:`url`,titleKey:`title`}:{urlKey:null,titleKey:`title`}}async function Vf(e,t,n){try{let r=new Set(n.map(e=>e.identityId).filter(Boolean)),i=await Qt(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 On(e,t,`member-of`,[n]);for(let n of a)r.has(n)||await en(e,t,`member-of`,n)}catch(e){console.error(`Failed to sync organization relations`,e)}}function Hf({document:e,workspaceId:t,onClose:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),a=Rf(e.schema),o=e.schema===Yt,s=Bn(e),c=Wn(e)??`markdown`,l=s&&Fn(e),u=e.schema===Nt,d=e.schema===`data/schema/identity`||e.schema.startsWith(`data/schema/identity/`),{urlKey:f,titleKey:p}=Bf(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?xd(String(e.data.dueDate)):Cd()),O=Mf(Af(e)),[k,ee]=(0,q.useState)(String(e.comment??``)),A=e.metadata?.geo??null,[te,j]=(0,q.useState)(A),M=e.features??e.metadata?.features,[ne,re]=(0,q.useState)(qn(M).length?qn(M):e.data?.tags??[]),N=In(e,t,o),{title:P,content:ie,comment:ae,tags:oe,geo:se,setTitle:ce,setContent:le,setComment:F,setTags:ue,setGeo:de}=o?N:{title:g,content:v,comment:k,tags:ne,geo:te,setTitle:_,setContent:y,setComment:ee,setTags:re,setGeo:j},fe=JSON.stringify(se??null)!==JSON.stringify(A??null),pe=Rn(t,e.id,{mode:`text`,enabled:s&&!l,maxTextLength:Vn,version:e.checksumArray?.[0]??null}),[me,I]=(0,q.useState)(null),L=`${e.id}:${e.checksumArray?.[0]??``}`;s&&pe.text!=null&&me!==L&&(I(L),le(pe.text));let[he,ge]=(0,q.useState)([]),[_e,R]=(0,q.useState)(!1),{replicating:ve,mirror:ye}=G(e);(0,q.useEffect)(()=>{let e=!1;return kt(t).then(t=>{e||ge(t)}).catch(()=>{}),()=>{e=!0}},[t]);let be=!f||(()=>{try{return new URL(m.trim()),!0}catch{return!1}})(),xe=!_e&&(s?!l&&pe.text!=null&&!pe.loading:a?d?O.displayName.trim().length>0&&O.emailValid:u?P.trim().length>0:o?N.canSave:be:!0),Se=async()=>{R(!0);try{if(o){await N.save(),n();return}if(s){let i=await Kn(t,e,ie,{comment:ae.trim(),...fe?{metadata:{geo:se}}:{}});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:ae.trim()};if(d){let{type:t,...n}=e.data??{};i.schema=`${Xt}/${O.values.type}`,i.data={...n,...kf(O.values)},i.metadata={features:Jn(oe)}}else if(u)i.data={...e.data,...wd({title:P,description:b,status:S,priority:w,due:E})},i.metadata={features:Jn(oe)};else if(a){let t=oe.map(e=>e.trim()).filter(Boolean),n;o?n={...P.trim()?{title:P.trim()}:{},content:ie}:(n={...e.data},f&&(n[f]=m.trim()),P.trim()?n[p]=P.trim():delete n[p],n.tags=t),i.data=n,i.metadata={features:Jn(oe)}}fe&&(i.metadata={...i.metadata??{},geo:se}),await An(t,i),d&&(await Vf(t,e.id,O.values.organizations),hu()),r(`Document updated`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),n()}catch(e){i(e instanceof Error?e.message:`Failed to update document`)}finally{R(!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)(uo,{htmlFor:`edit-url`,children:`URL`}),(0,Y.jsx)(H,{id:`edit-url`,value:m,onChange:e=>h(e.target.value),placeholder:`https://example.com`,className:`font-mono text-xs`}),m.trim()&&!be&&(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:`Enter a valid URL, e.g. https://example.com`})]}),a&&d&&(0,Y.jsx)(Lf,{idPrefix:`edit-identity`,workspaceName:t,...O,emailValid:O.emailValid}),a&&u&&(0,Y.jsx)(Cf,{idPrefix:`edit-todo`,title:P,setTitle:ce,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)(uo,{htmlFor:`edit-title`,children:`Title`}),(0,Y.jsx)(H,{id:`edit-title`,value:P,onChange:e=>ce(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)(uo,{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&&pe.error?(0,Y.jsx)(`p`,{className:`text-xs text-destructive`,children:pe.error}):s&&pe.text==null?(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Loading content…`}):(0,Y.jsx)(Hn,{kind:o?`markdown`:c,value:ie,onChange:le,placeholder:o?`Write your note…`:void 0})]}),a&&(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{children:`Tags`}),(0,Y.jsx)(Ml,{tags:oe,onChange:ue,suggestions:he})]}),(0,Y.jsx)(Wl,{value:se,onChange:de}),(0,Y.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Y.jsx)(uo,{htmlFor:`edit-comment`,children:`Comment`}),(0,Y.jsx)(`textarea`,{id:`edit-comment`,value:ae,onChange:e=>F(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)(Gn,{...N,onRetry:N.save}),(0,Y.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2`,children:[(0,Y.jsx)(W,{variant:`outline`,size:`sm`,onClick:()=>n(),disabled:_e,children:o?`Close`:`Cancel`}),(0,Y.jsx)(W,{size:`sm`,onClick:Se,disabled:!xe,children:_e?ve?`Replicating to ${ye.label}…`:`Saving…`:`Save changes`})]})]})}var Uf=(0,q.createContext)(null),Wf={open:()=>{},close:()=>{}};function Gf(){return(0,q.useContext)(Uf)??Wf}var Kf=`main`,qf=(0,q.createContext)(null);function Jf(){return(0,q.useContext)(qf)}var Yf=50;function Xf({relation:e,workspaceId:t,direction:n,onRemove:r,removing:i}){let{open:a}=Gf(),o=nu(),s=Jf(),c=n===`out`?e.to:e.from,l=e.document??null,u=l?Gt(l).title:``,[d,f]=(0,q.useState)(!1),{showErrorToast:p}=Tt(),m=async()=>{if(!(c==null||!l)){f(!0);try{let n=e.preview?await bn(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)(lt,{className:`h-3.5 w-3.5 shrink-0 text-muted-foreground`}),l?(0,Y.jsx)(wc,{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)(L,{className:`h-3.5 w-3.5`})})]})}function Zf({document:e,workspaceId:t}){let{showSuccessToast:n,showErrorToast:r}=Tt(),[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 Qt(t,e.id,{offset:m*Yf,limit:Yf,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)/Yf)-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(mu,e),()=>{y(),window.removeEventListener(mu,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 en(t,e.id,i.p,o,a),n(`Relation removed`),hu()}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)(W,{variant:`outline`,size:`sm`,onClick:()=>l(!0),children:[(0,Y.jsx)(ze,{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)(Xf,{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)(W,{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)(W,{variant:`outline`,size:`sm`,disabled:!i||m+1>=g,onClick:()=>E(m+1),children:`Next`})]}),c&&(0,Y.jsx)(As,{onClose:()=>{u||l(!1)},children:(0,Y.jsx)(Lc,{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 On(t,e.id,i,o,a),n(`Related to ${o.length} document${o.length===1?``:`s`}`),l(!1),hu()}catch(e){r(e instanceof Error?e.message:`Failed to create relation`)}finally{d(!1)}}})})]})}window.EXCALIDRAW_ASSET_PATH=`/excalidraw/`;var Qf=(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]))),$f=(0,q.lazy)(()=>s(()=>import(`./TextDocumentEditor-BF5NzQ6H.js`),__vite__mapDeps([25,3,4,11,10,13,12,14,15,16,26,1,23]))),ep={reply:`Reply`,replyAll:`Reply all`,forward:`Forward`},tp={reply:oe,replyAll:p,forward:ce};function np({document:e,workspaceId:t,initialEdit:n=!1,onChanged:r}){let i=Pn()!=null,{showErrorToast:a}=Tt(),[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&&zf(e)),v=e.schema===qt,[y,b]=(0,q.useState)(!1),x=e.schema===`data/schema/note`||Bn(e),[S,w]=(0,q.useState)(!1),T=`${t}:${e.id}:${n}:${i}`,[E,D]=(0,q.useState)(T);T!==E&&(D(T),_(n&&zf(e)),u(null),s(!1),b(!1),w(!1));let k=t=>{if(!h||!zf(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)(Hf,{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)(W,{size:`sm`,variant:o?`secondary`:`outline`,onClick:()=>s(!o),children:o?`Show message`:`View thread`}),f&&p.map(e=>{let t=tp[e];return(0,Y.jsxs)(W,{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`}),ep[e]]},e)}),e.schema===`data/schema/file`&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>Wt(t,e.id,Ft(e)||`document-${e.id}`).catch(e=>a(e instanceof Error?e.message:String(e))),children:[(0,Y.jsx)(Me,{className:`mr-1 h-3 w-3`}),` Download`]}),v&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>b(!0),children:[(0,Y.jsx)(C,{className:`mr-1 h-3 w-3`}),` Edit sketch`]}),x&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>w(!0),children:[(0,Y.jsx)(yt,{className:`mr-1 h-3 w-3`}),` Open editor`]}),(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>_(!0),children:[(0,Y.jsx)(O,{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)(Qf,{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)($f,{doc:e,workspaceName:t,onSaved:e=>{w(!1),r?.(e)},onClose:()=>w(!1),onDetails:()=>{w(!1),_(!0)}})}),(0,Y.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-auto`,onMouseDownCapture:e=>{e.button===0&&e.detail>1&&k(e)&&e.preventDefault()},onDoubleClickCapture:e=>{k(e)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.ownerDocument.getSelection()?.removeAllRanges(),_(!0))},children:[o&&!i?(0,Y.jsx)(af,{workspaceId:t,documentId:Number(e.id)},`${t}:${e.id}`):(0,Y.jsx)(Zd,{workspaceId:t,document:e}),l&&f&&(0,Y.jsx)(rf,{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 rp=e=>e?new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`long`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):`—`,ip=e=>!Number.isFinite(e)||!e?null:e>=1?`${e}s`:`1/${Math.round(1/e)}s`;function ap({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`,ip(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`,rp(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 op({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:rp(e.createdAt)})]}),(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(`span`,{className:`font-medium`,children:`Updated:`}),(0,Y.jsx)(`span`,{className:`ml-2`,children:rp(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)(ap,{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}=up(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}),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 sp({document:e}){let{showSuccessToast:t,showErrorToast:n}=Tt(),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)(W,{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 cp({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 $t(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)(Zf,{document:e,workspaceId:t})]}):(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Loading memberships...`})}function lp(e){return e===`stored`?pt:e===`workspace-file`?ne:e===`imap`?z:e===`readonly`?F:at}function up(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 dp({document:e,workspaceId:t,onChanged:n}){let{showSuccessToast:r,showErrorToast:i}=Tt(),[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=()=>{Lt(t,e.id).then(o).catch(e=>c(e instanceof Error?e.message:String(e)))};(0,q.useEffect)(()=>{let n=!1;return Lt(t,e.id).then(e=>{n||o(e)}).catch(e=>{n||c(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[v]);let S=async(a,o)=>{d(a),p(null);try{let i=await gn(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 kn(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(ns(i.failed,new Map([[e.id,Ft(e)||`Document ${e.id}`]]))||`Transfer failed`);let l=c.transfers?.flatMap(e=>e.state===`unchanged`?[]:[e.backend])??[],u=a.join(`, `);o===`delete`?r(`Deleted from ${u}`):l.length===0?r(`Nothing to do — already on ${u}`):r(`${o===`move`?`Moved to`:`Copied to`} ${l.join(`, `)}${c.transfers?.some(e=>e.state===`pending`)?` (pending sync)`:``}`),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`)),h(null),n?.(),x()}catch(e){i(e instanceof Error?e.message:String(e))}finally{_(!1)}},w=e=>{if((a?.length??0)<=1){p(e.url);return}window.confirm(`Remove this copy from the backend?\n\n${e.url}`)&&S(e.url)};if(s)return(0,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=Ft(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)(pt,{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)(W,{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)(W,{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=lp(n.kind),{backend:a,key:o}=up(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)(L,{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)(W,{variant:`destructive`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!1),children:`Also remove index entry`}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,disabled:s,onClick:()=>void S(n.url,!0),children:`Keep index entry (no bytes)`}),(0,Y.jsx)(W,{variant:`ghost`,size:`sm`,onClick:()=>p(null),children:`Cancel`})]})]})]},n.url)}),m&&(0,lo.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)(Ql,{workspaceId:t,documentCount:1,initialMode:m,defaultFilename:E,saving:g,onConfirm:C,onClose:()=>{g||h(null)}})}),window.document.body)]})}function fp(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 pp(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 mp(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&&pp(e,t,n.points)}function hp(e,t,n=!1){let r=fp(e);return r?mp(r.lat,r.lon,t):n}var gp=(0,q.lazy)(()=>s(()=>import(`./LocationTab-BONJQfYM.js`),__vite__mapDeps([27,3,4,28,29]))),_p=[{id:`view`,label:`View`,icon:dt},{id:`location`,label:`Location`,icon:Ie},{id:`metadata`,label:`Metadata`,icon:d},{id:`json`,label:`JSON`,icon:ge},{id:`synapses`,label:`Synapses`,icon:Qe},{id:`backends`,label:`Backends`,icon:pt}];function vp({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=Pn()!=null,d=fp(e),f=_p.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:V(b&&`document-detail-header shrink-0 border-b-[3px] bg-muted`),children:(0,Y.jsxs)(`div`,{className:V(`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)(ku,{tabs:f,active:v,onChange:y,className:V(`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)(Ou,{...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)(np,{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)(gp,{lat:d.lat,lon:d.lon})}),v===`metadata`&&(0,Y.jsx)(op,{document:e,workspaceId:t}),v===`json`&&(0,Y.jsx)(sp,{document:e,workspaceId:t}),v===`synapses`&&!u&&(0,Y.jsx)(cp,{document:e,workspaceId:t}),v===`backends`&&!u&&(0,Y.jsx)(dp,{document:e,workspaceId:t,onChanged:i})]})})]})}function yp(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}bn(e,u).then(e=>{c.current===a&&l.current===n&&e&&r(e)}).catch(()=>{})},[e,u,a]);return{document:n??t,refresh:d}}function bp(e){let t=wu(),n=(0,q.useContext)(eu),{document:r,workspaceId:i,isOpen:a,onClose:o,initialEdit:s,initialTab:c}=e,l=t===`side`&&!!n&&!!i&&!s&&!c;return(0,q.useLayoutEffect)(()=>{!l||!a||!r||!i||!n||((n.preview??n.open)(r,i),o())},[l,a,r,i,n,o]),l?null:(0,Y.jsx)(xp,{...e})}function xp({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}=yp(r,e);if(ps(()=>o?s(!1):n(),t&&!!l),!t||!l)return null;let d=!!(c?.state.t1Open||c?.state.t2Open);return(0,lo.createPortal)((0,Y.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,className:V(`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:V(`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=jt(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)(qe,{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)(gu.Provider,{value:()=>s(e=>!e),children:(0,Y.jsx)(vp,{document:l,workspaceId:r??``,initialTab:i,initialEdit:a,onChanged:u})})})]})}),window.document.body)}var Sp={sortBy:`alphabetical`,order:`asc`};function Cp(e){return e?.sortBy===`crud:deleted`?{...Sp}:{sortBy:e?.sortBy??Sp.sortBy,order:e?.order??Sp.order}}var wp={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:{...Sp}};function Tp(e){let t=e.bbox;return t?[`geo:bbox:${t.minLat},${t.minLon},${t.maxLat},${t.maxLon}`,...e.includeUnlocated?[`geo:missing`]:[]]:[]}function Ep(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 Dp(e){return e.customRanges?.length?e.customRanges:e.customRange?[e.customRange]:[]}function Op(e){let{quickFilter:t,indexCreated:n,indexUpdated:r,indexDeleted:i,contentEvents:a,selectedTimelines:o}=e,s=Dp(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 kp(e,t,n=[]){return{features:e.features,filters:[...Op(e.timeline),...Tp(e.geo),...Ep(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 Ap=Sp,jp={alphabetical:`Alphabetical`,type:`Type`,"crud:created":`Created`,"crud:updated":`Updated`,content:`Content`};function Mp(e){return jp[e]??e}function Np(e){let[t,n]=(0,q.useState)([]);return(0,q.useEffect)(()=>{let t=!1;return hn(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:Mp(e)})),[t])}function Pp({workspaceId:e,value:t,onChange:n}){let r=Np(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:Mp(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 Fp(e,t){let n=t?.replace(/^t:/,``)||`crud:created`,r=(n===`crud:created`?[e.createdAt]:n===`crud:updated`?[e.updatedAt]:(e.timelines??[]).filter(e=>(e.timeline||e.name)===n).map(e=>e.start)).map(e=>Date.parse(e??``)).filter(Number.isFinite);return r.length?Math.min(...r):null}var Ip={today:8,yesterday:7,thisWeek:6,lastWeek:5,thisMonth:4,lastMonth:3,thisYear:2,year:1,unknown:0},Lp=e=>e*1e6;function Rp(){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 zp(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function Bp(e,t){let n=((e.getDay()===0?7:e.getDay())-t+7)%7,r=zp(e);return r.setDate(r.getDate()-n),r}var Vp=864e5;function Hp(e){let t=Rp(),n=zp(e),r=Bp(e,t);return{today:n.getTime(),yesterday:n.getTime()-Vp,weekStart:r.getTime(),lastWeekStart:r.getTime()-7*Vp,year:e.getFullYear(),month:e.getFullYear()*12+e.getMonth()}}function Up(e,t){if(e===null||!Number.isFinite(e))return{key:`unknown`,label:`Unknown date`,rank:Lp(Ip.unknown)};if(e>=t.today)return{key:`today`,label:`Today`,rank:Lp(Ip.today)};if(e>=t.yesterday)return{key:`yesterday`,label:`Yesterday`,rank:Lp(Ip.yesterday)};if(e>=t.weekStart)return{key:`this-week`,label:`Earlier this week`,rank:Lp(Ip.thisWeek)};if(e>=t.lastWeekStart)return{key:`last-week`,label:`Last week`,rank:Lp(Ip.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:Lp(Ip.thisMonth)};if(r===t.month-1)return{key:`last-month`,label:`Last month`,rank:Lp(Ip.lastMonth)};if(n.getFullYear()===t.year)return{key:`this-year`,label:`Earlier this year`,rank:Lp(Ip.thisYear)};let i=n.getFullYear();return{key:`year-${i}`,label:String(i),rank:Lp(Ip.year)+i}}function Wp(e,t,n=`desc`,r=new Date){let i=Hp(r),a=new Map;for(let n of e){let e=Up(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 Gp(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 Kp(e,t=``){return`/Trash${e?`/${encodeURIComponent(e)}`:``}${t?`/${t}`:``}`}function qp(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 Jp=(e,t)=>`${bt.workspaces}/${encodeURIComponent(e)}/backends/file/${encodeURIComponent(t)}/trash`;async function Yp(e,t){let n=[],r=new Set,i=null,a=null;do{let o=new URLSearchParams({limit:`1000`,...i?{cursor:i}:{}}),s=await U.get(`${Jp(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 Xp(e,t,n){return Qp(e,t,n,`restore`)}function Zp(e,t,n){return Qp(e,t,n,`discard`)}async function Qp(e,t,n,r){let i=[...new Set(n)],a=[];try{for(let n=0;n<i.length;n+=100){let o=await U.post(`${Jp(e,t)}/${r}`,{ids:i.slice(n,n+100)});a.push(...o.results)}return a}finally{ln(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 $p(e,t){let n=Gp(`backends`,t);if(!n?.backend)return;let{items:r}=await Yp(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 Xp(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 em(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 tm(e,t){let n=Gp(`backends`,t);if(!n?.backend)return;let{items:r}=await Yp(e,n.backend),i=r.filter(e=>!n.prefix||e.key===n.prefix||e.key.startsWith(`${n.prefix}/`));if(!em(n.backend,i))return;let a=await Zp(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 nm(){let{showProgress:e}=wt();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 rm=new Map;function im(e,t,n,r,i){let a=JSON.stringify([t,n,r]),o=rm.get(a);if(o)return o;let s=(async()=>{let a=e({title:`Resyncing…`,description:r});try{for(await dn(t,n,r);;){let e=await Zt(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 rm.set(a,s),s.finally(()=>{rm.get(a)===s&&rm.delete(a)}).catch(()=>{}),s}var am=[`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`],om=new Map;function sm(e,t,n){ln(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 cm(e,t){let n=om.get(e);if(!n){let t=new Set([e]),r=new Set,i,a=am.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)ln(e,n),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:e,treeName:n,cacheInvalidated:!0}}))},200))};return mo.on(n,a),[n,a]});n={users:0,workspaceIds:t,stop:()=>{clearTimeout(i);for(let t of r)ln(e,t);a.forEach(([e,t])=>mo.off(e,t))}},om.set(e,n)}n.users++,t&&n.workspaceIds.add(t);let r=n;return()=>{--r.users===0&&(r.stop(),om.delete(e))}}function lm({contextId:e,workspaceId:t,treeName:n,onRefresh:r}){let i=nm(),{showProgress:a}=wt(),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 fn(t,n,r,o);else return!1;let a=ac(n);if(i&&a)try{e?await er(e,n,a):t&&await At(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 Dt(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 At(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 Nn(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 It(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 xn(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 K(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 At(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 Ht(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 yn(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 Mt(t,e,t,o);return l(300),n},[t,o,l]),x=(0,q.useCallback)(async(e,n)=>{if(!t)return!1;try{await nn(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 Ot(t,e,o);return l(),n},[t,o,l]),C=(0,q.useCallback)(async e=>{if(!t)return!1;let n=await rn(t).catch(()=>[]),r=Tn(e,n);return r?(await im(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 rn(t).catch(()=>[]),i=an(e,r);if(!i)return!1;let a=i.key?`${i.key}/${n}`:n;return await tn(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 rn(t).catch(()=>[]),i=an(e,r);return!i||!i.key?!1:(await cn(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 rn(t),r=Dn(e,n);if(!r)throw Error(`This folder is not on a writable backend, or is a backend root.`);try{return await zt(t,r.driver,r.address,r.key),!0}finally{l(200)}}):!1,[t,l,i]),D=(0,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:()=>{sm(t,o),l()}})},[t,o,l]),O=(0,q.useCallback)(async(e,n)=>{if(!t)return;let r=await s(()=>Promise.resolve().then(()=>dm),void 0);if(e===`import`)r.showDocumentImport(async e=>{if((await sn(t,n,e,o,Mn(o))).length!==e.length)throw Error(`Some documents could not be imported`);return sm(t,o),l(),!0});else{let e=[];for(let r=0;;){let i=await pn(t,n,[],{treeName:o,treeType:Mn(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 um({x:e,y:t,workspaceName:n,treeName:r,path:i,onClose:a,onOpen:o,onOpenToSide:s,pastedDocumentIds:c,onPasteDocuments:l}){let d=Pi(),f=lm({workspaceId:n,treeName:r}),p=r===`backends`,h=p?an(i):null,[g,_]=(0,q.useState)([]);(0,q.useEffect)(()=>{if(!p)return;let e=!1;return rn(n).then(t=>{e||_(t)}).catch(()=>{}),()=>{e=!0}},[n,p]);let v=p?Dn(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:V(`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=Mo(i);return{kind:e,storeTo:t?.backend||``,storeFolder:t?.rel||``}})():{kind:e,path:`dir:${i}`,storeFolder:e===`download`?`Downloads`:Po(i)};d(`/workspaces/${n}/settings/hooks?${No(t).toString()}`)},E=(e,t=``)=>{let n=prompt(e,t)?.trim();return n&&n!==t&&!n.includes(`/`)?n:null},D=Gp(r,i);return D?(0,Y.jsxs)(js,{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)(L,{className:`h-3 w-3`}),`Open Trash`,()=>o(i)),D.backend&&C((0,Y.jsx)(ht,{className:`h-3 w-3`}),`Restore original paths`,()=>$p(n,i)),D.backend&&C((0,Y.jsx)(L,{className:`h-3 w-3`}),`Empty Trash`,()=>tm(n,i),!0)]}):(0,Y.jsxs)(js,{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)(he,{className:`w-3 h-3`}),`Open`,()=>o(i)),s&&C((0,Y.jsx)(dt,{className:`w-3 h-3`}),`Open to the side`,()=>s(i)),w,p?h&&(0,Y.jsxs)(Y.Fragment,{children:[C((0,Y.jsx)(ze,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=E(`New folder name:`);e&&await f.onCreateBackendFolder?.(i,e)}),h.key&&C((0,Y.jsx)(N,{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)(ne,{className:`w-3 h-3`}),`Create storage rule…`,()=>T(`store`))]}):(0,Y.jsxs)(Y.Fragment,{children:[C((0,Y.jsx)(ze,{className:`w-3 h-3`}),`New folder here`,async()=>{let e=E(`New folder name:`);e&&await f.onInsertPath(`${i===`/`?``:i}/${e}`)}),C((0,Y.jsx)(N,{className:`w-3 h-3`}),`Rename`,async()=>{let e=E(`New name:`,y);e&&await f.onRenamePath(i,e)}),C((0,Y.jsx)(ne,{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)(m,{className:`w-3 h-3`}):(0,Y.jsx)(te,{className:`w-3 h-3`}),b?`Unpin`:`Pin`,async()=>{b?await jn(n,b.id):await Pt(n,i,r),window.dispatchEvent(new CustomEvent(`workspace:tree:refresh`,{detail:{workspaceName:n}}))}),w,f.onImportDocuments&&C((0,Y.jsx)(ze,{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)(A,{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)(L,{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)(L,{className:`w-3 h-3`}),`Remove`,async()=>{confirm(`Remove "${i}" and all children?`)&&await f.onRemovePath(i,!0)},!0)]})]})}var dm=t({DocumentList:()=>Im,default:()=>Im,showDocumentExport:()=>Rm,showDocumentImport:()=>Lm});function fm({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(ru),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)(ms,{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)(W,{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)(W,{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)(W,{onClick:o,children:`Close`})]})]})})}function pm({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,lo.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)(W,{variant:`outline`,onClick:u,disabled:a,children:`Cancel`}),(0,Y.jsx)(W,{onClick:l,disabled:a||!r.trim(),children:a?`Importing...`:`Import Documents`})]})]})})}),window.document.body)}function mm({document:e}){let{replicating:t,label:n}=G(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)(ut,{className:`h-3 w-3 animate-spin`}),n]}):null}function hm(e){return e.clientX||e.clientY?{x:e.clientX,y:e.clientY}:Bs(e.currentTarget,`inside`)}function gm({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 _m(e,t,n){e.target===e.currentTarget&&(e.key===`Enter`?(e.preventDefault(),t()):e.key===` `&&n&&(e.preventDefault(),n()))}function vm({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=is(),[c,l]=(0,q.useState)(!1),{replicating:u}=G(e),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=Gt(e),m=bm(e),h=m||Sm(e),{blobUrl:g}=Ju(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),_=t=>{o?.(t,e.id)},v=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),y=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),b=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},x=e=>{e.shiftKey&&e.preventDefault()},S=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(cu,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>_m(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring transition-opacity ${u?`opacity-60`:``} ${t?`bg-info-subtle hover:bg-info-subtle`:`hover:bg-muted/50`}`,onClick:b,onMouseDown:x,...s,onContextMenu:S,draggable:!0,onDragStart:_,children:[(0,Y.jsx)(uu,{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)(uu,{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)(wc,{document:e,chip:!0})}),(0,Y.jsx)(uu,{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}),p.isExternal&&(0,Y.jsx)(Ae,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(0,Y.jsx)(mm,{document:e})]}),p.subtitle&&(0,Y.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:p.subtitle,children:p.subtitle})]})}),(0,Y.jsx)(uu,{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)(uu,{className:`hidden text-xs text-muted-foreground lg:table-cell`,children:e.id}),(0,Y.jsx)(uu,{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)(uu,{className:`hidden text-xs text-muted-foreground sm:table-cell`,children:v(e.createdAt)}),(0,Y.jsx)(uu,{className:`w-12 text-right`,children:(0,Y.jsx)(gm,{documentId:e.id,onOpenActions:a})})]}),(0,Y.jsx)(bp,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function ym({document:e,isSelected:t,workspaceId:n,onSelect:r,onRightClick:i,onOpenActions:a,onDragStart:o}){let s=is(),[c,l]=(0,q.useState)(!1),u=e.schema===`data/schema/tab`,{replicating:d}=G(e),f=u?e.data.url:null,p=Gt(e),m=bm(e),h=m||Sm(e),{blobUrl:g,loading:_}=Ju(n??``,e.id,128,{enabled:h,blobFallback:m,version:e.checksumArray?.[0]??null}),v=t=>{o?.(t,e.id)},y=e=>new Date(e).toLocaleDateString(`en-US`,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),b=(()=>{let t=e.checksumArray?.[0];if(t){let[e,n]=t.split(`/`);if(n)return{algo:e,hash:n.substring(0,8)+`...`}}return null})(),x=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&(i?r(e.id,!t,i):r(e.id,!0,i)),i||(u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0))},S=e=>{e.shiftKey&&e.preventDefault()},C=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),i?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>_m(n,()=>u&&f?window.open(f,`_blank`,`noopener,noreferrer`):l(!0),()=>r?.(e.id,!t,!0)),className:`border rounded-(--card-radius) p-4 transition cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring ${d?`opacity-60`:``} ${t?`bg-info-subtle border-info ring-1 ring-info`:``} ${u&&!t?`hover:bg-info-subtle hover:border-info`:t?``:`hover:bg-accent/50`}`,onClick:x,onMouseDown:S,...s,onContextMenu:C,draggable:!0,onDragStart:v,children:(0,Y.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[h&&(0,Y.jsx)(`div`,{className:`h-14 w-14 shrink-0 overflow-hidden rounded-md border bg-muted/40`,children:g?(0,Y.jsx)(`img`,{src:g,alt:p.title,loading:`lazy`,className:`h-full w-full object-cover`}):_?(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)(wc,{document:e})})}),(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)(wc,{document:e,chip:!0}),(0,Y.jsx)(`h4`,{className:`font-medium truncate min-w-0 flex-1 max-w-[640px]`,title:p.title,children:p.title}),p.isExternal&&(0,Y.jsx)(Ae,{className:`h-3 w-3 text-muted-foreground flex-shrink-0`}),(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:p.schemaLabel}),(0,Y.jsx)(mm,{document:e})]}),p.subtitle&&(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground mb-2 truncate`,title:p.subtitle,children:p.subtitle}),p.preview&&(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground mb-3 line-clamp-2 break-all overflow-hidden`,children:p.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})]}),b&&(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(E,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{className:`font-mono`,title:`${b.algo} checksum`,children:b.hash})]}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 flex-shrink-0`,children:[(0,Y.jsx)(me,{className:`h-3 w-3`}),(0,Y.jsx)(`span`,{title:`Created: ${y(e.createdAt)}`,children:y(e.createdAt)})]})]})]}),(0,Y.jsx)(gm,{documentId:e.id,onOpenActions:a,className:`-mr-1 -mt-1 p-2`})]})}),(0,Y.jsx)(bp,{document:e,isOpen:c,onClose:()=>l(!1),workspaceId:n})]})}function bm(e){return(e.schema===`data/schema/file`||e.schema===`data/schema/drawing`)&&String(e.metadata?.contentType||``).startsWith(`image/`)}function xm(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``).startsWith(`video/`)}function Sm(e){return e.schema===`data/schema/file`&&String(e.metadata?.contentType||``)===`application/pdf`}function Cm({workspaceId:e,documentId:t,fallback:n}){let{src:r,error:i}=Un(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`,children:[(0,Y.jsx)(`video`,{src:r,preload:`metadata`,muted:!0,playsInline:!0,onError:()=>o(!0),className:`block h-auto w-full`}),(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)(ee,{className:`h-3.5 w-3.5`})})]}):(0,Y.jsx)(`div`,{className:`aspect-video w-full animate-pulse bg-muted/60`})}function wm({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}=Rn(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)(rd,{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)(wc,{document:e,size:10,chip:!0}),i&&s&&(0,Y.jsx)(`span`,{className:`sr-only`,children:`Loading text preview`})]})})}function Tm({document:e,isSelected:t,workspaceId:n,onSelect:r,onOpenToSide:i,onRightClick:a,onOpenActions:o,onDragStart:s}){let c=is(),[l,u]=(0,q.useState)(!1),d=e.schema===`data/schema/tab`,f=d?e.data.url:null,p=bm(e),m=xm(e),h=p||Sm(e),g=Gt(e),_=Vt(String(e.metadata?.contentType||``).split(`;`)[0].trim().toLowerCase(),e.metadata?.filename||Ft(e)),v=e.schema===`data/schema/file`&&(_===`markdown`||_===`text`)&&(e.metadata?.size??e.data?.size??0)<=1048576,y=!h&&e.schema!==`data/schema/file`&&!!(g.preview||g.subtitle),{replicating:b}=G(e),{blobUrl:x,loading:S}=Ju(n??``,e.id,768,{enabled:h,blobFallback:p,version:e.checksumArray?.[0]??null}),C=n=>{let i=n.ctrlKey||n.metaKey;if(n.shiftKey&&r){n.preventDefault(),r(e.id,!0,i,!0);return}r&&r(e.id,!i||!t,i),i||(d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0))},w=n=>{n.preventDefault(),n.stopPropagation(),r&&!t&&r(e.id,!0,!1),a?.(n,e.id)};return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)(`div`,{tabIndex:0,"data-document-id":e.id,"aria-selected":!!t,onKeyDown:n=>_m(n,()=>d&&f?window.open(f,`_blank`,`noopener,noreferrer`):u(!0),()=>r?.(e.id,!t,!0)),className:`group relative mb-3 flex break-inside-avoid flex-col overflow-hidden rounded-(--card-radius) border transition cursor-pointer outline-none hover:shadow-elevation-2 focus-visible:ring-2 focus-visible:ring-ring ${b?`opacity-60`:``} ${t?`ring-2 ring-info border-info`:``}`,onClick:C,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},...c,onContextMenu:w,draggable:!0,onDragStart:t=>s?.(t,e.id),title:g.title,children:[(0,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:`relative w-full bg-muted/40 ${h&&x||y||v&&n||m&&n?``:`aspect-square`}`,children:[h&&S&&(0,Y.jsx)(`div`,{className:`absolute inset-0 animate-pulse bg-muted/60`}),h&&x?(0,Y.jsx)(`img`,{src:x,alt:g.title,loading:`lazy`,className:`block h-auto w-full`}):m&&n?(0,Y.jsx)(Cm,{workspaceId:n,documentId:e.id,fallback:(0,Y.jsx)(`div`,{className:`flex aspect-square w-full items-center justify-center`,children:(0,Y.jsx)(wc,{document:e,size:10,chip:!0})})}):v&&n?(0,Y.jsx)(wm,{document:e,workspaceId:n,markdown:_===`markdown`},`${n}:${e.id}:${e.checksumArray?.[0]??``}`):y?(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)(wc,{document:e}),(0,Y.jsx)(`span`,{className:`min-w-0 truncate text-[10px] uppercase tracking-wide text-muted-foreground`,children:g.schemaLabel})]}),(0,Y.jsx)(`div`,{className:`line-clamp-2 text-sm font-semibold leading-snug`,children:g.title}),g.subtitle&&(0,Y.jsx)(`div`,{className:`truncate text-[11px] text-info`,children:g.subtitle}),(0,Y.jsx)(`p`,{className:`line-clamp-[8] text-xs leading-relaxed text-muted-foreground`,children:g.preview})]}):(0,Y.jsx)(`div`,{className:`flex h-full w-full items-center justify-center`,children:(0,Y.jsx)(wc,{document:e,size:10,chip:!0})}),(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)(de,{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`})})]})]}),!y&&(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:g.title,children:g.title}),g.isExternal&&(0,Y.jsx)(Ae,{className:`h-3 w-3 shrink-0 text-muted-foreground`})]})]}),(0,Y.jsx)(bp,{document:e,isOpen:l,onClose:()=>u(!1),workspaceId:n})]})}function Em(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)&&!ql(c,i,r,e.path))try{await t(e.path,c.documentIds,{move:!1,sourcePath:c.sourcePath??n,sourceTreeName:c.sourceTreeName??r})}catch{}}}}function Dm(e,t,n){e.stopPropagation(),!(t.isParent||!n)&&(e.preventDefault(),n(t.path,e))}function Om({folder:e,className:t=`h-4 w-4`}){if(e.isParent)return(0,Y.jsx)(gt,{className:`${t} text-muted-foreground`});let n=e.color?{color:e.color}:void 0;return(0,Y.jsx)(pe,{className:`${t} ${e.color?``:`text-warning`}`,style:n})}var km=e=>e.isParent?`Parent folder`:e.label&&e.label!==e.name?`${e.label} (${e.name})`:e.name;function Am({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Em(e,r,i,a,o);return(0,Y.jsxs)(`button`,{type:`button`,title:km(e),onClick:()=>t?.(e.path),onContextMenu:t=>Dm(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)(Om,{folder:e,className:`h-4 w-4 group-hover:hidden`}),e.isParent?(0,Y.jsx)(gt,{className:`hidden h-4 w-4 group-hover:block`}):(0,Y.jsx)(he,{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 jm({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Em(e,r,i,a,o),c=e.color?{color:e.color}:void 0;return(0,Y.jsxs)(`button`,{type:`button`,title:km(e),onClick:()=>t?.(e.path),onContextMenu:t=>Dm(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)(gt,{className:`h-10 w-10`,strokeWidth:1.5}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(pe,{className:`h-14 w-14 group-hover:hidden ${e.color?``:`text-warning`}`,strokeWidth:1.25,fill:`currentColor`,fillOpacity:.18,style:c}),(0,Y.jsx)(he,{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 Mm({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)(jm,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function Nm({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)(Am,{folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o},e.path))})}function Pm({folder:e,onOpen:t,onMenu:n,onPasteDocuments:r,contextPath:i,treeName:a,workspaceId:o}){let s=Em(e,r,i,a,o);return(0,Y.jsxs)(cu,{"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=>Dm(t,e,n),onDragOver:s.onDragOver,onDragLeave:s.onDragLeave,onDrop:s.onDrop,title:km(e),children:[(0,Y.jsx)(uu,{className:`w-10`}),(0,Y.jsx)(uu,{className:`w-12`,children:(0,Y.jsx)(Om,{folder:e})}),(0,Y.jsx)(uu,{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)(uu,{className:`hidden md:table-cell text-xs text-muted-foreground`,children:e.isParent?``:`Folder`}),(0,Y.jsx)(uu,{className:`hidden lg:table-cell`}),(0,Y.jsx)(uu,{className:`hidden lg:table-cell`}),(0,Y.jsx)(uu,{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)(uu,{className:`w-12 md:w-auto`})]})}function Fm({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)(vt,{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 Im({externalSearchQuery:e,toolbarActions:t,documents:n,isLoading:r,contextPath:i,treeName:a,workspaceId:o,totalCount:s,onRemoveDocument:d,onDeleteDocument:f,onDestroyDocument:p,onRemoveDocuments:m,onDeleteDocuments:h,onDestroyDocuments:v,onCopyDocuments:y,onCutDocuments:b,onPasteDocuments:x,onImportDocuments:S,onSelectionChange:C,pastedDocumentIds:w,viewMode:E=`card`,allowViewToggle:k=!1,activeContextUrl:ee,currentContextUrl:te,currentPage:j=1,pageSize:M=50,onPageChange:N,onPageSizeChange:P,onPurgeDocuments:ae,disablePurgeDocuments:oe=!1,backendSearchQueries:se=[],onBackendSearch:ce,onRemoveBackendQuery:le,serverSort:ue,onServerSortChange:pe,scope:me=`path`,onScopeChange:I,canSaveChanges:he=!1,isSavingChanges:ge=!1,onSaveChanges:_e,linkTree:R,folders:ve,onOpenFolder:ye}){let[be,xe]=(0,q.useState)(()=>{if(!k)return E;try{let e=localStorage.getItem(`doclist:view`);if(e===`card`||e===`table`||e===`tile`)return e}catch{}return E}),Se=k?be:E,z=(0,q.useCallback)(e=>{xe(e);try{localStorage.setItem(`doclist:view`,e)}catch{}},[]),[Te,Ee]=(0,q.useState)(()=>{try{return localStorage.getItem(`doclist:groupdates`)!==`off`}catch{return!0}}),De=(0,q.useCallback)(()=>{Ee(e=>{let t=!e;try{localStorage.setItem(`doclist:groupdates`,t?`on`:`off`)}catch{}return t})},[]),[Oe,ke]=(0,q.useState)(new Set),Pe=(0,q.useCallback)(e=>{ke(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[B,Fe]=(0,q.useState)(new Set),[Ie,Le]=(0,q.useState)(null),[Re,Be]=(0,q.useState)(null),He=tr(),Ue=!!(He&&o),Ke=(0,q.useCallback)((e,t=!1)=>{if(!He||!o)return;let r=e.map(e=>n.find(t=>t.id===e)).filter(e=>!!e);r.length!==0&&He.openAddRelated({workspaceName:o,documents:r},t)},[He,o,n]),[qe,Je]=(0,q.useState)(!1),[Ye,Qe]=(0,q.useState)(null),[$e,et]=(0,q.useState)(!1),[tt,nt]=(0,q.useState)(null),[at,ot]=(0,q.useState)(!1),st=(0,q.useRef)(!1),ct=(0,q.useRef)(!1),lt=a===`backends`&&me===`path`?Mo(i):null;(0,q.useEffect)(()=>()=>{st.current=!0},[]);let[ut,pt]=(0,q.useState)(!1),[ht,gt]=(0,q.useState)(null),[_t,yt]=(0,q.useState)(!1),[V,bt]=(0,q.useState)(null),H=Pn()==null&&!!o,[U,xt]=(0,q.useState)(null),[St,Ct]=(0,q.useState)(null),Et=!!(R&&x),Dt=!!o,{showSuccessToast:Ot,showErrorToast:kt}=Tt(),{showProgress:At}=wt(),jt=nu(),Mt=o?e=>jt.open(e,o):void 0,Nt=me===`workspace`,Pt=Nt?void 0:d,It=Nt?void 0:m,[Lt,Rt]=(0,q.useState)(!1),[zt,Bt]=(0,q.useState)(!1),[Vt,Ht]=(0,q.useState)(``),G=e??Vt,Ut=e!==void 0,[Wt,Kt]=(0,q.useState)(!1),qt=se.length>0,Jt=(0,q.useRef)(null),Yt=(0,q.useCallback)(()=>{Ht(``),Jt.current&&(Jt.current.value=``)},[]);(0,q.useEffect)(()=>{if(!k||window.matchMedia(`(max-width: 767px)`).matches)return;let e=Jt.current;if(!e)return;let t=setTimeout(()=>{let t=window.document.activeElement;t&&t!==window.document.body||e.focus()},60);return()=>clearTimeout(t)},[k]);let Xt=JSON.stringify([o,a,i]),[Zt,Qt]=(0,q.useState)(Xt);Xt!==Zt&&(Qt(Xt),Fe(new Set),Qe(null),Be(null),Le(null)),(0,q.useEffect)(()=>{C?.(Array.from(B))},[B,C]);let $t=(0,q.useCallback)(()=>{if(!ce)return;let e=G.trim();e&&(ce(e),Yt())},[ce,G,Yt]),en=(0,q.useCallback)(()=>{Yt(),le&&se.length>0&&le(-1)},[le,se.length,Yt]),tn=(0,q.useCallback)((e,t)=>{let n;B.has(t)&&B.size>1?n=Array.from(B):(n=[t],Fe(new Set([t])));let r={type:`document`,documentIds:n,sourcePath:me===`path`?i:void 0,sourceTreeName:a,sourceWorkspaceId:o};e.dataTransfer.setData(`application/json`,JSON.stringify(r)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setDragImage(e.currentTarget,0,0)},[B,i,a,o,me]),nn=(0,q.useCallback)(async e=>{if(!x)return;let t=e.dataTransfer.getData(`application/json`);if(!t)return;let n=null;try{n=JSON.parse(t)}catch{return}n?.type!==`document`||!Array.isArray(n.documentIds)||n.documentIds.length===0||(e.preventDefault(),e.stopPropagation(),Kt(!1),!ql(n,o,a,i)&&(await x(i,n.documentIds,{move:e.shiftKey,sourcePath:n.sourcePath,sourceTreeName:n.sourceTreeName}),Fe(new Set)))},[i,a,o,x]),rn=(0,q.useCallback)(e=>{x&&Array.from(e.dataTransfer.types).includes(`application/json`)&&(e.preventDefault(),e.dataTransfer.dropEffect=e.shiftKey?`move`:`copy`,Kt(!0))},[x]),an=(0,q.useCallback)(e=>{e.currentTarget.contains(e.relatedTarget)||Kt(!1)},[]),on=(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}),[]),sn=(0,q.useMemo)(()=>n.length===0?null:new Xn(n,on),[n,on]),cn=(0,q.useDeferredValue)(G),K=(0,q.useMemo)(()=>{if(!cn.trim())return n;let{text:e,ids:t,invalid:r}=ts(cn);if(r)return[];let i=e&&sn?sn.search(e).map(e=>e.item):n;return t.length?i.filter(e=>t.every(t=>e.id===t)):i},[n,cn,sn]),ln=(0,q.useMemo)(()=>{if(!ve||ve.length===0||cn.trim())return[];let e=ue?.order===`desc`?-1:1;return[...ve].sort((t,n)=>Number(!!n.isParent)-Number(!!t.isParent)||(t.label||t.name).localeCompare(n.label||n.name,void 0,{numeric:!0,sensitivity:`base`})*e)},[ve,cn,ue?.order]),un=ln.length>0,[dn,fn]=(0,q.useState)(null),pn=(0,q.useMemo)(()=>o&&a&&ye?(e,t)=>fn({x:t.clientX,y:t.clientY,path:e}):void 0,[o,a,ye]),hn={folders:ln,onOpen:ye,onMenu:pn,onPasteDocuments:x,contextPath:i,treeName:a,workspaceId:o},{sorted:gn,sort:vn,toggleSort:yn}=pu(K,(0,q.useMemo)(()=>({title:e=>Gt(e).title?.toLowerCase()??``,schema:e=>Gt(e).schemaLabel??``,type:_n,id:e=>e.id,created:e=>Date.parse(e.createdAt)||0}),[])),bn=(0,q.useCallback)(e=>Fp(e,ue?.sortBy),[ue?.sortBy]),xn=(0,q.useMemo)(()=>Wp(K,bn,ue?.order===`asc`?`asc`:`desc`),[K,bn,ue?.order]),Sn=Te&&!mn(ue?.sortBy)&&xn.length>1,Cn=(0,q.useCallback)((e,t)=>{Fe(n=>{let r=new Set(n);for(let n of e)t?r.add(n):r.delete(n);return r})},[]),wn=(0,q.useMemo)(()=>(Se===`table`?gn:Sn?xn.filter(e=>!Oe.has(e.key)).flatMap(e=>e.items):K).map(e=>e.id),[Se,gn,Sn,xn,Oe,K]),Tn=(0,q.useRef)(null),En=JSON.stringify([o,i,a,j]),Dn=(0,q.useCallback)(e=>{Tn.current=null,Fe(t=>t.size===e.size&&[...t].every(t=>e.has(t))?t:e)},[]),An=(0,q.useCallback)((e,t,n,r=!1)=>{let i=Tn.current,a=i?.scope===En&&wn.includes(i.id)?i.id:null;(!r||a===null)&&(Tn.current={scope:En,id:e}),Fe(i=>{if(r)return as(wn,a,e,i,n);let o=n?new Set(i):new Set;return t?o.add(e):o.delete(e),o})},[En,wn]),jn=(0,q.useCallback)((e,t)=>{let n;B.has(e)?n=Array.from(B):(n=[e],Fe(new Set([e]))),Le({anchor:t,ids:n})},[B]),Mn=(0,q.useCallback)((e,t)=>{jn(t,Bs(e))},[jn]),Nn=(0,q.useCallback)((e,t)=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),jn(t,hm(e)))},[jn]),Fn=(0,q.useCallback)(async(e,t)=>{if(t.length!==0&&e.targetIds.length!==0){Je(!0);try{for(let n of t)await On(o,n,e.predicate,e.targetIds,e.direction);let n=t.length*e.targetIds.length;Ot(`Created ${n} relation${n===1?``:`s`}`),hu(),Be(null)}catch(e){kt(e instanceof Error?e.message:`Failed to create relations`)}finally{Je(!1)}}},[o,Ot,kt]),In=(0,q.useCallback)(async(e,t,n)=>{if(x){for(let r of e)await x(r,t,{move:!1,targetTreeName:n?.treeName,targetTreeType:n?.treeType});Fe(new Set)}},[x]),Ln=(0,q.useCallback)(async(e,t,r)=>{if(!o||!Ye||ct.current)return;ct.current=!0,st.current=!1,ot(!1),et(!0);let i=At({title:t===`delete`?`Deleting…`:t===`move`?`Moving…`:`Copying…`,description:`${Ye.ids.length} document(s) · ${e.join(`, `)}`});try{let a=n=>kn(o,n,{to:e,mode:t,keepDocument:r.keepDocument,...t===`delete`&<?{deleteFrom:{backend:lt.backend,folder:lt.rel}}:{},folder:r.folder,filename:r.filename,onConflict:r.onConflict}),s=t===`delete`?await go(Ye.ids,a,{shouldStop:()=>st.current,onProgress:(t,n)=>{nt({completed:t,total:n}),i.update({title:`Deleting…`,description:`${t} / ${n} document(s) · ${e.join(`, `)}`})}}):{...await a(Ye.ids),pending:[]},c=s.successful.filter(e=>e.transfers?.every(e=>e.state===`unchanged`)).length,l=s.successful.filter(e=>e.transfers?.some(e=>e.state===`pending`)).length,u=s.successful.length-c-l,d=s.failed.length,f=t===`delete`?`Deleted from`:t===`move`?`Moved to`:`Copied to`,p=e.join(`, `),m=[c?`${c} already there`:null,l?`${l} queued for backend sync`:null,d?`${d} skipped`:null,s.pending.length?`${s.pending.length} not processed`:null].filter(Boolean).join(` · `),h=`${f} ${p}: ${u} document${u===1?``:`s`}${m?` · ${m}`:``}`;d>0?(i.fail({title:`Operation incomplete`,description:`${h}. ${ns(s.failed,new Map(n.map(e=>[e.id,Gt(e).title])))}`,variant:`destructive`}),console.warn(`Backend transfer skipped documents:`,s.failed)):i.done({title:s.pending.length?`Operation stopped`:l?`Transfer queued`:`Operation complete`,description:h}),window.dispatchEvent(new CustomEvent(`workspace:documents:refresh`));let g=[...s.failed.map(e=>e.id),...s.pending];Qe(g.length?{ids:g,mode:t}:null),Fe(new Set(g))}catch(e){i.fail({title:`Operation failed`,description:e instanceof Error?e.message:String(e),variant:`destructive`})}finally{ct.current=!1,et(!1),nt(null)}},[o,Ye,lt,n,At]),Rn=(0,q.useCallback)(()=>{B.size===K.length?Fe(new Set):Fe(new Set(K.map(e=>e.id)))},[B.size,K]),zn=(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)}},[]),Bn=e=>{if(e.length===0)return[];let t=e.length,r=t>1?` (${t})`:``,i=t===1?n.find(t=>t.id===e[0]):void 0,o=()=>Fe(new Set),s=e.some(e=>(n.find(t=>t.id===e)?.locations?.length??0)>0),c=[],l=e=>{e&&c.push(e)};if(i){let e=i.schema===`data/schema/tab`?i.data.url:null;l({id:`view`,group:`open`,label:`View details`,icon:dt,run:()=>Ct({document:i})}),l(zf(i)&&H&&{id:`edit`,group:`open`,label:`Edit`,icon:O,run:()=>Ct({document:i,edit:!0})}),l(e&&{id:`open-url`,group:`open`,label:`Open URL`,icon:Ae,run:()=>{window.open(e,`_blank`,`noopener,noreferrer`)}}),l(Mt&&{id:`open-side`,group:`open`,label:`Open to the side`,icon:de,run:()=>Mt(i)})}return l(y&&{id:`copy`,group:`clipboard`,label:`Copy${r}`,icon:u,shortcut:`Mod+C`,run:()=>y(e)}),l(b&&{id:`cut`,group:`clipboard`,label:`Cut${r}`,icon:we,shortcut:`Mod+X`,run:()=>b(e)}),l(i&&{id:`copy-id`,group:`clipboard`,label:`Copy ID`,icon:We,run:()=>zn(String(i.id))}),l(i&&H&&{id:`create-rule`,group:`organize`,label:`Create rule…`,icon:Ze,run:()=>xt(i)}),l(Et&&{id:`link-to`,group:`organize`,label:`Link to…${r}`,icon:Ne,run:()=>Be(e)}),l(Ue&&{id:`add-related`,group:`organize`,label:`Add related document…${r}`,icon:ze,run:t=>Ke(e,t?.shiftKey)}),l(H&&{id:`bulk-edit`,group:`organize`,label:`Bulk edit…${r}`,icon:O,run:()=>bt(e)}),l(H&&{id:`copy-workspace`,group:`organize`,label:`Copy to workspace…`,icon:u,run:t=>{yt(!!t?.shiftKey),gt(e)}}),l({id:`export`,group:`organize`,label:`Export…${r}`,icon:Me,run:()=>Rt(!0)}),l(a!==`backends`&&(Pt||It)&&{id:`remove`,group:`remove`,label:`Remove (unlink) from folder${r}`,icon:_,shortcut:`Delete`,hint:`Unlinks from this folder; the document stays in the index`,run:()=>{t===1&&Pt?Pt(e[0]):It?.(e),o()}}),l(a!==`backends`&&(f||h)&&{id:`delete`,group:`remove`,label:`Delete from index${r}`,icon:L,destructive:!0,hint:`Removes the document from the index entirely; file data stays on its backend(s)`,run:()=>{t===1&&f?f(e[0]):h?.(e),o()}}),s&&Dt?(l({id:`backend-copy`,group:`backends`,groupLabel:`Backends`,label:`Copy to backend…${r}`,icon:ne,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…${r}`,icon:Ve,hint:`Move the file data to another storage backend (source released once the copy is durable)`,run:()=>Qe({ids:e,mode:`move`})}),l({id:`backend-delete`,group:`backends`,label:`Delete from backend…${r}`,icon:L,destructive:!0,hint:`Delete the file data from selected backends (copies elsewhere are kept)`,run:()=>Qe({ids:e,mode:`delete`})})):s&&(p||v)&&l({id:`destroy`,group:`backends`,label:`Delete from backend(s)${r}`,icon:L,destructive:!0,hint:`Deletes the document and its file data from the storage backend(s)`,run:()=>{t===1&&p?p(e[0]):v?.(e),o()}}),c},Vn=()=>{let e=[],t=t=>{t&&e.push(t)},r=w??[];return t(x&&r.length>0&&{id:`paste`,group:`clipboard`,label:`Paste (${r.length})`,icon:A,shortcut:`Mod+V`,run:async()=>{try{await x(i,r)}catch(e){console.error(`Failed to paste documents:`,e)}}}),t(K.length>0&&{id:`select-all`,group:`select`,label:G?`Select all matches (${K.length})`:`Select all on this page`,icon:Ce,shortcut:`Mod+A`,run:()=>Fe(new Set(K.map(e=>e.id)))}),t(B.size>0&&{id:`select-none`,group:`select`,label:`Clear selection`,icon:it,run:()=>Fe(new Set)}),t(x&&{id:`add-existing`,group:`add`,label:`Add existing documents…`,icon:Xe,hint:`Browse and add existing documents to this folder`,run:()=>pt(!0)}),t(S&&{id:`import`,group:`add`,label:`Import…`,icon:fe,run:()=>Bt(!0)}),t(n.length>0&&{id:`export-all`,group:`add`,label:`Export all…`,icon:Me,run:()=>{Fe(new Set),Rt(!0)}}),t(ae&&s>0&&{id:`purge`,group:`purge`,label:`Purge all (${s})`,icon:L,destructive:!0,disabled:oe||!!G,hint:G?`Purge is disabled while local search is active`:oe?`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:ae}),e},Hn=!!(pe&&ue&&o),Un=Ie?Ie.ids?Bn(Ie.ids):Vn():[],Wn=Ie?.ids?.length===1?n.find(e=>e.id===Ie.ids[0]):void 0,Gn=Wn?(0,Y.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,Y.jsx)(wc,{document:Wn,chip:!0}),(0,Y.jsxs)(`div`,{className:`min-w-0`,children:[(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Gt(Wn).title}),(0,Y.jsxs)(`div`,{className:`truncate text-xs text-muted-foreground`,children:[`ID: `,Wn.id,` · `,Wn.schema]})]})]}):(0,Y.jsx)(`div`,{className:`truncate text-base font-semibold`,children:Ie?.ids?`${Ie.ids.length} documents`:`This folder`}),Kn=e=>{Le({anchor:Bs(e.currentTarget),ids:B.size>0?Array.from(B):null})},qn=e=>{e.target.closest?.(`[role="dialog"]`)||(e.preventDefault(),e.stopPropagation(),Fe(new Set),Le({anchor:hm(e),ids:null}))},Jn=e=>{if(e.defaultPrevented||Is(e.target))return;let t=e.target.closest?.(`[data-document-id]`)??null;if(Rs(e)){e.preventDefault(),t?jn(Number(t.dataset.documentId),Bs(t,`inside`)):Le({anchor:Bs(e.target,`inside`),ids:B.size>0?Array.from(B):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&&An(Number(i.dataset.documentId),!0,!1,!0);return}if(e.key===`Escape`&&B.size>0){e.preventDefault(),Fe(new Set);return}Ls(e,[...Bn(Array.from(B)),...Vn()])},Yn=(0,q.useCallback)(async e=>{if(!S)return!1;try{return await S(e,i)}catch(e){return console.error(`Failed to import documents:`,e),!1}},[S,i]),Zn=e=>Sn?xn.map(t=>{let n=Oe.has(t.key),r=t.items.map(e=>e.id),i=r.reduce((e,t)=>e+ +!!B.has(t),0);return(0,Y.jsxs)(`section`,{className:`group mb-4`,children:[(0,Y.jsx)(Fm,{label:t.label,count:t.items.length,collapsed:n,allSelected:i===r.length,someSelected:i>0,onToggle:()=>Pe(t.key),onSelectAll:e=>Cn(r,e)}),!n&&e(t.items)]},t.key)}):e(K);return r?(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.jsxs)(`div`,{tabIndex:-1,onKeyDown:Jn,className:`flex-1 flex flex-col min-h-0 min-w-0 p-4 rounded-(--card-radius) outline-none transition-colors ${Wt?`ring-2 ring-inset ring-primary bg-primary/5`:``}`,onDragOver:rn,onDragLeave:an,onDrop:nn,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:G?`${K.length} of ${n.length}`:`${s.toLocaleString()} document${s===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:Ut,className:`min-w-0 truncate`,children:[`Context: `,(0,Y.jsx)(`span`,{className:`font-mono`,children:i}),ee&&te&&ee!==te&&(0,Y.jsx)(`span`,{className:`text-warning ml-2`,children:`(not yet active)`})]}),(0,Y.jsxs)(`p`,{className:`shrink-0`,children:[B.size>0&&(0,Y.jsxs)(`span`,{className:`text-info`,children:[B.size,` selected`]}),B.size>0&&(G||s>M)&&(0,Y.jsx)(`span`,{className:`mx-1`,children:`·`}),G?`on this page`:s>M?`Showing ${Math.min((j-1)*M+1,s)}–${Math.min(j*M,s)}`:null]})]})]}),!Ut&&(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:[!Ut&&I&&(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:()=>I(`path`),className:`px-2.5 py-2 transition-colors ${me===`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:()=>I(`workspace`),className:`px-2.5 py-2 border-l border-input transition-colors flex items-center gap-1 ${me===`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)(F,{className:`h-3.5 w-3.5`}),`Whole workspace`]})]}),!Ut&&(0,Y.jsxs)(`div`,{className:`relative flex-1 min-w-[12rem]`,children:[(0,Y.jsx)(mt,{className:`absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none`}),(0,Y.jsx)(`input`,{ref:Jt,type:`text`,placeholder:ce?qt?`Refine: add another query (Enter)…`:`Search documents (Enter for server search)…`:`Search documents...`,title:`Search text or an exact document ID, e.g. @id:101140. Press Enter to search the server.`,defaultValue:``,onChange:e=>Ht(e.target.value),onFocus:e=>{let t=e.currentTarget;window.matchMedia(`(max-width: 767px)`).matches&&setTimeout(()=>t.scrollIntoView({block:`center`,behavior:`smooth`}),250)},onKeyDown:e=>{e.key===`Enter`&&ce&&(e.preventDefault(),$t())},className:`w-full pl-10 pr-9 py-2 border border-input rounded-md bg-background text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent`}),(G||qt)&&(0,Y.jsx)(`button`,{onClick:en,className:`absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground hover:text-foreground`,title:`Clear search`,children:(0,Y.jsx)(T,{className:`h-4 w-4`})})]}),!Ut&&ce&&G.trim()&&!se.includes(G.trim())&&(0,Y.jsxs)(W,{size:`sm`,variant:`default`,onClick:$t,className:`shrink-0`,title:qt?`Refine: narrow the current results by this query`:`Run full-text search on the server`,children:[(0,Y.jsx)(mt,{className:`h-3.5 w-3.5 mr-1`}),qt?`Refine`:`Search server`]})]}),!Ut&&qt&&(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:`}),se.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,`"`]}),le&&(0,Y.jsx)(`button`,{onClick:()=>le(t),className:`text-muted-foreground hover:text-foreground`,title:`Remove this query`,children:(0,Y.jsx)(T,{className:`h-3 w-3`})})]})]},`${e}-${t}`)),le&&se.length>1&&(0,Y.jsx)(`button`,{onClick:()=>le(-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:[k&&(0,Y.jsx)(`div`,{className:`flex shrink-0 items-center rounded-md border p-0.5 touch-target`,children:[[`table`,c,`Table view`],[`tile`,ft,`Tile view`],[`card`,je,`Card view`]].map(([e,t,n])=>(0,Y.jsx)(`button`,{type:`button`,onClick:()=>z(e),title:n,"aria-pressed":Se===e,className:`rounded-sm p-1.5 transition-colors focus-ring ${Se===e?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Y.jsx)(t,{className:`h-4 w-4`})},e))}),k&&Se!==`table`&&!mn(ue?.sortBy)&&(0,Y.jsx)(`button`,{type:`button`,onClick:De,title:Te?`Grouping by date — click for a flat list`:`Group by date (Today, Yesterday, …)`,"aria-pressed":Te,className:`touch-target shrink-0 rounded-md border p-1.5 transition-colors focus-ring ${Te?`bg-primary text-primary-foreground`:`text-muted-foreground hover:bg-accent/50`}`,children:(0,Y.jsx)(g,{className:`h-4 w-4`})})]}),N&&s>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:M,onChange:e=>P?.(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:[Hn&&(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)(Pp,{workspaceId:o,value:ue,onChange:pe})]}),(0,Y.jsxs)(`div`,{className:`document-toolbar-actions`,children:[(n.length>0||S||x)&&(0,Y.jsxs)(`div`,{className:`contents`,children:[(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:Kn,"aria-haspopup":`menu`,"aria-label":B.size>0?`Actions (${B.size} selected)`:`Actions`,className:`document-toolbar-action-button flex items-center gap-1.5 touch-target`,title:`Actions (${Ps(`Shift+F10`)} or right-click)`,children:[(0,Y.jsx)(Ge,{className:`h-4 w-4`}),(0,Y.jsxs)(`span`,{className:`document-toolbar-action-label`,children:[`Actions`,B.size>0?` (${B.size} selected)`:``]})]}),B.size>0&&(0,Y.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:()=>Fe(new Set),"aria-label":`Clear selection`,className:`document-toolbar-action-button touch-target`,title:`Clear selection (Esc)`,children:[(0,Y.jsx)(T,{className:`h-3.5 w-3.5`}),(0,Y.jsx)(`span`,{className:`document-toolbar-action-label`,children:`Clear`})]}),w&&w.length>0&&x&&(0,Y.jsxs)(W,{variant:`outline`,size:`sm`,onClick:()=>x(i,w),className:`flex items-center gap-1.5`,title:`Paste into this folder (${Ps(`Mod+V`)})`,children:[(0,Y.jsx)(A,{className:`h-4 w-4`}),`Paste (`,w.length,`)`]})]}),he&&_e&&(0,Y.jsx)(W,{size:`sm`,variant:`outline`,onClick:_e,disabled:ge,className:`w-control-sm shrink-0 px-0 touch-target`,"aria-label":ge?`Saving filters`:`Save current query and filters`,title:`Save current query and filters`,children:(0,Y.jsx)(ie,{className:`h-3.5 w-3.5`})}),t]})]})]})}),N&&s>M&&(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((j-1)*M+1,s),` - `,Math.min(j*M,s),` of `,s]}),(0,Y.jsxs)(`div`,{className:`flex items-center gap-1 max-sm:gap-0.5`,children:[(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`First page`,onClick:()=>N(1),disabled:j===1,className:`p-1 touch-target`,children:(0,Y.jsx)(re,{className:`h-4 w-4`})}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`Previous page`,onClick:()=>N(j-1),disabled:j===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 `}),j,(0,Y.jsx)(`span`,{className:`max-sm:hidden`,children:` of `}),(0,Y.jsx)(`span`,{className:`sm:hidden`,children:`/`}),Math.ceil(s/M)]}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`Next page`,onClick:()=>N(j+1),disabled:j>=Math.ceil(s/M),className:`p-1 touch-target`,children:(0,Y.jsx)(vt,{className:`h-4 w-4`})}),(0,Y.jsx)(W,{variant:`outline`,size:`sm`,"aria-label":`Last page`,onClick:()=>N(Math.ceil(s/M)),disabled:j>=Math.ceil(s/M),className:`p-1 touch-target`,children:(0,Y.jsx)(D,{className:`h-4 w-4`})})]})]})]}),(0,Y.jsx)(kl,{scope:JSON.stringify([En,Se,wn]),selected:B,onSelectionChange:Dn,onContextMenu:qn,children:K.length===0&&!un?(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)(rt,{className:`h-12 w-12 text-muted-foreground/50 mx-auto`}),(0,Y.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:G?`No documents match your search`:`No documents found in this context`}),(0,Y.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:G?(0,Y.jsxs)(Y.Fragment,{children:[`Search: `,(0,Y.jsxs)(`span`,{className:`font-mono`,children:[`"`,G,`"`]})]}):(0,Y.jsxs)(Y.Fragment,{children:[`Path: `,(0,Y.jsx)(`span`,{className:`font-mono`,children:i})]})}),!Ut&&G&&(0,Y.jsx)(`button`,{onClick:Yt,className:`text-xs text-primary hover:text-primary/80 underline mt-1`,children:`Clear search`}),!G&&w&&w.length>0&&(0,Y.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Right-click or press `,Ps(`Mod+V`),` to paste `,w.length,` document(s)`]})]})}):Se===`tile`?(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(Mm,{...hn}),K.length===0&&(0,Y.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Zn(e=>(0,Y.jsx)(`div`,{className:`columns-[300px] gap-3 pr-2`,children:e.map(e=>(0,Y.jsx)(Tm,{document:e,isSelected:B.has(e.id),workspaceId:o,onSelect:An,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn},e.id))}))]}):Se===`table`?(0,Y.jsx)(`div`,{children:(0,Y.jsxs)(iu,{children:[(0,Y.jsx)(au,{children:(0,Y.jsxs)(cu,{children:[(0,Y.jsx)(lu,{className:`w-10`,children:(0,Y.jsx)(`input`,{type:`checkbox`,className:`h-4 w-4 cursor-pointer accent-primary align-middle`,checked:K.length>0&&B.size===K.length,ref:e=>{e&&(e.indeterminate=B.size>0&&B.size<K.length)},onChange:Rn,title:`Select all on this page`})}),(0,Y.jsx)(fu,{label:(0,Y.jsx)(`span`,{className:`max-md:sr-only`,children:`Type`}),sortKey:`type`,sort:vn,onSort:yn,className:`w-12`}),(0,Y.jsx)(fu,{label:`Title`,sortKey:`title`,sort:vn,onSort:yn,className:`w-full max-w-0 md:w-auto md:max-w-none`}),(0,Y.jsx)(fu,{label:`Schema`,sortKey:`schema`,sort:vn,onSort:yn,className:`hidden md:table-cell`}),(0,Y.jsx)(fu,{label:`ID`,sortKey:`id`,sort:vn,onSort:yn,className:`hidden lg:table-cell`}),(0,Y.jsx)(lu,{className:`hidden lg:table-cell`,children:`Checksum`}),(0,Y.jsx)(fu,{label:`Created`,sortKey:`created`,sort:vn,onSort:yn,className:`hidden sm:table-cell`}),(0,Y.jsx)(lu,{className:`w-12 md:w-auto`,children:(0,Y.jsx)(`span`,{className:`max-md:sr-only`,children:`Actions`})})]})}),(0,Y.jsxs)(ou,{children:[ln.map(e=>(0,Y.jsx)(Pm,{folder:e,onOpen:ye,onMenu:pn,onPasteDocuments:x,contextPath:i,treeName:a,workspaceId:o},e.path)),gn.map(e=>(0,Y.jsx)(vm,{document:e,isSelected:B.has(e.id),workspaceId:o,onSelect:An,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn},e.id))]})]})}):(0,Y.jsxs)(`div`,{children:[(0,Y.jsx)(Nm,{...hn}),K.length===0&&(0,Y.jsx)(`p`,{className:`py-6 text-center text-xs text-muted-foreground`,children:`No documents in this folder`}),Zn(e=>(0,Y.jsx)(`div`,{className:`space-y-3 pr-2`,children:e.map(e=>(0,Y.jsx)(`div`,{children:(0,Y.jsx)(ym,{document:e,isSelected:B.has(e.id),workspaceId:o,onSelect:An,onOpenToSide:Mt,onRightClick:Nn,onOpenActions:Mn,onDragStart:tn})},e.id))}))]})}),Ie&&(0,Y.jsx)(Gs,{anchor:Ie.anchor,items:Un,onClose:()=>Le(null),label:Ie.ids?`Document actions`:`Folder actions`,header:Gn}),(0,Y.jsx)(fm,{isOpen:Lt,onClose:()=>Rt(!1),documents:n,selectedDocuments:B}),(0,Y.jsx)(pm,{isOpen:zt,onClose:()=>Bt(!1),onImport:Yn}),ht&&o&&(0,Y.jsx)(jl,{modal:_t,workspaceId:o,ids:ht,onClose:()=>gt(null)}),Re&&R&&(0,Y.jsx)(ms,{label:`Link to`,onClose:()=>Be(null),children:(0,Y.jsx)(Lc,{sizeClassName:`h-full w-full rounded-none border-0 bg-popover text-popover-foreground shadow-none`,documentCount:Re.length,fixedWorkspaceName:o,tabs:[`context`,`directory`,`relations`],saving:qe,relationExcludeIds:new Set(Re),onConfirm:(e,t)=>In(e,Re,t),onConfirmRelation:e=>Fn(e,Re),onClose:()=>Be(null)})}),Ye&&o&&(0,lo.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)(Ql,{workspaceId:o,documentCount:Ye.ids.length,initialMode:Ye.mode,defaultFilename:Ye.ids.length===1?Ft(n.find(e=>e.id===Ye.ids[0])??{}):``,saving:$e,progress:tt,stopping:at,onStop:()=>{st.current=!0,ot(!0)},deleteFrom:lt?{backend:lt.backend,folder:lt.rel}:void 0,onConfirm:Ln,onClose:()=>{$e||Qe(null)}})}),window.document.body),ut&&x&&(0,lo.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:()=>pt(!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)($l,{sizeClassName:`h-full w-[420px] max-w-full max-md:w-full max-md:shadow-elevation-5`,fixedWorkspaceName:o,onConfirm:async e=>{await x(i,e),pt(!1)},onClose:()=>pt(!1)})})]}),window.document.body),U&&o&&(0,Y.jsx)(Cl,{workspaceId:o,document:U,onClose:()=>xt(null)},`${o}:${U.id}`),V&&o&&(0,Y.jsx)(Gl,{workspaceId:o,documentIds:V,onClose:()=>bt(null)}),(0,Y.jsx)(bp,{document:St?.document??null,isOpen:!!St,onClose:()=>Ct(null),workspaceId:o,initialEdit:St?.edit}),dn&&o&&a&&ye&&(0,Y.jsx)(um,{x:dn.x,y:dn.y,workspaceName:o,treeName:a,path:dn.path,onClose:()=>fn(null),onOpen:ye,onOpenToSide:e=>window.dispatchEvent(new CustomEvent(`workspace:open-to-side`,{detail:{workspaceName:o,treeName:a,path:e}})),pastedDocumentIds:w,onPasteDocuments:x?(e,t)=>x(e,t):void 0})]})}function Lm(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,fo.createRoot)(t);n.render((0,Y.jsx)(pm,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},onImport:e}))}function Rm(e){let t=window.document.createElement(`div`);window.document.body.appendChild(t);let n=(0,fo.createRoot)(t);n.render((0,Y.jsx)(fm,{isOpen:!0,onClose:()=>{n.unmount(),t.remove()},documents:e,selectedDocuments:new Set}))}export{Cd as $,da as $n,Fs as $t,fp as A,Ro as An,Sl as At,vf as B,mo as Bn,Xs as Bt,Dp as C,Zo as Cn,eu as Ct,vp as D,Eo as Dn,Gl as Dt,yp as E,qo as En,ql as Et,Uf as F,bo as Fn,wc as Ft,kd as G,xi as Gn,rc as Gt,nf as H,pr as Hn,Zs as Ht,Gf as I,Ko as In,uc as It,Ed as J,sa as Jn,oc as Jt,Od as K,oa as Kn,ic as Kt,Lf as L,Oo as Ln,hc as Lt,qf as M,Xo as Mn,Lc as Mt,Kf as N,No as Nn,Ec as Nt,hp as O,To as On,Vl as Ot,Jf as P,Yo as Pn,Tc as Pt,Sd as Q,xr as Qn,Is as Qt,Mf as R,Mo as Rn,mc as Rt,Ep as S,yo as Sn,cu as St,bp as T,ko as Tn,$l as Tt,Xd as U,Xa as Un,$s as Ut,rf as V,uo as Vn,Ys as Vt,Dd as W,Za as Wn,Qs as Wt,wd as X,Si as Xn,Js as Xt,vd as Y,ca as Yn,ac as Yt,xd as Z,ua as Zn,Gs as Zt,wp as _,zo as _n,iu as _t,im as a,bs as an,ro as ar,Bu as at,Op as b,Qo as bn,lu as bt,tm as c,ys as cn,ku as ct,$p as d,os as dn,Su as dt,js as en,Tr as er,Td as et,Gp as f,is as fn,wu as ft,Ap as g,Wo as gn,fu as gt,Pp as h,Jo as hn,pu as ht,cm as i,Ds as in,Ri as ir,Ju as it,Qf as j,Vo as jn,Rc as jt,mp as k,vo as kn,Ml as kt,Yp as l,ms as ln,Ou as lt,qp as m,es as mn,hu as mt,lm as n,As as nn,ji as nr,rd as nt,em as o,vs as on,Vu as ot,Kp as p,Ho as pn,gu as pt,Ad as q,bi as qn,qs as qt,sm as r,Ts as rn,Pi as rr,Qu as rt,Zp as s,_s as sn,Iu as st,Im as t,ks as tn,Sr as tr,hd as tt,Xp as u,ps as un,Du as ut,Sp as v,Po as vn,ou as vt,Cp as w,Bo as wn,nu as wt,Tp as x,Go as xn,au as xt,kp as y,xo as yn,uu as yt,Cf as z,ho as zn,pc as zt};
|